blob: 1d95615491b4cb7473d422fbf0a185ca98792932 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -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 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Alex Lighteb7c1442015-08-31 13:17:42 -070019#include <algorithm>
Brian Carlstromdbc05252011-09-09 01:59:59 -070020#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070021#include <iostream>
Vladimir Marko21300532017-01-24 18:06:55 +000022#include <map>
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070024#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070025#include <string>
Alex Lighteb7c1442015-08-31 13:17:42 -070026#include <tuple>
Andreas Gampea696c0a2014-12-10 20:51:45 -080027#include <unistd.h>
Alex Lighteb7c1442015-08-31 13:17:42 -070028#include <unordered_map>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070029#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070030#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070031
Andreas Gampe46ee31b2016-12-14 10:11:49 -080032#include "android-base/stringprintf.h"
33
Mathieu Chartierc7853442015-03-27 14:35:38 -070034#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070035#include "art_method-inl.h"
36#include "base/arena_allocator.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080037#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080038#include "base/logging.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070039#include "base/scoped_arena_containers.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010040#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080041#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080042#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010043#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080044#include "base/unix_file/fd_file.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070045#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070046#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080047#include "class_linker-inl.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070048#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000049#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080050#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070051#include "dex_file-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070052#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070053#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070054#include "experimental_flags.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070055#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070056#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080057#include "gc/accounting/heap_bitmap-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070058#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070059#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070060#include "gc/space/image_space.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070061#include "handle_scope-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080062#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070063#include "imt_conflict_table.h"
64#include "imtable-inl.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070065#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070066#include "interpreter/interpreter.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080067#include "jit/jit.h"
68#include "jit/jit_code_cache.h"
Calin Juravle33083d62017-01-18 15:29:12 -080069#include "jit/profile_compilation_info.h"
Andreas Gampe08883de2016-11-08 13:20:52 -080070#include "jni_internal.h"
Ian Rogers0571d352011-11-03 19:51:38 -070071#include "leb128.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070072#include "linear_alloc.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000073#include "mirror/call_site.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080074#include "mirror/class.h"
75#include "mirror/class-inl.h"
Alex Lightd6251582016-10-31 11:12:30 -070076#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080077#include "mirror/class_loader.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070078#include "mirror/dex_cache.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070079#include "mirror/dex_cache-inl.h"
Narayan Kamath000e1882016-10-24 17:14:25 +010080#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070081#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080082#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070083#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +010084#include "mirror/method_type.h"
85#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000086#include "mirror/method_handles_lookup.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080087#include "mirror/object-inl.h"
88#include "mirror/object_array-inl.h"
89#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070090#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080091#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070092#include "mirror/string-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070093#include "native/dalvik_system_DexFile.h"
94#include "oat.h"
95#include "oat_file.h"
96#include "oat_file-inl.h"
97#include "oat_file_assistant.h"
98#include "oat_file_manager.h"
99#include "object_lock.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800100#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700101#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800102#include "runtime_callbacks.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700103#include "ScopedLocalRef.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700104#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700105#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700106#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700107#include "trace.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700108#include "utils.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100109#include "utils/dex_cache_arrays_layout-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800110#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700111#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700112
113namespace art {
114
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800115using android::base::StringPrintf;
116
Mathieu Chartierc7853442015-03-27 14:35:38 -0700117static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700118static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700119
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700120static void ThrowNoClassDefFoundError(const char* fmt, ...)
121 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700122 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700123static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700124 va_list args;
125 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800126 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000127 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800128 va_end(args);
129}
130
Andreas Gampe99babb62015-11-02 16:20:00 -0800131static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700132 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700133 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700134 StackHandleScope<1> hs(self);
135 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700136 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700137 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700138
139 if (exception_class == nullptr) {
140 // No exc class ~ no <init>-with-string.
141 CHECK(self->IsExceptionPending());
142 self->ClearException();
143 return false;
144 }
145
Mathieu Chartiere401d142015-04-22 13:56:20 -0700146 ArtMethod* exception_init_method = exception_class->FindDeclaredDirectMethod(
Andreas Gampe99babb62015-11-02 16:20:00 -0800147 "<init>", "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700148 return exception_init_method != nullptr;
149}
150
Alex Lightd6251582016-10-31 11:12:30 -0700151static mirror::Object* GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700152 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700153 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
154 if (ext == nullptr) {
155 return nullptr;
156 } else {
157 return ext->GetVerifyError();
158 }
159}
160
161// Helper for ThrowEarlierClassFailure. Throws the stored error.
162static void HandleEarlierVerifyError(Thread* self,
163 ClassLinker* class_linker,
164 ObjPtr<mirror::Class> c)
165 REQUIRES_SHARED(Locks::mutator_lock_) {
166 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800167 DCHECK(obj != nullptr);
168 self->AssertNoPendingException();
169 if (obj->IsClass()) {
170 // Previous error has been stored as class. Create a new exception of that type.
171
172 // It's possible the exception doesn't have a <init>(String).
173 std::string temp;
174 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
175
176 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700177 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800178 } else {
179 self->ThrowNewException(descriptor, nullptr);
180 }
181 } else {
182 // Previous error has been stored as an instance. Just rethrow.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700183 ObjPtr<mirror::Class> throwable_class =
Andreas Gampe99babb62015-11-02 16:20:00 -0800184 self->DecodeJObject(WellKnownClasses::java_lang_Throwable)->AsClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700185 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800186 CHECK(throwable_class->IsAssignableFrom(error_class));
187 self->SetException(obj->AsThrowable());
188 }
189 self->AssertPendingException();
190}
191
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700192void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c, bool wrap_in_no_class_def) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700193 // The class failed to initialize on a previous attempt, so we want to throw
194 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
195 // failed in verification, in which case v2 5.4.1 says we need to re-throw
196 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800197 Runtime* const runtime = Runtime::Current();
198 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700199 std::string extra;
Alex Lightd6251582016-10-31 11:12:30 -0700200 if (GetVerifyError(c) != nullptr) {
201 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
Andreas Gampe369c8512016-01-28 15:31:39 -0800202 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700203 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800204 } else {
205 extra = verify_error->AsThrowable()->Dump();
206 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700207 }
David Sehr709b0702016-10-13 09:12:37 -0700208 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
209 << ": " << extra;
Ian Rogers87e552d2012-08-31 15:54:48 -0700210 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700211
David Sehr709b0702016-10-13 09:12:37 -0700212 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800213 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800214 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700215 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700216 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000217 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700218 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700219 if (GetVerifyError(c) != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800220 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800221 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800222 }
Alex Lightd6251582016-10-31 11:12:30 -0700223 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
224 // might have meant to go down the earlier if statement with the original error but it got
225 // swallowed by the OOM so we end up here.
226 if (GetVerifyError(c) == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800227 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
228 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
229 // exception will be a cause.
230 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700231 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700232 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700233 }
234}
235
Brian Carlstromb23eab12014-10-08 17:55:21 -0700236static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700237 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700238 if (VLOG_IS_ON(class_linker)) {
239 std::string temp;
240 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000241 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700242 }
243}
244
245static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700246 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700247 Thread* self = Thread::Current();
248 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700249
250 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700251 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700252
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800253 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
254 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
255 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800256 std::string tmp;
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800257 LOG(kIsDebugBuild ? FATAL : WARNING) << klass->GetDescriptor(&tmp) << " failed initialization";
Andreas Gampe22f71d22016-11-21 10:10:08 -0800258 }
259
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700260 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700261 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
262 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700263
Elliott Hughesa4f94742012-05-29 16:28:38 -0700264 // We only wrap non-Error exceptions; an Error can just be used as-is.
265 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000266 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700267 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700268 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700269}
270
Fred Shih381e4ca2014-08-25 17:24:27 -0700271// Gap between two fields in object layout.
272struct FieldGap {
273 uint32_t start_offset; // The offset from the start of the object.
274 uint32_t size; // The gap size of 1, 2, or 4 bytes.
275};
276struct FieldGapsComparator {
277 explicit FieldGapsComparator() {
278 }
279 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
280 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800281 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700282 // Note that the priority queue returns the largest element, so operator()
283 // should return true if lhs is less than rhs.
284 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700285 }
286};
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700287typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
Fred Shih381e4ca2014-08-25 17:24:27 -0700288
289// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800290static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700291 DCHECK(gaps != nullptr);
292
293 uint32_t current_offset = gap_start;
294 while (current_offset != gap_end) {
295 size_t remaining = gap_end - current_offset;
296 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
297 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
298 current_offset += sizeof(uint32_t);
299 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
300 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
301 current_offset += sizeof(uint16_t);
302 } else {
303 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
304 current_offset += sizeof(uint8_t);
305 }
306 DCHECK_LE(current_offset, gap_end) << "Overran gap";
307 }
308}
309// Shuffle fields forward, making use of gaps whenever possible.
310template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000311static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700312 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700313 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700314 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700315 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700316 DCHECK(current_field_idx != nullptr);
317 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700318 DCHECK(gaps != nullptr);
319 DCHECK(field_offset != nullptr);
320
321 DCHECK(IsPowerOfTwo(n));
322 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700323 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700324 Primitive::Type type = field->GetTypeAsPrimitiveType();
325 if (Primitive::ComponentSize(type) < n) {
326 break;
327 }
328 if (!IsAligned<n>(field_offset->Uint32Value())) {
329 MemberOffset old_offset = *field_offset;
330 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
331 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
332 }
David Sehr709b0702016-10-13 09:12:37 -0700333 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700334 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700335 if (!gaps->empty() && gaps->top().size >= n) {
336 FieldGap gap = gaps->top();
337 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100338 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700339 field->SetOffset(MemberOffset(gap.start_offset));
340 if (gap.size > n) {
341 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
342 }
343 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100344 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700345 field->SetOffset(*field_offset);
346 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
347 }
348 ++(*current_field_idx);
349 }
350}
351
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800352ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampecc1b5352016-12-01 16:58:38 -0800353 : failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800354 class_roots_(nullptr),
355 array_iftable_(nullptr),
356 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700357 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000358 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700359 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800360 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800361 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100362 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800363 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampe542451c2016-07-26 09:02:02 -0700364 image_pointer_size_(kRuntimePointerSize) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700365 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700366 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
367 "Array cache size wrong.");
368 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700369}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700370
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800371void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700372 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800373 if (c2 == nullptr) {
374 LOG(FATAL) << "Could not find class " << descriptor;
375 UNREACHABLE();
376 }
377 if (c1.Get() != c2) {
378 std::ostringstream os1, os2;
379 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
380 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
381 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
382 << ". This is most likely the result of a broken build. Make sure that "
383 << "libcore and art projects match.\n\n"
384 << os1.str() << "\n\n" << os2.str();
385 UNREACHABLE();
386 }
387}
388
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800389bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
390 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800391 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700392
Mathieu Chartiere401d142015-04-22 13:56:20 -0700393 Thread* const self = Thread::Current();
394 Runtime* const runtime = Runtime::Current();
395 gc::Heap* const heap = runtime->GetHeap();
396
Jeff Haodcdc85b2015-12-04 14:06:18 -0800397 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700398 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700399
Mathieu Chartiere401d142015-04-22 13:56:20 -0700400 // Use the pointer size from the runtime since we are probably creating the image.
401 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
402
Elliott Hughes30646832011-10-13 16:59:46 -0700403 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700404 // The GC can't handle an object with a null class since we can't get the size of this object.
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800405 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700406 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700407 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700408 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700409 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800410 CHECK(java_lang_Class != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700411 mirror::Class::SetClassClass(java_lang_Class.Get());
412 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700413 if (kUseBakerReadBarrier) {
414 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800415 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700416 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700417 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800418 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700419 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700420
Elliott Hughes418d20f2011-09-22 14:00:39 -0700421 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700422 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700423 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700424 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700425 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700426
Ian Rogers23435d02012-09-24 11:23:12 -0700427 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700428 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700429 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800430 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700431 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700432 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700433 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700434
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700435 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800436 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
437 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
438 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
439 java_lang_Object.Get(),
440 java_lang_Object->GetObjectSize(),
441 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700442
Ian Rogers23435d02012-09-24 11:23:12 -0700443 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700444 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700445 AllocClass(self, java_lang_Class.Get(),
446 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700447 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700448
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700449 // Setup the char (primitive) class to be used for char[].
450 Handle<mirror::Class> char_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700451 AllocClass(self, java_lang_Class.Get(),
452 mirror::Class::PrimitiveClassSize(image_pointer_size_))));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700453 // The primitive char class won't be initialized by
454 // InitializePrimitiveClass until line 459, but strings (and
455 // internal char arrays) will be allocated before that and the
456 // component size, which is computed from the primitive type, needs
457 // to be set here.
458 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700459
Ian Rogers23435d02012-09-24 11:23:12 -0700460 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700461 Handle<mirror::Class> char_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700462 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700463 char_array_class->SetComponentType(char_class.Get());
464 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700465
Ian Rogers23435d02012-09-24 11:23:12 -0700466 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700467 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700468 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700469 java_lang_String->SetStringClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700470 mirror::String::SetClass(java_lang_String.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700471 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400472
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700473 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700474 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700475 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700476 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
477 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700478 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700479
Ian Rogers23435d02012-09-24 11:23:12 -0700480 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700481 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700482 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
483 kClassRootsMax));
484 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700485 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
486 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
487 SetClassRoot(kClassArrayClass, class_array_class.Get());
488 SetClassRoot(kObjectArrayClass, object_array_class.Get());
489 SetClassRoot(kCharArrayClass, char_array_class.Get());
490 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700491 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700492
Mathieu Chartier6beced42016-11-15 15:51:31 -0800493 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
494 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
495
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700496 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700497 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
498 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
499 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
500 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
501 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
502 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
503 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
504 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700505
Ian Rogers23435d02012-09-24 11:23:12 -0700506 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700507 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700508
Ian Rogers23435d02012-09-24 11:23:12 -0700509 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700510 Handle<mirror::Class> int_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700511 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700512 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700513 mirror::IntArray::SetArrayClass(int_array_class.Get());
514 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700515
Mathieu Chartierc7853442015-03-27 14:35:38 -0700516 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
517 Handle<mirror::Class> long_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700518 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700519 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
520 mirror::LongArray::SetArrayClass(long_array_class.Get());
521 SetClassRoot(kLongArrayClass, long_array_class.Get());
522
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700523 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700524
Ian Rogers52813c92012-10-11 11:50:38 -0700525 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700526 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700527 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700528 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100529 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700530 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700531 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700532
Alex Lightd6251582016-10-31 11:12:30 -0700533
534 // Setup dalvik.system.ClassExt
535 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
536 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
537 SetClassRoot(kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
538 mirror::ClassExt::SetClass(dalvik_system_ClassExt.Get());
539 mirror::Class::SetStatus(dalvik_system_ClassExt, mirror::Class::kStatusResolved, self);
540
Mathieu Chartier66f19252012-09-18 08:57:04 -0700541 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700542 Handle<mirror::Class> object_array_string(hs.NewHandle(
543 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700544 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700545 object_array_string->SetComponentType(java_lang_String.Get());
546 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700547
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000548 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700549 // Create runtime resolution and imt conflict methods.
550 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000551 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
552 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700553
Ian Rogers23435d02012-09-24 11:23:12 -0700554 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
555 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
556 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800557 if (boot_class_path.empty()) {
558 *error_msg = "Boot classpath is empty.";
559 return false;
560 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800561 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800562 if (dex_file.get() == nullptr) {
563 *error_msg = "Null dex file.";
564 return false;
565 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700566 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800567 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700568 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700569
570 // now we can use FindSystemClass
571
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700572 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700573 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
574 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700575
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700576 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
577 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700578 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800579 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700580 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700581 quick_resolution_trampoline_ = GetQuickResolutionStub();
582 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
583 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700584 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700585
Alex Lightd6251582016-10-31 11:12:30 -0700586 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700587 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800588 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700589 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700590 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800591 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700592 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800593 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700594 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Alex Lightd6251582016-10-31 11:12:30 -0700595 mirror::Class::SetStatus(dalvik_system_ClassExt, mirror::Class::kStatusNotReady, self);
596 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
597 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700598
Ian Rogers23435d02012-09-24 11:23:12 -0700599 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800600 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800601 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700602
Ian Rogers98379392014-02-24 16:53:16 -0800603 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800604 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700605
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800606 CheckSystemClass(self, char_array_class, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700607
Ian Rogers98379392014-02-24 16:53:16 -0800608 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800609 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700610
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800611 CheckSystemClass(self, int_array_class, "[I");
612 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700613
Ian Rogers98379392014-02-24 16:53:16 -0800614 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800615 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700616
Ian Rogers98379392014-02-24 16:53:16 -0800617 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800618 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700619
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800620 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
621 // in class_table_.
622 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700623
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800624 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
625 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700626
Ian Rogers23435d02012-09-24 11:23:12 -0700627 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700628 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800629 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700630 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800631 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700632 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
633 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700634 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
635 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700636
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700637 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
638 // suspension.
639 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000640 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700641 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000642 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700643 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000644 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700645 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000646 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700647
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700648 CHECK_EQ(object_array_string.Get(),
649 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700650
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800651 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700652
Ian Rogers23435d02012-09-24 11:23:12 -0700653 // Create java.lang.reflect.Proxy root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700654 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700655
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700656 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700657 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
658 CHECK(class_root != nullptr);
659 SetClassRoot(kJavaLangReflectField, class_root);
660 mirror::Field::SetClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700661
662 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700663 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
664 CHECK(class_root != nullptr);
665 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
666 mirror::Field::SetArrayClass(class_root);
667
668 // Create java.lang.reflect.Constructor.class root and array root.
669 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
670 CHECK(class_root != nullptr);
671 SetClassRoot(kJavaLangReflectConstructor, class_root);
672 mirror::Constructor::SetClass(class_root);
673 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
674 CHECK(class_root != nullptr);
675 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
676 mirror::Constructor::SetArrayClass(class_root);
677
678 // Create java.lang.reflect.Method.class root and array root.
679 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
680 CHECK(class_root != nullptr);
681 SetClassRoot(kJavaLangReflectMethod, class_root);
682 mirror::Method::SetClass(class_root);
683 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
684 CHECK(class_root != nullptr);
685 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
686 mirror::Method::SetArrayClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700687
Narayan Kamathafa48272016-08-03 12:46:58 +0100688 // Create java.lang.invoke.MethodType.class root
689 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
690 CHECK(class_root != nullptr);
691 SetClassRoot(kJavaLangInvokeMethodType, class_root);
692 mirror::MethodType::SetClass(class_root);
693
694 // Create java.lang.invoke.MethodHandleImpl.class root
695 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
696 CHECK(class_root != nullptr);
697 SetClassRoot(kJavaLangInvokeMethodHandleImpl, class_root);
698 mirror::MethodHandleImpl::SetClass(class_root);
699
Orion Hodsonc069a302017-01-18 09:23:12 +0000700 // Create java.lang.invoke.MethodHandles.Lookup.class root
701 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
702 CHECK(class_root != nullptr);
703 SetClassRoot(kJavaLangInvokeMethodHandlesLookup, class_root);
704 mirror::MethodHandlesLookup::SetClass(class_root);
705
706 // Create java.lang.invoke.CallSite.class root
707 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
708 CHECK(class_root != nullptr);
709 SetClassRoot(kJavaLangInvokeCallSite, class_root);
710 mirror::CallSite::SetClass(class_root);
711
Narayan Kamath000e1882016-10-24 17:14:25 +0100712 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
713 CHECK(class_root != nullptr);
714 SetClassRoot(kDalvikSystemEmulatedStackFrame, class_root);
715 mirror::EmulatedStackFrame::SetClass(class_root);
716
Brian Carlstrom1f870082011-08-23 16:02:11 -0700717 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700718 // finish initializing Reference class
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700719 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800720 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700721 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700722 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
723 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700724 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700725 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700726 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700727 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700728 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700729 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700730 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700731 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700732 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700733 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700734 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700735 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700736
Ian Rogers23435d02012-09-24 11:23:12 -0700737 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700738 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700739 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700740 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
741 SetClassRoot(kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700742
jeffhao8cd6dda2012-02-22 10:15:34 -0800743 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700744 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800745 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800746 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700747 SetClassRoot(kJavaLangClassNotFoundException,
748 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800749 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700750 SetClassRoot(kJavaLangStackTraceElementArrayClass,
751 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800752 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700753
Andreas Gampe76bd8802014-12-10 16:43:58 -0800754 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
755 // initialized.
756 {
757 const DexFile& dex_file = java_lang_Object->GetDexFile();
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700758 const DexFile::TypeId* void_type_id = dex_file.FindTypeId("V");
Andreas Gampe76bd8802014-12-10 16:43:58 -0800759 CHECK(void_type_id != nullptr);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800760 dex::TypeIndex void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
Andreas Gampe76bd8802014-12-10 16:43:58 -0800761 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
762 // as referrer so the used dex cache is core's one.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800763 ObjPtr<mirror::Class> resolved_type = ResolveType(dex_file,
764 void_type_idx,
765 java_lang_Object.Get());
Andreas Gampe76bd8802014-12-10 16:43:58 -0800766 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
767 self->AssertNoPendingException();
768 }
769
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700770 // Create conflict tables that depend on the class linker.
771 runtime->FixupConflictTables();
772
Ian Rogers98379392014-02-24 16:53:16 -0800773 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700774
Brian Carlstroma004aa92012-02-08 18:05:09 -0800775 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800776
777 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700778}
779
Ian Rogers98379392014-02-24 16:53:16 -0800780void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800781 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700782
783 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700784 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700785 // as the types of the field can't be resolved prior to the runtime being
786 // fully initialized
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700787 StackHandleScope<2> hs(self);
788 Handle<mirror::Class> java_lang_ref_Reference = hs.NewHandle(GetClassRoot(kJavaLangRefReference));
789 Handle<mirror::Class> java_lang_ref_FinalizerReference =
790 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800791
Mathieu Chartierc7853442015-03-27 14:35:38 -0700792 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700793 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
794 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700795
Mathieu Chartierc7853442015-03-27 14:35:38 -0700796 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700797 CHECK_STREQ(queue->GetName(), "queue");
798 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700799
Mathieu Chartierc7853442015-03-27 14:35:38 -0700800 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700801 CHECK_STREQ(queueNext->GetName(), "queueNext");
802 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700803
Mathieu Chartierc7853442015-03-27 14:35:38 -0700804 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700805 CHECK_STREQ(referent->GetName(), "referent");
806 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700807
Mathieu Chartierc7853442015-03-27 14:35:38 -0700808 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700809 CHECK_STREQ(zombie->GetName(), "zombie");
810 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700811
Brian Carlstroma663ea52011-08-19 23:33:41 -0700812 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700813 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700814 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700815 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700816 CHECK(klass != nullptr);
817 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700818 // note SetClassRoot does additional validation.
819 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700820 }
821
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700822 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700823
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700824 // disable the slow paths in FindClass and CreatePrimitiveClass now
825 // that Object, Class, and Object[] are setup
826 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700827
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800828 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700829}
830
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700831void ClassLinker::RunRootClinits() {
832 Thread* self = Thread::Current();
833 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700834 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700835 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700836 StackHandleScope<1> hs(self);
837 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700838 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700839 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700840 }
841 }
842}
843
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200844// Set image methods' entry point to interpreter.
845class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
846 public:
Andreas Gampe542451c2016-07-26 09:02:02 -0700847 explicit SetInterpreterEntrypointArtMethodVisitor(PointerSize image_pointer_size)
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200848 : image_pointer_size_(image_pointer_size) {}
849
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700850 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200851 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
852 CHECK(method->GetDeclaringClass() != nullptr);
853 }
854 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
855 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
856 image_pointer_size_);
857 }
858 }
859
860 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700861 const PointerSize image_pointer_size_;
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200862
863 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
864};
865
Jeff Haodcdc85b2015-12-04 14:06:18 -0800866struct TrampolineCheckData {
867 const void* quick_resolution_trampoline;
868 const void* quick_imt_conflict_trampoline;
869 const void* quick_generic_jni_trampoline;
870 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700871 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800872 ArtMethod* m;
873 bool error;
874};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800875
Jeff Haodcdc85b2015-12-04 14:06:18 -0800876static void CheckTrampolines(mirror::Object* obj, void* arg) NO_THREAD_SAFETY_ANALYSIS {
877 if (obj->IsClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700878 ObjPtr<mirror::Class> klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800879 TrampolineCheckData* d = reinterpret_cast<TrampolineCheckData*>(arg);
880 for (ArtMethod& m : klass->GetMethods(d->pointer_size)) {
881 const void* entrypoint = m.GetEntryPointFromQuickCompiledCodePtrSize(d->pointer_size);
882 if (entrypoint == d->quick_resolution_trampoline ||
883 entrypoint == d->quick_imt_conflict_trampoline ||
884 entrypoint == d->quick_generic_jni_trampoline ||
885 entrypoint == d->quick_to_interpreter_bridge_trampoline) {
886 d->m = &m;
887 d->error = true;
888 return;
889 }
890 }
891 }
892}
893
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800894bool ClassLinker::InitFromBootImage(std::string* error_msg) {
895 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700896 CHECK(!init_done_);
897
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700898 Runtime* const runtime = Runtime::Current();
899 Thread* const self = Thread::Current();
900 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800901 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
902 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700903 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
904 if (!ValidPointerSize(pointer_size_unchecked)) {
905 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800906 return false;
907 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700908 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800909 if (!runtime->IsAotCompiler()) {
910 // Only the Aot compiler supports having an image with a different pointer size than the
911 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
912 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700913 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800914 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700915 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800916 sizeof(void*));
917 return false;
918 }
919 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800920 std::vector<const OatFile*> oat_files =
921 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
922 DCHECK(!oat_files.empty());
923 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
924 CHECK_EQ(default_oat_header.GetImageFileLocationOatChecksum(), 0U);
925 CHECK_EQ(default_oat_header.GetImageFileLocationOatDataBegin(), 0U);
926 const char* image_file_location = oat_files[0]->GetOatHeader().
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700927 GetStoreValueByKey(OatHeader::kImageLocationKey);
928 CHECK(image_file_location == nullptr || *image_file_location == 0);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800929 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
930 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
931 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
932 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
933 if (kIsDebugBuild) {
934 // Check that the other images use the same trampoline.
935 for (size_t i = 1; i < oat_files.size(); ++i) {
936 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
937 const void* ith_quick_resolution_trampoline =
938 ith_oat_header.GetQuickResolutionTrampoline();
939 const void* ith_quick_imt_conflict_trampoline =
940 ith_oat_header.GetQuickImtConflictTrampoline();
941 const void* ith_quick_generic_jni_trampoline =
942 ith_oat_header.GetQuickGenericJniTrampoline();
943 const void* ith_quick_to_interpreter_bridge_trampoline =
944 ith_oat_header.GetQuickToInterpreterBridge();
945 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
946 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
947 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
948 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
949 // Make sure that all methods in this image do not contain those trampolines as
950 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
951 TrampolineCheckData data;
952 data.error = false;
953 data.pointer_size = GetImagePointerSize();
954 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
955 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
956 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
957 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
958 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
959 spaces[i]->GetLiveBitmap()->Walk(CheckTrampolines, &data);
960 if (data.error) {
961 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -0700962 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800963 *error_msg = "Found an ArtMethod with a bad entrypoint";
964 return false;
965 }
966 }
967 }
968 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700969
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800970 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
971 down_cast<mirror::ObjectArray<mirror::Class>*>(
972 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)));
973 mirror::Class::SetClassClass(class_roots_.Read()->Get(kJavaLangClass));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700974
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700975 // Special case of setting up the String class early so that we can test arbitrary objects
976 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700977 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800978
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700979 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot(kJavaLangObject);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700980 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800981 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
982 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800983 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
984 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700985
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800986 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700987 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800988 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800989 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700990 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
991 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700992 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
993 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
994 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
995 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
Narayan Kamathafa48272016-08-03 12:46:58 +0100996 mirror::MethodType::SetClass(GetClassRoot(kJavaLangInvokeMethodType));
997 mirror::MethodHandleImpl::SetClass(GetClassRoot(kJavaLangInvokeMethodHandleImpl));
Orion Hodsonc069a302017-01-18 09:23:12 +0000998 mirror::MethodHandlesLookup::SetClass(GetClassRoot(kJavaLangInvokeMethodHandlesLookup));
999 mirror::CallSite::SetClass(GetClassRoot(kJavaLangInvokeCallSite));
Fred Shih4ee7a662014-07-11 09:59:27 -07001000 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001001 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1002 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1003 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1004 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1005 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1006 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1007 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1008 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1009 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1010 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Narayan Kamath000e1882016-10-24 17:14:25 +01001011 mirror::EmulatedStackFrame::SetClass(GetClassRoot(kDalvikSystemEmulatedStackFrame));
Alex Lightd6251582016-10-31 11:12:30 -07001012 mirror::ClassExt::SetClass(GetClassRoot(kDalvikSystemClassExt));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001013
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001014 for (gc::space::ImageSpace* image_space : spaces) {
1015 // Boot class loader, use a null handle.
1016 std::vector<std::unique_ptr<const DexFile>> dex_files;
1017 if (!AddImageSpace(image_space,
1018 ScopedNullHandle<mirror::ClassLoader>(),
1019 /*dex_elements*/nullptr,
1020 /*dex_location*/nullptr,
1021 /*out*/&dex_files,
1022 error_msg)) {
1023 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001024 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001025 // Append opened dex files at the end.
1026 boot_dex_files_.insert(boot_dex_files_.end(),
1027 std::make_move_iterator(dex_files.begin()),
1028 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001029 }
Ian Rogers98379392014-02-24 16:53:16 -08001030 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001031
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001032 VLOG(startup) << __FUNCTION__ << " exiting";
1033 return true;
1034}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001035
Jeff Hao5872d7c2016-04-27 11:07:41 -07001036bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001037 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001038 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001039 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1040 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001041}
1042
Andreas Gampe08883de2016-11-08 13:20:52 -08001043static mirror::String* GetDexPathListElementName(ObjPtr<mirror::Object> element)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001044 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001045 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001046 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001047 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001048 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001049 DCHECK(dex_file_field != nullptr);
1050 DCHECK(dex_file_name_field != nullptr);
1051 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001052 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001053 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001054 if (dex_file == nullptr) {
1055 return nullptr;
1056 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001057 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001058 if (name_object != nullptr) {
1059 return name_object->AsString();
1060 }
1061 return nullptr;
1062}
1063
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001064static bool FlattenPathClassLoader(ObjPtr<mirror::ClassLoader> class_loader,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001065 std::list<mirror::String*>* out_dex_file_names,
1066 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001067 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001068 DCHECK(out_dex_file_names != nullptr);
1069 DCHECK(error_msg != nullptr);
1070 ScopedObjectAccessUnchecked soa(Thread::Current());
1071 ArtField* const dex_path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001072 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001073 ArtField* const dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001074 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001075 CHECK(dex_path_list_field != nullptr);
1076 CHECK(dex_elements_field != nullptr);
Jeff Hao5872d7c2016-04-27 11:07:41 -07001077 while (!ClassLinker::IsBootClassLoader(soa, class_loader)) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07001078 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1079 class_loader->GetClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001080 *error_msg = StringPrintf("Unknown class loader type %s",
1081 class_loader->PrettyTypeOf().c_str());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001082 // Unsupported class loader.
1083 return false;
1084 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001085 ObjPtr<mirror::Object> dex_path_list = dex_path_list_field->GetObject(class_loader);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001086 if (dex_path_list != nullptr) {
1087 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
Mathieu Chartier3398c782016-09-30 10:27:43 -07001088 ObjPtr<mirror::Object> dex_elements_obj = dex_elements_field->GetObject(dex_path_list);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001089 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1090 // at the mCookie which is a DexFile vector.
1091 if (dex_elements_obj != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001092 ObjPtr<mirror::ObjectArray<mirror::Object>> dex_elements =
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001093 dex_elements_obj->AsObjectArray<mirror::Object>();
1094 // Reverse order since we insert the parent at the front.
1095 for (int32_t i = dex_elements->GetLength() - 1; i >= 0; --i) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001096 ObjPtr<mirror::Object> element = dex_elements->GetWithoutChecks(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001097 if (element == nullptr) {
1098 *error_msg = StringPrintf("Null dex element at index %d", i);
1099 return false;
1100 }
Andreas Gampe08883de2016-11-08 13:20:52 -08001101 ObjPtr<mirror::String> const name = GetDexPathListElementName(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001102 if (name == nullptr) {
1103 *error_msg = StringPrintf("Null name for dex element at index %d", i);
1104 return false;
1105 }
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001106 out_dex_file_names->push_front(name.Ptr());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001107 }
1108 }
1109 }
1110 class_loader = class_loader->GetParent();
1111 }
1112 return true;
1113}
1114
1115class FixupArtMethodArrayVisitor : public ArtMethodVisitor {
1116 public:
1117 explicit FixupArtMethodArrayVisitor(const ImageHeader& header) : header_(header) {}
1118
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001119 virtual void Visit(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light36121492016-02-22 13:43:29 -08001120 const bool is_copied = method->IsCopied();
Andreas Gampe542451c2016-07-26 09:02:02 -07001121 ArtMethod** resolved_methods = method->GetDexCacheResolvedMethods(kRuntimePointerSize);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001122 if (resolved_methods != nullptr) {
1123 bool in_image_space = false;
Alex Light36121492016-02-22 13:43:29 -08001124 if (kIsDebugBuild || is_copied) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001125 in_image_space = header_.GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains(
1126 reinterpret_cast<const uint8_t*>(resolved_methods) - header_.GetImageBegin());
1127 }
1128 // Must be in image space for non-miranda method.
Alex Light36121492016-02-22 13:43:29 -08001129 DCHECK(is_copied || in_image_space)
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001130 << resolved_methods << " is not in image starting at "
1131 << reinterpret_cast<void*>(header_.GetImageBegin());
Alex Light36121492016-02-22 13:43:29 -08001132 if (!is_copied || in_image_space) {
Vladimir Marko6dd14882016-10-25 11:51:35 +01001133 method->SetDexCacheResolvedMethods(method->GetDexCache()->GetResolvedMethods(),
Andreas Gampe542451c2016-07-26 09:02:02 -07001134 kRuntimePointerSize);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001135 }
1136 }
1137 }
1138
1139 private:
1140 const ImageHeader& header_;
1141};
1142
1143class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1144 public:
1145 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1146
1147 virtual void Visit(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001148 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001149 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001150 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
David Sehr709b0702016-10-13 09:12:37 -07001151 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << mirror::Class::PrettyClass(klass);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001152 }
1153 }
1154
1155 private:
1156 ClassTable* const table_;
1157};
1158
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001159class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1160 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001161 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001162 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1163
1164 virtual void Visit(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001165 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001166 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked();
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001167 if (klass != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001168 CHECK(live_bitmap_->Test(klass.Ptr())) << "Image method has unmarked declaring class";
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001169 }
1170 }
1171
1172 private:
1173 gc::accounting::HeapBitmap* const live_bitmap_;
1174};
1175
Artem Udovichenkob3ac45b2016-09-09 14:02:25 +03001176// Copies data from one array to another array at the same position
1177// if pred returns false. If there is a page of continuous data in
1178// the src array for which pred consistently returns true then
1179// corresponding page in the dst array will not be touched.
1180// This should reduce number of allocated physical pages.
1181template <class T, class NullPred>
1182static void CopyNonNull(const T* src, size_t count, T* dst, const NullPred& pred) {
1183 for (size_t i = 0; i < count; ++i) {
1184 if (!pred(src[i])) {
1185 dst[i] = src[i];
1186 }
1187 }
1188}
1189
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001190bool ClassLinker::UpdateAppImageClassLoadersAndDexCaches(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001191 gc::space::ImageSpace* space,
1192 Handle<mirror::ClassLoader> class_loader,
1193 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Mathieu Chartier69731002016-03-02 16:08:31 -08001194 ClassTable::ClassSet* new_class_set,
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001195 bool* out_forward_dex_cache_array,
1196 std::string* out_error_msg) {
1197 DCHECK(out_forward_dex_cache_array != nullptr);
1198 DCHECK(out_error_msg != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001199 Thread* const self = Thread::Current();
1200 gc::Heap* const heap = Runtime::Current()->GetHeap();
1201 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001202 {
1203 // Add image classes into the class table for the class loader, and fixup the dex caches and
1204 // class loader fields.
1205 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001206 // Dex cache array fixup is all or nothing, we must reject app images that have mixed since we
1207 // rely on clobering the dex cache arrays in the image to forward to bss.
1208 size_t num_dex_caches_with_bss_arrays = 0;
1209 const size_t num_dex_caches = dex_caches->GetLength();
1210 for (size_t i = 0; i < num_dex_caches; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001211 ObjPtr<mirror::DexCache> const dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001212 const DexFile* const dex_file = dex_cache->GetDexFile();
1213 const OatFile::OatDexFile* oat_dex_file = dex_file->GetOatDexFile();
1214 if (oat_dex_file != nullptr && oat_dex_file->GetDexCacheArrays() != nullptr) {
1215 ++num_dex_caches_with_bss_arrays;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001216 }
1217 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001218 *out_forward_dex_cache_array = num_dex_caches_with_bss_arrays != 0;
1219 if (*out_forward_dex_cache_array) {
1220 if (num_dex_caches_with_bss_arrays != num_dex_caches) {
1221 // Reject application image since we cannot forward only some of the dex cache arrays.
1222 // TODO: We could get around this by having a dedicated forwarding slot. It should be an
1223 // uncommon case.
1224 *out_error_msg = StringPrintf("Dex caches in bss does not match total: %zu vs %zu",
1225 num_dex_caches_with_bss_arrays,
1226 num_dex_caches);
1227 return false;
1228 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001229 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001230 // Only add the classes to the class loader after the points where we can return false.
1231 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001232 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001233 const DexFile* const dex_file = dex_cache->GetDexFile();
1234 const OatFile::OatDexFile* oat_dex_file = dex_file->GetOatDexFile();
1235 if (oat_dex_file != nullptr && oat_dex_file->GetDexCacheArrays() != nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01001236 // If the oat file expects the dex cache arrays to be in the BSS, then allocate there and
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001237 // copy over the arrays.
1238 DCHECK(dex_file != nullptr);
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001239 size_t num_strings = mirror::DexCache::kDexCacheStringCacheSize;
1240 if (dex_file->NumStringIds() < num_strings) {
1241 num_strings = dex_file->NumStringIds();
1242 }
Mathieu Chartier5812e202017-02-13 18:32:04 -08001243 const size_t num_types = dex_file->NumTypeIds();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001244 const size_t num_methods = dex_file->NumMethodIds();
1245 const size_t num_fields = dex_file->NumFieldIds();
Narayan Kamath269cb432016-10-28 10:19:54 +01001246 size_t num_method_types = mirror::DexCache::kDexCacheMethodTypeCacheSize;
1247 if (dex_file->NumProtoIds() < num_method_types) {
1248 num_method_types = dex_file->NumProtoIds();
Narayan Kamath25352fc2016-08-03 12:46:58 +01001249 }
Orion Hodsonc069a302017-01-18 09:23:12 +00001250 const size_t num_call_sites = dex_file->NumCallSiteIds();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001251 CHECK_EQ(num_strings, dex_cache->NumStrings());
1252 CHECK_EQ(num_types, dex_cache->NumResolvedTypes());
1253 CHECK_EQ(num_methods, dex_cache->NumResolvedMethods());
1254 CHECK_EQ(num_fields, dex_cache->NumResolvedFields());
Narayan Kamath25352fc2016-08-03 12:46:58 +01001255 CHECK_EQ(num_method_types, dex_cache->NumResolvedMethodTypes());
Orion Hodsonc069a302017-01-18 09:23:12 +00001256 CHECK_EQ(num_call_sites, dex_cache->NumResolvedCallSites());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001257 DexCacheArraysLayout layout(image_pointer_size_, dex_file);
1258 uint8_t* const raw_arrays = oat_dex_file->GetDexCacheArrays();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001259 if (num_strings != 0u) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001260 mirror::StringDexCacheType* const image_resolved_strings = dex_cache->GetStrings();
1261 mirror::StringDexCacheType* const strings =
1262 reinterpret_cast<mirror::StringDexCacheType*>(raw_arrays + layout.StringsOffset());
Mathieu Chartier5812e202017-02-13 18:32:04 -08001263 for (size_t j = 0; j < num_strings; ++j) {
1264 DCHECK_EQ(strings[j].load(std::memory_order_relaxed).index, 0u);
1265 DCHECK(strings[j].load(std::memory_order_relaxed).object.IsNull());
1266 strings[j].store(image_resolved_strings[j].load(std::memory_order_relaxed),
1267 std::memory_order_relaxed);
1268 }
1269 mirror::StringDexCachePair::Initialize(strings);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001270 dex_cache->SetStrings(strings);
1271 }
1272 if (num_types != 0u) {
Mathieu Chartier5812e202017-02-13 18:32:04 -08001273 GcRoot<mirror::Class>* const image_resolved_types = dex_cache->GetResolvedTypes();
1274 GcRoot<mirror::Class>* const types =
1275 reinterpret_cast<GcRoot<mirror::Class>*>(raw_arrays + layout.TypesOffset());
1276 for (size_t j = 0; kIsDebugBuild && j < num_types; ++j) {
1277 DCHECK(types[j].IsNull());
1278 }
1279 CopyNonNull(image_resolved_types,
1280 num_types,
1281 types,
1282 [](const GcRoot<mirror::Class>& elem) {
1283 return elem.IsNull();
1284 });
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001285 dex_cache->SetResolvedTypes(types);
1286 }
1287 if (num_methods != 0u) {
1288 ArtMethod** const methods = reinterpret_cast<ArtMethod**>(
1289 raw_arrays + layout.MethodsOffset());
1290 ArtMethod** const image_resolved_methods = dex_cache->GetResolvedMethods();
1291 for (size_t j = 0; kIsDebugBuild && j < num_methods; ++j) {
1292 DCHECK(methods[j] == nullptr);
1293 }
Artem Udovichenkob3ac45b2016-09-09 14:02:25 +03001294 CopyNonNull(image_resolved_methods,
1295 num_methods,
1296 methods,
1297 [] (const ArtMethod* method) {
1298 return method == nullptr;
1299 });
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001300 dex_cache->SetResolvedMethods(methods);
1301 }
1302 if (num_fields != 0u) {
1303 ArtField** const fields =
1304 reinterpret_cast<ArtField**>(raw_arrays + layout.FieldsOffset());
1305 for (size_t j = 0; kIsDebugBuild && j < num_fields; ++j) {
1306 DCHECK(fields[j] == nullptr);
1307 }
Artem Udovichenkob3ac45b2016-09-09 14:02:25 +03001308 CopyNonNull(dex_cache->GetResolvedFields(),
1309 num_fields,
1310 fields,
1311 [] (const ArtField* field) {
1312 return field == nullptr;
1313 });
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001314 dex_cache->SetResolvedFields(fields);
1315 }
Narayan Kamath25352fc2016-08-03 12:46:58 +01001316 if (num_method_types != 0u) {
1317 // NOTE: We currently (Sep 2016) do not resolve any method types at
1318 // compile time, but plan to in the future. This code exists for the
1319 // sake of completeness.
1320 mirror::MethodTypeDexCacheType* const image_resolved_method_types =
1321 dex_cache->GetResolvedMethodTypes();
1322 mirror::MethodTypeDexCacheType* const method_types =
1323 reinterpret_cast<mirror::MethodTypeDexCacheType*>(
1324 raw_arrays + layout.MethodTypesOffset());
Mathieu Chartier5812e202017-02-13 18:32:04 -08001325 for (size_t j = 0; j < num_method_types; ++j) {
1326 DCHECK_EQ(method_types[j].load(std::memory_order_relaxed).index, 0u);
1327 DCHECK(method_types[j].load(std::memory_order_relaxed).object.IsNull());
1328 method_types[j].store(
1329 image_resolved_method_types[j].load(std::memory_order_relaxed),
1330 std::memory_order_relaxed);
1331 }
1332
1333 mirror::MethodTypeDexCachePair::Initialize(method_types);
Narayan Kamath25352fc2016-08-03 12:46:58 +01001334 dex_cache->SetResolvedMethodTypes(method_types);
1335 }
Orion Hodsonc069a302017-01-18 09:23:12 +00001336 if (num_call_sites != 0u) {
1337 GcRoot<mirror::CallSite>* const image_resolved_call_sites =
1338 dex_cache->GetResolvedCallSites();
1339 GcRoot<mirror::CallSite>* const call_sites =
1340 reinterpret_cast<GcRoot<mirror::CallSite>*>(raw_arrays + layout.CallSitesOffset());
1341 for (size_t j = 0; kIsDebugBuild && j < num_call_sites; ++j) {
1342 DCHECK(call_sites[j].IsNull());
1343 }
1344 CopyNonNull(image_resolved_call_sites,
1345 num_call_sites,
1346 call_sites,
1347 [](const GcRoot<mirror::CallSite>& elem) {
1348 return elem.IsNull();
1349 });
1350 dex_cache->SetResolvedCallSites(call_sites);
1351 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001352 }
1353 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001354 WriterMutexLock mu2(self, *Locks::dex_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001355 // Make sure to do this after we update the arrays since we store the resolved types array
1356 // in DexCacheData in RegisterDexFileLocked. We need the array pointer to be the one in the
1357 // BSS.
Vladimir Markocd556b02017-02-03 11:47:34 +00001358 CHECK(!FindDexCacheDataLocked(*dex_file).IsValid());
1359 RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001360 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001361 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001362 CHECK(new_class_set != nullptr);
Mathieu Chartier5812e202017-02-13 18:32:04 -08001363 GcRoot<mirror::Class>* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001364 const size_t num_types = dex_cache->NumResolvedTypes();
Mathieu Chartier5812e202017-02-13 18:32:04 -08001365 for (int32_t j = 0; j < static_cast<int32_t>(num_types); j++) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001366 // The image space is not yet added to the heap, avoid read barriers.
Mathieu Chartier5812e202017-02-13 18:32:04 -08001367 ObjPtr<mirror::Class> klass = types[j].Read();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001368 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001369 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001370 auto it = new_class_set->Find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001371 DCHECK(it != new_class_set->end());
1372 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001373 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001374 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001375 auto it2 = new_class_set->Find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001376 DCHECK(it2 != new_class_set->end());
1377 DCHECK_EQ(it2->Read(), super_class);
1378 }
1379 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1380 const void* code = m.GetEntryPointFromQuickCompiledCode();
1381 const void* oat_code = m.IsInvokable() ? GetQuickOatCodeFor(&m) : code;
1382 if (!IsQuickResolutionStub(code) &&
1383 !IsQuickGenericJniStub(code) &&
1384 !IsQuickToInterpreterBridge(code) &&
1385 !m.IsNative()) {
David Sehr709b0702016-10-13 09:12:37 -07001386 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001387 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001388 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01001389 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1390 const void* code = m.GetEntryPointFromQuickCompiledCode();
1391 const void* oat_code = m.IsInvokable() ? GetQuickOatCodeFor(&m) : code;
1392 if (!IsQuickResolutionStub(code) &&
1393 !IsQuickGenericJniStub(code) &&
1394 !IsQuickToInterpreterBridge(code) &&
1395 !m.IsNative()) {
David Sehr709b0702016-10-13 09:12:37 -07001396 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001397 }
1398 }
1399 }
1400 }
1401 }
1402 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001403 }
1404 if (*out_forward_dex_cache_array) {
1405 ScopedTrace timing("Fixup ArtMethod dex cache arrays");
1406 FixupArtMethodArrayVisitor visitor(header);
Andreas Gampe542451c2016-07-26 09:02:02 -07001407 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001408 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get());
1409 }
1410 if (kVerifyArtMethodDeclaringClasses) {
1411 ScopedTrace timing("Verify declaring classes");
1412 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1413 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001414 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001415 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001416 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001417}
1418
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001419// Update the class loader. Should only be used on classes in the image space.
1420class UpdateClassLoaderVisitor {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001421 public:
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001422 UpdateClassLoaderVisitor(gc::space::ImageSpace* space, ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001423 : space_(space),
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001424 class_loader_(class_loader) {}
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001425
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001426 bool operator()(ObjPtr<mirror::Class> klass) const REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001427 // Do not update class loader for boot image classes where the app image
1428 // class loader is only the initiating loader but not the defining loader.
1429 if (klass->GetClassLoader() != nullptr) {
1430 klass->SetClassLoader(class_loader_);
1431 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001432 return true;
1433 }
1434
1435 gc::space::ImageSpace* const space_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001436 ObjPtr<mirror::ClassLoader> const class_loader_;
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001437};
1438
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001439static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1440 const char* location,
1441 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001442 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001443 DCHECK(error_msg != nullptr);
1444 std::unique_ptr<const DexFile> dex_file;
Richard Uhler9a37efc2016-08-05 16:32:55 -07001445 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001446 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001447 return std::unique_ptr<const DexFile>();
1448 }
1449 std::string inner_error_msg;
1450 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1451 if (dex_file == nullptr) {
1452 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1453 location,
1454 oat_file->GetLocation().c_str(),
1455 inner_error_msg.c_str());
1456 return std::unique_ptr<const DexFile>();
1457 }
1458
1459 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1460 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1461 location,
1462 dex_file->GetLocationChecksum(),
1463 oat_dex_file->GetDexFileLocationChecksum());
1464 return std::unique_ptr<const DexFile>();
1465 }
1466 return dex_file;
1467}
1468
1469bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1470 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1471 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001472 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001473 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001474 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001475 DCHECK(dex_caches_object != nullptr);
1476 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1477 dex_caches_object->AsObjectArray<mirror::DexCache>();
1478 const OatFile* oat_file = space->GetOatFile();
1479 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001480 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001481 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1482 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1483 dex_file_location.c_str(),
1484 error_msg);
1485 if (dex_file == nullptr) {
1486 return false;
1487 }
1488 dex_cache->SetDexFile(dex_file.get());
1489 out_dex_files->push_back(std::move(dex_file));
1490 }
1491 return true;
1492}
1493
Andreas Gampe0793bec2016-12-01 11:37:33 -08001494// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1495// together and caches some intermediate results.
1496class ImageSanityChecks FINAL {
1497 public:
1498 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1499 REQUIRES_SHARED(Locks::mutator_lock_) {
1500 ImageSanityChecks isc(heap, class_linker);
1501 heap->VisitObjects(ImageSanityChecks::SanityCheckObjectsCallback, &isc);
1502 }
1503
1504 static void CheckPointerArray(gc::Heap* heap,
1505 ClassLinker* class_linker,
1506 ArtMethod** arr,
1507 size_t size)
1508 REQUIRES_SHARED(Locks::mutator_lock_) {
1509 ImageSanityChecks isc(heap, class_linker);
1510 isc.SanityCheckArtMethodPointerArray(arr, size);
1511 }
1512
1513 static void SanityCheckObjectsCallback(mirror::Object* obj, void* arg)
1514 REQUIRES_SHARED(Locks::mutator_lock_) {
1515 DCHECK(obj != nullptr);
1516 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1517 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1518 if (obj->IsClass()) {
1519 ImageSanityChecks* isc = reinterpret_cast<ImageSanityChecks*>(arg);
1520
1521 auto klass = obj->AsClass();
1522 for (ArtField& field : klass->GetIFields()) {
1523 CHECK_EQ(field.GetDeclaringClass(), klass);
1524 }
1525 for (ArtField& field : klass->GetSFields()) {
1526 CHECK_EQ(field.GetDeclaringClass(), klass);
1527 }
1528 const auto pointer_size = isc->pointer_size_;
1529 for (auto& m : klass->GetMethods(pointer_size)) {
1530 isc->SanityCheckArtMethod(&m, klass);
1531 }
1532 auto* vtable = klass->GetVTable();
1533 if (vtable != nullptr) {
1534 isc->SanityCheckArtMethodPointerArray(vtable, nullptr);
1535 }
1536 if (klass->ShouldHaveImt()) {
1537 ImTable* imt = klass->GetImt(pointer_size);
1538 for (size_t i = 0; i < ImTable::kSize; ++i) {
1539 isc->SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1540 }
1541 }
1542 if (klass->ShouldHaveEmbeddedVTable()) {
1543 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1544 isc->SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1545 }
1546 }
1547 mirror::IfTable* iftable = klass->GetIfTable();
1548 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1549 if (iftable->GetMethodArrayCount(i) > 0) {
1550 isc->SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1551 }
1552 }
1553 }
1554 }
1555
1556 private:
1557 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1558 : spaces_(heap->GetBootImageSpaces()),
1559 pointer_size_(class_linker->GetImagePointerSize()) {
1560 space_begin_.reserve(spaces_.size());
1561 method_sections_.reserve(spaces_.size());
1562 runtime_method_sections_.reserve(spaces_.size());
1563 for (gc::space::ImageSpace* space : spaces_) {
1564 space_begin_.push_back(space->Begin());
1565 auto& header = space->GetImageHeader();
1566 method_sections_.push_back(&header.GetMethodsSection());
1567 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1568 }
1569 }
1570
1571 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1572 REQUIRES_SHARED(Locks::mutator_lock_) {
1573 if (m->IsRuntimeMethod()) {
1574 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1575 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1576 } else if (m->IsCopied()) {
1577 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1578 } else if (expected_class != nullptr) {
1579 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1580 }
1581 if (!spaces_.empty()) {
1582 bool contains = false;
1583 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1584 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1585 contains = method_sections_[i]->Contains(offset) ||
1586 runtime_method_sections_[i]->Contains(offset);
1587 }
1588 CHECK(contains) << m << " not found";
1589 }
1590 }
1591
1592 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1593 ObjPtr<mirror::Class> expected_class)
1594 REQUIRES_SHARED(Locks::mutator_lock_) {
1595 CHECK(arr != nullptr);
1596 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1597 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1598 // expected_class == null means we are a dex cache.
1599 if (expected_class != nullptr) {
1600 CHECK(method != nullptr);
1601 }
1602 if (method != nullptr) {
1603 SanityCheckArtMethod(method, expected_class);
1604 }
1605 }
1606 }
1607
1608 void SanityCheckArtMethodPointerArray(ArtMethod** arr, size_t size)
1609 REQUIRES_SHARED(Locks::mutator_lock_) {
1610 CHECK_EQ(arr != nullptr, size != 0u);
1611 if (arr != nullptr) {
1612 bool contains = false;
1613 for (auto space : spaces_) {
1614 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
1615 if (space->GetImageHeader().GetImageSection(
1616 ImageHeader::kSectionDexCacheArrays).Contains(offset)) {
1617 contains = true;
1618 break;
1619 }
1620 }
1621 CHECK(contains);
1622 }
1623 for (size_t j = 0; j < size; ++j) {
1624 ArtMethod* method = mirror::DexCache::GetElementPtrSize(arr, j, pointer_size_);
1625 // expected_class == null means we are a dex cache.
1626 if (method != nullptr) {
1627 SanityCheckArtMethod(method, nullptr);
1628 }
1629 }
1630 }
1631
1632 const std::vector<gc::space::ImageSpace*>& spaces_;
1633 const PointerSize pointer_size_;
1634
1635 // Cached sections from the spaces.
1636 std::vector<const uint8_t*> space_begin_;
1637 std::vector<const ImageSection*> method_sections_;
1638 std::vector<const ImageSection*> runtime_method_sections_;
1639};
1640
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001641bool ClassLinker::AddImageSpace(
1642 gc::space::ImageSpace* space,
1643 Handle<mirror::ClassLoader> class_loader,
1644 jobjectArray dex_elements,
1645 const char* dex_location,
1646 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1647 std::string* error_msg) {
1648 DCHECK(out_dex_files != nullptr);
1649 DCHECK(error_msg != nullptr);
1650 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001651 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001652 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001653 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001654 DCHECK(dex_caches_object != nullptr);
1655 Runtime* const runtime = Runtime::Current();
1656 gc::Heap* const heap = runtime->GetHeap();
1657 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001658 // Check that the image is what we are expecting.
1659 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1660 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1661 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1662 image_pointer_size_);
1663 return false;
1664 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001665 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1666 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1667 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1668 expected_image_roots,
1669 header.GetImageRoots()->GetLength());
1670 return false;
1671 }
1672 StackHandleScope<3> hs(self);
1673 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1674 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1675 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1676 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
1677 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1678 "Class loader should be the last image root.");
1679 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
1680 app_image ? header.GetImageRoot(ImageHeader::kClassLoader)->AsClassLoader() : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001681 DCHECK(class_roots != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001682 if (class_roots->GetLength() != static_cast<int32_t>(kClassRootsMax)) {
1683 *error_msg = StringPrintf("Expected %d class roots but got %d",
1684 class_roots->GetLength(),
1685 static_cast<int32_t>(kClassRootsMax));
1686 return false;
1687 }
1688 // Check against existing class roots to make sure they match the ones in the boot image.
1689 for (size_t i = 0; i < kClassRootsMax; i++) {
1690 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i))) {
1691 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1692 return false;
1693 }
1694 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001695 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001696 if (oat_file->GetOatHeader().GetDexFileCount() !=
1697 static_cast<uint32_t>(dex_caches->GetLength())) {
1698 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1699 "image";
1700 return false;
1701 }
1702
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001703 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001704 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1705 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001706 // TODO: Only store qualified paths.
1707 // If non qualified, qualify it.
1708 if (dex_file_location.find('/') == std::string::npos) {
1709 std::string dex_location_path = dex_location;
1710 const size_t pos = dex_location_path.find_last_of('/');
1711 CHECK_NE(pos, std::string::npos);
1712 dex_location_path = dex_location_path.substr(0, pos + 1); // Keep trailing '/'
1713 dex_file_location = dex_location_path + dex_file_location;
1714 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001715 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1716 dex_file_location.c_str(),
1717 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001718 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001719 return false;
1720 }
1721
1722 if (app_image) {
1723 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
1724 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00001725 dex_cache->SetDexFile(dex_file.get());
Mathieu Chartier5812e202017-02-13 18:32:04 -08001726 GcRoot<mirror::Class>* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00001727 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Mathieu Chartier5812e202017-02-13 18:32:04 -08001728 ObjPtr<mirror::Class> klass = types[j].Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001729 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001730 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001731 }
1732 }
1733 } else {
1734 if (kSanityCheckObjects) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001735 ImageSanityChecks::CheckPointerArray(heap,
1736 this,
Vladimir Markocd556b02017-02-03 11:47:34 +00001737 dex_cache->GetResolvedMethods(),
1738 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001739 }
1740 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00001741 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001742 }
1743 out_dex_files->push_back(std::move(dex_file));
1744 }
1745
1746 if (app_image) {
1747 ScopedObjectAccessUnchecked soa(Thread::Current());
1748 // Check that the class loader resolves the same way as the ones in the image.
1749 // Image class loader [A][B][C][image dex files]
1750 // Class loader = [???][dex_elements][image dex files]
1751 // Need to ensure that [???][dex_elements] == [A][B][C].
1752 // For each class loader, PathClassLoader, the laoder checks the parent first. Also the logic
1753 // for PathClassLoader does this by looping through the array of dex files. To ensure they
1754 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
1755 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001756 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1757 *error_msg = "Unexpected BootClassLoader in app image";
1758 return false;
1759 }
1760 std::list<mirror::String*> image_dex_file_names;
1761 std::string temp_error_msg;
1762 if (!FlattenPathClassLoader(image_class_loader.Get(), &image_dex_file_names, &temp_error_msg)) {
1763 *error_msg = StringPrintf("Failed to flatten image class loader hierarchy '%s'",
1764 temp_error_msg.c_str());
1765 return false;
1766 }
1767 std::list<mirror::String*> loader_dex_file_names;
1768 if (!FlattenPathClassLoader(class_loader.Get(), &loader_dex_file_names, &temp_error_msg)) {
1769 *error_msg = StringPrintf("Failed to flatten class loader hierarchy '%s'",
1770 temp_error_msg.c_str());
1771 return false;
1772 }
1773 // Add the temporary dex path list elements at the end.
1774 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
1775 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
1776 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
1777 if (element != nullptr) {
1778 // If we are somewhere in the middle of the array, there may be nulls at the end.
1779 loader_dex_file_names.push_back(GetDexPathListElementName(element));
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01001780 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001781 }
1782 // Ignore the number of image dex files since we are adding those to the class loader anyways.
1783 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
1784 static_cast<size_t>(dex_caches->GetLength()));
1785 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
1786 // Check that the dex file names match.
1787 bool equal = image_count == loader_dex_file_names.size();
1788 if (equal) {
1789 auto it1 = image_dex_file_names.begin();
1790 auto it2 = loader_dex_file_names.begin();
1791 for (size_t i = 0; equal && i < image_count; ++i, ++it1, ++it2) {
1792 equal = equal && (*it1)->Equals(*it2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001793 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001794 }
1795 if (!equal) {
1796 VLOG(image) << "Image dex files " << image_dex_file_names.size();
1797 for (ObjPtr<mirror::String> name : image_dex_file_names) {
1798 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001799 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001800 VLOG(image) << "Loader dex files " << loader_dex_file_names.size();
1801 for (ObjPtr<mirror::String> name : loader_dex_file_names) {
1802 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001803 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001804 *error_msg = "Rejecting application image due to class loader mismatch";
1805 // Ignore class loader mismatch for now since these would just use possibly incorrect
1806 // oat code anyways. The structural class check should be done in the parent.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001807 }
1808 }
1809
1810 if (kSanityCheckObjects) {
1811 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1812 auto* dex_cache = dex_caches->Get(i);
1813 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
1814 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
1815 if (field != nullptr) {
1816 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
1817 }
1818 }
1819 }
1820 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001821 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001822 }
1823 }
1824
1825 // Set entry point to interpreter if in InterpretOnly mode.
1826 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001827 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001828 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001829 }
1830
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001831 ClassTable* class_table = nullptr;
1832 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001833 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001834 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08001835 }
1836 // If we have a class table section, read it and use it for verification in
1837 // UpdateAppImageClassLoadersAndDexCaches.
1838 ClassTable::ClassSet temp_set;
1839 const ImageSection& class_table_section = header.GetImageSection(ImageHeader::kSectionClassTable);
1840 const bool added_class_table = class_table_section.Size() > 0u;
1841 if (added_class_table) {
1842 const uint64_t start_time2 = NanoTime();
1843 size_t read_count = 0;
1844 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
1845 /*make copy*/false,
1846 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08001847 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001848 }
1849 if (app_image) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001850 bool forward_dex_cache_arrays = false;
1851 if (!UpdateAppImageClassLoadersAndDexCaches(space,
1852 class_loader,
1853 dex_caches,
Vladimir Marko1a1de672016-10-13 12:53:15 +01001854 &temp_set,
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001855 /*out*/&forward_dex_cache_arrays,
1856 /*out*/error_msg)) {
1857 return false;
1858 }
Mathieu Chartier69731002016-03-02 16:08:31 -08001859 // Update class loader and resolved strings. If added_class_table is false, the resolved
1860 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001861 UpdateClassLoaderVisitor visitor(space, class_loader.Get());
1862 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001863 visitor(root.Read());
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001864 }
Mathieu Chartier8c4f0412016-02-03 16:40:20 -08001865 // forward_dex_cache_arrays is true iff we copied all of the dex cache arrays into the .bss.
1866 // In this case, madvise away the dex cache arrays section of the image to reduce RAM usage and
1867 // mark as PROT_NONE to catch any invalid accesses.
1868 if (forward_dex_cache_arrays) {
1869 const ImageSection& dex_cache_section = header.GetImageSection(
1870 ImageHeader::kSectionDexCacheArrays);
1871 uint8_t* section_begin = AlignUp(space->Begin() + dex_cache_section.Offset(), kPageSize);
1872 uint8_t* section_end = AlignDown(space->Begin() + dex_cache_section.End(), kPageSize);
1873 if (section_begin < section_end) {
1874 madvise(section_begin, section_end - section_begin, MADV_DONTNEED);
1875 mprotect(section_begin, section_end - section_begin, PROT_NONE);
1876 VLOG(image) << "Released and protected dex cache array image section from "
1877 << reinterpret_cast<const void*>(section_begin) << "-"
1878 << reinterpret_cast<const void*>(section_end);
1879 }
1880 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001881 }
1882 if (!oat_file->GetBssGcRoots().empty()) {
1883 // Insert oat file to class table for visiting .bss GC roots.
1884 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001885 }
Mathieu Chartier69731002016-03-02 16:08:31 -08001886 if (added_class_table) {
1887 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1888 class_table->AddClassSet(std::move(temp_set));
1889 }
1890 if (kIsDebugBuild && app_image) {
1891 // This verification needs to happen after the classes have been added to the class loader.
1892 // Since it ensures classes are in the class table.
1893 VerifyClassInTableArtMethodVisitor visitor2(class_table);
Andreas Gampe542451c2016-07-26 09:02:02 -07001894 header.VisitPackedArtMethods(&visitor2, space->Begin(), kRuntimePointerSize);
Mathieu Chartier69731002016-03-02 16:08:31 -08001895 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001896 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001897 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001898}
1899
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001900bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001901 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
1902 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001903}
1904
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001905void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001906 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
1907 // enabling tracing requires the mutator lock, there are no race conditions here.
1908 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001909 Thread* const self = Thread::Current();
1910 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001911 if (kUseReadBarrier) {
1912 // We do not track new roots for CC.
1913 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
1914 kVisitRootFlagClearRootLog |
1915 kVisitRootFlagStartLoggingNewRoots |
1916 kVisitRootFlagStopLoggingNewRoots));
1917 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001918 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001919 // Argument for how root visiting deals with ArtField and ArtMethod roots.
1920 // There is 3 GC cases to handle:
1921 // Non moving concurrent:
1922 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001923 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001924 //
1925 // Moving non-concurrent:
1926 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
1927 // To prevent missing roots, this case needs to ensure that there is no
1928 // suspend points between the point which we allocate ArtMethod arrays and place them in a
1929 // class which is in the class table.
1930 //
1931 // Moving concurrent:
1932 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
1933 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001934 //
1935 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
1936 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
1937 // these objects.
1938 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
1939 boot_class_table_.VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07001940 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09001941 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001942 for (const ClassLoaderData& data : class_loaders_) {
1943 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
1944 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
1945 }
1946 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001947 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001948 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001949 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001950 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001951 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001952 // Concurrent moving GC marked new roots through the to-space invariant.
1953 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001954 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001955 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
1956 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
1957 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
1958 if (old_ref != nullptr) {
1959 DCHECK(old_ref->IsClass());
1960 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
1961 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
1962 // Concurrent moving GC marked new roots through the to-space invariant.
1963 CHECK_EQ(new_ref, old_ref);
1964 }
1965 }
1966 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001967 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001968 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001969 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00001970 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001971 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001972 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001973 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001974 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001975 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001976 }
1977 // We deliberately ignore the class roots in the image since we
1978 // handle image roots by using the MS/CMS rescanning of dirty cards.
1979}
1980
Brian Carlstroma663ea52011-08-19 23:33:41 -07001981// Keep in sync with InitCallback. Anything we visit, we need to
1982// reinit references to when reinitializing a ClassLinker from a
1983// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001984void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07001985 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001986 VisitClassRoots(visitor, flags);
Mathieu Chartier31000802015-06-14 14:14:37 -07001987 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07001988 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
1989 // unloading if we are marking roots.
1990 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001991}
1992
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001993class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
1994 public:
1995 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
1996 : visitor_(visitor),
1997 done_(false) {}
1998
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001999 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002000 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002001 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002002 if (!done_ && class_table != nullptr) {
2003 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2004 if (!class_table->Visit(visitor)) {
2005 // If the visitor ClassTable returns false it means that we don't need to continue.
2006 done_ = true;
2007 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002008 }
2009 }
2010
2011 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002012 // Class visitor that limits the class visits from a ClassTable to the classes with
2013 // the provided defining class loader. This filter is used to avoid multiple visits
2014 // of the same class which can be recorded for multiple initiating class loaders.
2015 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2016 public:
2017 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2018 ClassVisitor* visitor)
2019 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2020
2021 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
2022 if (klass->GetClassLoader() != defining_class_loader_) {
2023 return true;
2024 }
2025 return (*visitor_)(klass);
2026 }
2027
2028 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2029 ClassVisitor* const visitor_;
2030 };
2031
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002032 ClassVisitor* const visitor_;
2033 // If done is true then we don't need to do any more visiting.
2034 bool done_;
2035};
2036
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002037void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002038 if (boot_class_table_.Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002039 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2040 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002041 }
2042}
2043
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002044void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002045 Thread* const self = Thread::Current();
2046 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2047 // Not safe to have thread suspension when we are holding a lock.
2048 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002049 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002050 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002051 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002052 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002053 }
2054}
2055
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002056class GetClassesInToVector : public ClassVisitor {
2057 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002058 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002059 classes_.push_back(klass);
2060 return true;
2061 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002062 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002063};
2064
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002065class GetClassInToObjectArray : public ClassVisitor {
2066 public:
2067 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2068 : arr_(arr), index_(0) {}
2069
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002070 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002071 ++index_;
2072 if (index_ <= arr_->GetLength()) {
2073 arr_->Set(index_ - 1, klass);
2074 return true;
2075 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002076 return false;
2077 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002078
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002079 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002080 return index_ <= arr_->GetLength();
2081 }
2082
2083 private:
2084 mirror::ObjectArray<mirror::Class>* const arr_;
2085 int32_t index_;
2086};
2087
2088void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002089 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2090 // is avoiding duplicates.
2091 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002092 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002093 GetClassesInToVector accumulator;
2094 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002095 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002096 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002097 return;
2098 }
2099 }
2100 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002101 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002102 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002103 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002104 // We size the array assuming classes won't be added to the class table during the visit.
2105 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002106 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002107 size_t class_table_size;
2108 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002109 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002110 // Add 100 in case new classes get loaded when we are filling in the object array.
2111 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002112 }
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07002113 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002114 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002115 classes.Assign(
2116 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002117 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002118 GetClassInToObjectArray accumulator(classes.Get());
2119 VisitClasses(&accumulator);
2120 if (accumulator.Succeeded()) {
2121 break;
2122 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002123 }
2124 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2125 // If the class table shrank during creation of the clases array we expect null elements. If
2126 // the class table grew then the loop repeats. If classes are created after the loop has
2127 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002128 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002129 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002130 return;
2131 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002132 }
2133 }
2134}
2135
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002136ClassLinker::~ClassLinker() {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002137 mirror::Class::ResetClass();
2138 mirror::Constructor::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07002139 mirror::Field::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002140 mirror::Method::ResetClass();
2141 mirror::Reference::ResetClass();
2142 mirror::StackTraceElement::ResetClass();
2143 mirror::String::ResetClass();
2144 mirror::Throwable::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002145 mirror::BooleanArray::ResetArrayClass();
2146 mirror::ByteArray::ResetArrayClass();
2147 mirror::CharArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002148 mirror::Constructor::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002149 mirror::DoubleArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002150 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002151 mirror::FloatArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002152 mirror::Method::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002153 mirror::IntArray::ResetArrayClass();
2154 mirror::LongArray::ResetArrayClass();
2155 mirror::ShortArray::ResetArrayClass();
Narayan Kamathafa48272016-08-03 12:46:58 +01002156 mirror::MethodType::ResetClass();
2157 mirror::MethodHandleImpl::ResetClass();
Orion Hodsonc069a302017-01-18 09:23:12 +00002158 mirror::MethodHandlesLookup::ResetClass();
2159 mirror::CallSite::ResetClass();
Narayan Kamath000e1882016-10-24 17:14:25 +01002160 mirror::EmulatedStackFrame::ResetClass();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002161 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002162 for (const ClassLoaderData& data : class_loaders_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002163 DeleteClassLoader(self, data);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002164 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002165 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002166}
2167
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002168void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data) {
2169 Runtime* const runtime = Runtime::Current();
2170 JavaVMExt* const vm = runtime->GetJavaVM();
2171 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002172 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002173 if (runtime->GetJit() != nullptr) {
2174 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2175 if (code_cache != nullptr) {
2176 code_cache->RemoveMethodsIn(self, *data.allocator);
2177 }
2178 }
2179 delete data.allocator;
2180 delete data.class_table;
2181}
2182
Mathieu Chartiere401d142015-04-22 13:56:20 -07002183mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) {
Andreas Gampe542451c2016-07-26 09:02:02 -07002184 return down_cast<mirror::PointerArray*>(
2185 image_pointer_size_ == PointerSize::k64
2186 ? static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length))
2187 : static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002188}
2189
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002190mirror::DexCache* ClassLinker::AllocDexCache(ObjPtr<mirror::String>* out_location,
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002191 Thread* self,
2192 const DexFile& dex_file) {
2193 StackHandleScope<1> hs(self);
2194 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002195 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002196 GetClassRoot(kJavaLangDexCache)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002197 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002198 self->AssertPendingOOMException();
2199 return nullptr;
2200 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002201 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002202 if (location == nullptr) {
2203 self->AssertPendingOOMException();
2204 return nullptr;
2205 }
2206 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002207 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002208}
2209
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002210mirror::DexCache* ClassLinker::AllocAndInitializeDexCache(Thread* self,
2211 const DexFile& dex_file,
2212 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002213 ObjPtr<mirror::String> location = nullptr;
2214 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002215 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002216 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002217 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002218 mirror::DexCache::InitializeDexCache(self,
2219 dex_cache,
2220 location,
2221 &dex_file,
2222 linear_alloc,
2223 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002224 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002225 return dex_cache.Ptr();
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002226}
2227
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002228mirror::Class* ClassLinker::AllocClass(Thread* self,
2229 ObjPtr<mirror::Class> java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08002230 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002231 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002232 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002233 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002234 ObjPtr<mirror::Object> k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002235 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2236 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002237 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002238 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002239 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002240 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002241 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002242}
2243
Ian Rogers6fac4472014-02-25 17:01:10 -08002244mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002245 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002246}
2247
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002248mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002249 Thread* self,
2250 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002251 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2252 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002253}
2254
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002255mirror::Class* ClassLinker::EnsureResolved(Thread* self,
2256 const char* descriptor,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002257 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002258 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002259 if (kIsDebugBuild) {
2260 StackHandleScope<1> hs(self);
2261 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2262 Thread::PoisonObjectPointersIfDebug();
2263 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002264
2265 // For temporary classes we must wait for them to be retired.
2266 if (init_done_ && klass->IsTemp()) {
2267 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002268 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002269 ThrowEarlierClassFailure(klass);
2270 return nullptr;
2271 }
2272 StackHandleScope<1> hs(self);
2273 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2274 ObjectLock<mirror::Class> lock(self, h_class);
2275 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002276 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002277 lock.WaitIgnoringInterrupts();
2278 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002279 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002280 ThrowEarlierClassFailure(h_class.Get());
2281 return nullptr;
2282 }
2283 CHECK(h_class->IsRetired());
2284 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002285 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002286 }
2287
Brian Carlstromaded5f72011-10-07 17:15:04 -07002288 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002289 size_t index = 0;
2290 // Maximum number of yield iterations until we start sleeping.
2291 static const size_t kNumYieldIterations = 1000;
2292 // How long each sleep is in us.
2293 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002294 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002295 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002296 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002297 {
2298 ObjectTryLock<mirror::Class> lock(self, h_class);
2299 // Can not use a monitor wait here since it may block when returning and deadlock if another
2300 // thread has locked klass.
2301 if (lock.Acquired()) {
2302 // Check for circular dependencies between classes, the lock is required for SetStatus.
2303 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2304 ThrowClassCircularityError(h_class.Get());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002305 mirror::Class::SetStatus(h_class, mirror::Class::kStatusErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002306 return nullptr;
2307 }
2308 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002309 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002310 {
2311 // Handle wrapper deals with klass moving.
2312 ScopedThreadSuspension sts(self, kSuspended);
2313 if (index < kNumYieldIterations) {
2314 sched_yield();
2315 } else {
2316 usleep(kSleepDurationUS);
2317 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002318 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002319 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002320 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002321
Vladimir Marko72ab6842017-01-20 19:32:50 +00002322 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002323 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002324 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002325 }
2326 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002327 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002328 self->AssertNoPendingException();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002329 return klass.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002330}
2331
Ian Rogers68b56852014-08-29 20:19:11 -07002332typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2333
2334// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002335ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002336 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002337 for (const DexFile* dex_file : class_path) {
David Sehr9aa352e2016-09-15 18:13:52 -07002338 const DexFile::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002339 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002340 return ClassPathEntry(dex_file, dex_class_def);
2341 }
2342 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002343 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002344}
2345
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002346bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2347 Thread* self,
2348 const char* descriptor,
2349 size_t hash,
2350 Handle<mirror::ClassLoader> class_loader,
2351 ObjPtr<mirror::Class>* result) {
Andreas Gampef865ea92015-04-13 22:14:19 -07002352 // Termination case: boot class-loader.
2353 if (IsBootClassLoader(soa, class_loader.Get())) {
2354 // The boot class loader, search the boot class path.
2355 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2356 if (pair.second != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002357 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
Andreas Gampef865ea92015-04-13 22:14:19 -07002358 if (klass != nullptr) {
2359 *result = EnsureResolved(self, descriptor, klass);
2360 } else {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002361 *result = DefineClass(self,
2362 descriptor,
2363 hash,
2364 ScopedNullHandle<mirror::ClassLoader>(),
2365 *pair.first,
2366 *pair.second);
Andreas Gampef865ea92015-04-13 22:14:19 -07002367 }
2368 if (*result == nullptr) {
2369 CHECK(self->IsExceptionPending()) << descriptor;
2370 self->ClearException();
2371 }
Ian Rogers32427292014-11-19 14:05:21 -08002372 } else {
Andreas Gampef865ea92015-04-13 22:14:19 -07002373 *result = nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002374 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002375 return true;
2376 }
2377
2378 // Unsupported class-loader?
Mathieu Chartier0795f232016-09-27 18:43:30 -07002379 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
2380 class_loader->GetClass()) {
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002381 // PathClassLoader is the most common case, so it's the one we check first. For secondary dex
2382 // files, we also check DexClassLoader here.
2383 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_DexClassLoader) !=
2384 class_loader->GetClass()) {
2385 *result = nullptr;
2386 return false;
2387 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002388 }
2389
2390 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2391 StackHandleScope<4> hs(self);
2392 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002393 bool recursive_result = FindClassInBaseDexClassLoader(soa,
2394 self,
2395 descriptor,
2396 hash,
2397 h_parent,
2398 result);
Andreas Gampef865ea92015-04-13 22:14:19 -07002399
2400 if (!recursive_result) {
2401 // Something wrong up the chain.
2402 return false;
2403 }
2404
2405 if (*result != nullptr) {
2406 // Found the class up the chain.
2407 return true;
2408 }
2409
2410 // Handle this step.
2411 // Handle as if this is the child PathClassLoader.
2412 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2413 // We need to get the DexPathList and loop through it.
Andreas Gampe08883de2016-11-08 13:20:52 -08002414 ArtField* const cookie_field =
2415 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Andreas Gampef865ea92015-04-13 22:14:19 -07002416 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002417 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002418 ObjPtr<mirror::Object> dex_path_list =
Andreas Gampe08883de2016-11-08 13:20:52 -08002419 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
2420 GetObject(class_loader.Get());
Andreas Gampef865ea92015-04-13 22:14:19 -07002421 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
2422 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002423 ObjPtr<mirror::Object> dex_elements_obj =
Andreas Gampe08883de2016-11-08 13:20:52 -08002424 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
Andreas Gampef865ea92015-04-13 22:14:19 -07002425 GetObject(dex_path_list);
2426 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2427 // at the mCookie which is a DexFile vector.
2428 if (dex_elements_obj != nullptr) {
2429 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2430 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2431 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002432 ObjPtr<mirror::Object> element = dex_elements->GetWithoutChecks(i);
Andreas Gampef865ea92015-04-13 22:14:19 -07002433 if (element == nullptr) {
2434 // Should never happen, fall back to java code to throw a NPE.
2435 break;
2436 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002437 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Andreas Gampef865ea92015-04-13 22:14:19 -07002438 if (dex_file != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002439 ObjPtr<mirror::LongArray> long_array = cookie_field->GetObject(dex_file)->AsLongArray();
Andreas Gampef865ea92015-04-13 22:14:19 -07002440 if (long_array == nullptr) {
2441 // This should never happen so log a warning.
2442 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002443 break;
2444 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002445 int32_t long_array_size = long_array->GetLength();
Mathieu Chartiere58991b2015-10-13 07:59:34 -07002446 // First element is the oat file.
2447 for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) {
Andreas Gampef865ea92015-04-13 22:14:19 -07002448 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
2449 long_array->GetWithoutChecks(j)));
David Sehr9aa352e2016-09-15 18:13:52 -07002450 const DexFile::ClassDef* dex_class_def =
2451 OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002452 if (dex_class_def != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002453 ObjPtr<mirror::Class> klass = DefineClass(self,
Mathieu Chartiere58991b2015-10-13 07:59:34 -07002454 descriptor,
2455 hash,
2456 class_loader,
2457 *cp_dex_file,
2458 *dex_class_def);
Andreas Gampef865ea92015-04-13 22:14:19 -07002459 if (klass == nullptr) {
2460 CHECK(self->IsExceptionPending()) << descriptor;
2461 self->ClearException();
2462 // TODO: Is it really right to break here, and not check the other dex files?
2463 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002464 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002465 *result = klass;
2466 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002467 }
2468 }
2469 }
2470 }
2471 }
Ian Rogers32427292014-11-19 14:05:21 -08002472 self->AssertNoPendingException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002473 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002474
2475 // Result is still null from the parent call, no need to set it again...
2476 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002477}
2478
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002479mirror::Class* ClassLinker::FindClass(Thread* self,
2480 const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002481 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002482 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002483 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002484 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002485 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002486 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002487 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2488 // for primitive classes that aren't backed by dex files.
2489 return FindPrimitiveClass(descriptor[0]);
2490 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002491 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002492 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002493 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002494 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002495 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002496 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002497 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002498 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002499 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002500 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002501 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002502 return DefineClass(self,
2503 descriptor,
2504 hash,
2505 ScopedNullHandle<mirror::ClassLoader>(),
2506 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002507 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002508 } else {
2509 // The boot class loader is searched ahead of the application class loader, failures are
2510 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2511 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002512 ObjPtr<mirror::Throwable> pre_allocated =
2513 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002514 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002515 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002516 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002517 }
2518 ObjPtr<mirror::Class> result_ptr;
2519 bool descriptor_equals;
2520 if (descriptor[0] == '[') {
2521 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2522 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2523 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2524 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002525 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002526 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002527 bool known_hierarchy =
2528 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2529 if (result_ptr != nullptr) {
2530 // The chain was understood and we found the class. We still need to add the class to
2531 // the class table to protect from racy programs that can try and redefine the path list
2532 // which would change the Class<?> returned for subsequent evaluation of const-class.
2533 DCHECK(known_hierarchy);
2534 DCHECK(result_ptr->DescriptorEquals(descriptor));
2535 descriptor_equals = true;
2536 } else {
2537 // Either the chain wasn't understood or the class wasn't found.
2538 //
2539 // If the chain was understood but we did not find the class, let the Java-side
2540 // rediscover all this and throw the exception with the right stack trace. Note that
2541 // the Java-side could still succeed for racy programs if another thread is actively
2542 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002543
Calin Juravleccd56952016-12-15 17:57:38 +00002544 if (!self->CanCallIntoJava()) {
2545 // Oops, we can't call into java so we can't run actual class-loader code.
2546 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002547 ObjPtr<mirror::Throwable> pre_allocated =
2548 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2549 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002550 return nullptr;
2551 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002552
2553 ScopedLocalRef<jobject> class_loader_object(
2554 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
2555 std::string class_name_string(DescriptorToDot(descriptor));
2556 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2557 {
2558 ScopedThreadStateChange tsc(self, kNative);
2559 ScopedLocalRef<jobject> class_name_object(
2560 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2561 if (class_name_object.get() == nullptr) {
2562 DCHECK(self->IsExceptionPending()); // OOME.
2563 return nullptr;
2564 }
2565 CHECK(class_loader_object.get() != nullptr);
2566 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2567 WellKnownClasses::java_lang_ClassLoader_loadClass,
2568 class_name_object.get()));
2569 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002570 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002571 // broken loader - throw NPE to be compatible with Dalvik
2572 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2573 class_name_string.c_str()).c_str());
2574 return nullptr;
2575 }
2576 result_ptr = soa.Decode<mirror::Class>(result.get());
2577 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002578 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002579 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002580 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002581
2582 if (self->IsExceptionPending()) {
2583 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2584 // However, to comply with the RI behavior, first check if another thread succeeded.
2585 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2586 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2587 self->ClearException();
2588 return EnsureResolved(self, descriptor, result_ptr);
2589 }
2590 return nullptr;
2591 }
2592
2593 // Try to insert the class to the class table, checking for mismatch.
2594 ObjPtr<mirror::Class> old;
2595 {
2596 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2597 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2598 old = class_table->Lookup(descriptor, hash);
2599 if (old == nullptr) {
2600 old = result_ptr; // For the comparison below, after releasing the lock.
2601 if (descriptor_equals) {
2602 class_table->InsertWithHash(result_ptr.Ptr(), hash);
2603 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get());
2604 } // else throw below, after releasing the lock.
2605 }
2606 }
2607 if (UNLIKELY(old != result_ptr)) {
2608 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2609 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2610 mirror::Class* loader_class = class_loader->GetClass();
2611 const char* loader_class_name =
2612 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2613 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2614 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2615 << DescriptorToDot(descriptor) << "\").";
2616 return EnsureResolved(self, descriptor, old);
2617 }
2618 if (UNLIKELY(!descriptor_equals)) {
2619 std::string result_storage;
2620 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2621 std::string loader_storage;
2622 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2623 ThrowNoClassDefFoundError(
2624 "Initiating class loader of type %s returned class %s instead of %s.",
2625 DescriptorToDot(loader_class_name).c_str(),
2626 DescriptorToDot(result_name).c_str(),
2627 DescriptorToDot(descriptor).c_str());
2628 return nullptr;
2629 }
2630 // success, return mirror::Class*
2631 return result_ptr.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002632}
2633
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002634mirror::Class* ClassLinker::DefineClass(Thread* self,
2635 const char* descriptor,
2636 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002637 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002638 const DexFile& dex_file,
2639 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002640 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002641 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002642
Brian Carlstromaded5f72011-10-07 17:15:04 -07002643 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002644 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002645 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002646 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002647 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002648 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002649 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002650 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002651 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002652 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2653 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002654 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002655 klass.Assign(GetClassRoot(kJavaLangDexCache));
Alex Lightd6251582016-10-31 11:12:30 -07002656 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
2657 klass.Assign(GetClassRoot(kDalvikSystemClassExt));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002658 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002659 }
2660
Andreas Gampefa4333d2017-02-14 11:10:34 -08002661 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002662 // Allocate a class with the status of not ready.
2663 // Interface object should get the right size here. Regular class will
2664 // figure out the right size later and be replaced with one of the right
2665 // size when the class becomes resolved.
2666 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002667 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08002668 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002669 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07002670 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002671 }
Alex Lightb0f11922017-01-23 14:25:17 -08002672 // Get the real dex file. This will return the input if there aren't any callbacks or they do
2673 // nothing.
2674 DexFile const* new_dex_file = nullptr;
2675 DexFile::ClassDef const* new_class_def = nullptr;
2676 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
2677 // will only be called once.
2678 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
2679 klass,
2680 class_loader,
2681 dex_file,
2682 dex_class_def,
2683 &new_dex_file,
2684 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08002685 // Check to see if an exception happened during runtime callbacks. Return if so.
2686 if (self->IsExceptionPending()) {
2687 return nullptr;
2688 }
Alex Lightb0f11922017-01-23 14:25:17 -08002689 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002690 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002691 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002692 return nullptr;
2693 }
2694 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08002695 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002696
Jeff Hao848f70a2014-01-15 13:49:50 -08002697 // Mark the string class by setting its access flag.
2698 if (UNLIKELY(!init_done_)) {
2699 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2700 klass->SetStringClass();
2701 }
2702 }
2703
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002704 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002705 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08002706 // Make sure we have a valid empty iftable even if there are errors.
2707 klass->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002708
Mathieu Chartier590fee92013-09-13 13:46:47 -07002709 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002710 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002711 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002712 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2713 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002714 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002715 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002716
Mathieu Chartierc7853442015-03-27 14:35:38 -07002717 // Load the fields and other things after we are inserted in the table. This is so that we don't
2718 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
2719 // other reason is that the field roots are only visited from the class table. So we need to be
2720 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08002721 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002722 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002723 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07002724 // An exception occured during load, set status to erroneous while holding klass' lock in case
2725 // notification is necessary.
2726 if (!klass->IsErroneous()) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002727 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002728 }
2729 return nullptr;
2730 }
2731
Brian Carlstromaded5f72011-10-07 17:15:04 -07002732 // Finish loading (if necessary) by finding parents
2733 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08002734 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002735 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002736 if (!klass->IsErroneous()) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002737 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002738 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002739 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002740 }
2741 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08002742
2743 // At this point the class is loaded. Publish a ClassLoad even.
2744 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08002745 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08002746
Brian Carlstromaded5f72011-10-07 17:15:04 -07002747 // Link the class (if necessary)
2748 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002749 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002750 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002751
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002752 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002753 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002754 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002755 if (!klass->IsErroneous()) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002756 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002757 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002758 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002759 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002760 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002761 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00002762 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002763
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002764 // Instrumentation may have updated entrypoints for all methods of all
2765 // classes. However it could not update methods of this class while we
2766 // were loading it. Now the class is resolved, we can update entrypoints
2767 // as required by instrumentation.
2768 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2769 // We must be in the kRunnable state to prevent instrumentation from
2770 // suspending all threads to update entrypoints while we are doing it
2771 // for this class.
2772 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002773 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002774 }
2775
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002776 /*
2777 * We send CLASS_PREPARE events to the debugger from here. The
2778 * definition of "preparation" is creating the static fields for a
2779 * class and initializing them to the standard default values, but not
2780 * executing any code (that comes later, during "initialization").
2781 *
2782 * We did the static preparation in LinkClass.
2783 *
2784 * The class has been prepared and resolved but possibly not yet verified
2785 * at this point.
2786 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08002787 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002788
Tamas Berghammer160e6df2016-01-05 14:29:02 +00002789 // Notify native debugger of the new class and its layout.
2790 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
2791
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002792 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002793}
2794
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002795uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2796 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002797 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002798 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002799 size_t num_8 = 0;
2800 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002801 size_t num_32 = 0;
2802 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002803 if (class_data != nullptr) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002804 // We allow duplicate definitions of the same field in a class_data_item
2805 // but ignore the repeated indexes here, b/21868015.
2806 uint32_t last_field_idx = DexFile::kDexNoIndex;
Ian Rogers0571d352011-11-03 19:51:38 -07002807 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002808 uint32_t field_idx = it.GetMemberIndex();
2809 // Ordering enforced by DexFileVerifier.
2810 DCHECK(last_field_idx == DexFile::kDexNoIndex || last_field_idx <= field_idx);
2811 if (UNLIKELY(field_idx == last_field_idx)) {
2812 continue;
2813 }
2814 last_field_idx = field_idx;
2815 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002816 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002817 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002818 switch (c) {
2819 case 'L':
2820 case '[':
2821 num_ref++;
2822 break;
2823 case 'J':
2824 case 'D':
2825 num_64++;
2826 break;
2827 case 'I':
2828 case 'F':
2829 num_32++;
2830 break;
2831 case 'S':
2832 case 'C':
2833 num_16++;
2834 break;
2835 case 'B':
2836 case 'Z':
2837 num_8++;
2838 break;
2839 default:
2840 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002841 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002842 }
2843 }
2844 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002845 return mirror::Class::ComputeClassSize(false,
2846 0,
2847 num_8,
2848 num_16,
2849 num_32,
2850 num_64,
2851 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002852 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002853}
2854
TDYa12785321912012-04-01 15:24:56 -07002855// Special case to get oat code without overwriting a trampoline.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002856const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07002857 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00002858 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002859 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002860 }
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002861 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
2862 if (code != nullptr) {
2863 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08002864 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002865 if (method->IsNative()) {
2866 // No code and native? Use generic trampoline.
2867 return GetQuickGenericJniStub();
2868 }
2869 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07002870}
2871
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002872bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
2873 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
2874 return false;
2875 }
2876
Elliott Hughes956af0f2014-12-11 14:34:28 -08002877 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002878 return true;
2879 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002880
2881 Runtime* runtime = Runtime::Current();
2882 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
2883 if (instr->InterpretOnly()) {
2884 return true;
2885 }
2886
2887 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
2888 // Doing this check avoids doing compiled/interpreter transitions.
2889 return true;
2890 }
2891
2892 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
2893 // Force the use of interpreter when it is required by the debugger.
2894 return true;
2895 }
2896
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002897 if (runtime->IsJavaDebuggable()) {
2898 // For simplicity, we ignore precompiled code and go to the interpreter
2899 // assuming we don't already have jitted code.
2900 // We could look at the oat file where `quick_code` is being defined,
2901 // and check whether it's been compiled debuggable, but we decided to
2902 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08002903 jit::Jit* jit = Runtime::Current()->GetJit();
2904 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
2905 }
2906
David Srbeckyf4480162016-03-16 00:06:24 +00002907 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01002908 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00002909 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002910 // since we want to JIT it (at first use) with extra stackmaps for native
2911 // debugging. We keep however all AOT code from the boot image,
2912 // since the JIT-at-first-use is blocking and would result in non-negligible
2913 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00002914 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002915 }
2916
2917 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002918}
2919
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002920void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07002921 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07002922 if (klass->NumDirectMethods() == 0) {
2923 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002924 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002925 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002926 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002927 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002928 return; // OAT file unavailable.
2929 }
Ian Rogers19846512012-02-24 11:42:47 -08002930 }
Alex Light64ad14d2014-08-19 14:23:13 -07002931
Mathieu Chartierf8322842014-05-16 10:59:25 -07002932 const DexFile& dex_file = klass->GetDexFile();
2933 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002934 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002935 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002936 // There should always be class data if there were direct methods.
David Sehr709b0702016-10-13 09:12:37 -07002937 CHECK(class_data != nullptr) << klass->PrettyDescriptor();
Ian Rogers19846512012-02-24 11:42:47 -08002938 ClassDataItemIterator it(dex_file, class_data);
2939 // Skip fields
2940 while (it.HasNextStaticField()) {
2941 it.Next();
2942 }
2943 while (it.HasNextInstanceField()) {
2944 it.Next();
2945 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002946 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002947 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
2948 klass->GetDexClassDefIndex(),
2949 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002950 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002951 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002952 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002953 if (!method->IsStatic()) {
2954 // Only update static methods.
2955 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002956 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002957 const void* quick_code = nullptr;
2958 if (has_oat_class) {
2959 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002960 quick_code = oat_method.GetQuickCode();
2961 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002962 // Check whether the method is native, in which case it's generic JNI.
2963 if (quick_code == nullptr && method->IsNative()) {
2964 quick_code = GetQuickGenericJniStub();
2965 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002966 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002967 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002968 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002969 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08002970 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002971 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002972}
2973
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002974// Does anything needed to make sure that the compiler will not generate a direct invoke to this
2975// method. Should only be called on non-invokable methods.
2976inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07002977 DCHECK(method != nullptr);
2978 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002979 method->SetEntryPointFromQuickCompiledCodePtrSize(
2980 class_linker->GetQuickToInterpreterBridgeTrampoline(),
2981 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07002982}
2983
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002984static void LinkCode(ClassLinker* class_linker,
2985 ArtMethod* method,
2986 const OatFile::OatClass* oat_class,
2987 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002988 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002989 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002990 // The following code only applies to a non-compiler runtime.
2991 return;
2992 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002993 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002994 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002995 if (oat_class != nullptr) {
2996 // Every kind of method should at least get an invoke stub from the oat_method.
2997 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002998 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002999 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003000 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003001
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003002 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003003 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003004 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003005
Alex Light9139e002015-10-09 15:59:48 -07003006 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003007 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003008 return;
3009 }
Ian Rogers19846512012-02-24 11:42:47 -08003010
3011 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003012 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003013 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3014 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003015 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003016 } else if (quick_code == nullptr && method->IsNative()) {
3017 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003018 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003019 // Set entry point from compiled code if there's no code or in interpreter only mode.
3020 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003021 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003022
Ian Rogers62d6c772013-02-27 08:32:07 -08003023 if (method->IsNative()) {
3024 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003025 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003026
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003027 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003028 // We have a native method here without code. Then it should have either the generic JNI
3029 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3030 // TODO: this doesn't handle all the cases where trampolines may be installed.
3031 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003032 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3033 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003034 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003035 }
3036}
3037
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003038void ClassLinker::SetupClass(const DexFile& dex_file,
3039 const DexFile::ClassDef& dex_class_def,
3040 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003041 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003042 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003043 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003044 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003045 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003046 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003047
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003048 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07003049 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003050 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003051 klass->SetAccessFlags(access_flags);
3052 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003053 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003054 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003055
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003056 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003057 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003058}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003059
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003060void ClassLinker::LoadClass(Thread* self,
3061 const DexFile& dex_file,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003062 const DexFile::ClassDef& dex_class_def,
3063 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07003064 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003065 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07003066 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07003067 }
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003068 LoadClassMembers(self, dex_file, class_data, klass);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003069}
3070
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003071LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3072 LinearAlloc* allocator,
3073 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003074 if (length == 0) {
3075 return nullptr;
3076 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003077 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3078 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3079 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003080 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003081 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003082 CHECK(ret != nullptr);
3083 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3084 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003085}
3086
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003087LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3088 LinearAlloc* allocator,
3089 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003090 if (length == 0) {
3091 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003092 }
Vladimir Marko14632852015-08-17 12:07:23 +01003093 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3094 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003095 const size_t storage_size =
3096 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003097 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003098 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003099 CHECK(ret != nullptr);
3100 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003101 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003102 }
3103 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003104}
3105
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003106LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003107 if (class_loader == nullptr) {
3108 return Runtime::Current()->GetLinearAlloc();
3109 }
3110 LinearAlloc* allocator = class_loader->GetAllocator();
3111 DCHECK(allocator != nullptr);
3112 return allocator;
3113}
3114
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003115LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003116 if (class_loader == nullptr) {
3117 return Runtime::Current()->GetLinearAlloc();
3118 }
3119 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3120 LinearAlloc* allocator = class_loader->GetAllocator();
3121 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003122 RegisterClassLoader(class_loader);
3123 allocator = class_loader->GetAllocator();
3124 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003125 }
3126 return allocator;
3127}
3128
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003129void ClassLinker::LoadClassMembers(Thread* self,
3130 const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07003131 const uint8_t* class_data,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003132 Handle<mirror::Class> klass) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003133 {
3134 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3135 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003136 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003137 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003138 // We allow duplicate definitions of the same field in a class_data_item
3139 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003140 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003141 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003142 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3143 allocator,
3144 it.NumStaticFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003145 size_t num_sfields = 0;
3146 uint32_t last_field_idx = 0u;
3147 for (; it.HasNextStaticField(); it.Next()) {
3148 uint32_t field_idx = it.GetMemberIndex();
3149 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3150 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
3151 DCHECK_LT(num_sfields, it.NumStaticFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003152 LoadField(it, klass, &sfields->At(num_sfields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003153 ++num_sfields;
3154 last_field_idx = field_idx;
3155 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003156 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003157
Mathieu Chartiere401d142015-04-22 13:56:20 -07003158 // Load instance fields.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003159 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3160 allocator,
3161 it.NumInstanceFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003162 size_t num_ifields = 0u;
3163 last_field_idx = 0u;
3164 for (; it.HasNextInstanceField(); it.Next()) {
3165 uint32_t field_idx = it.GetMemberIndex();
3166 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3167 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
3168 DCHECK_LT(num_ifields, it.NumInstanceFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003169 LoadField(it, klass, &ifields->At(num_ifields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003170 ++num_ifields;
3171 last_field_idx = field_idx;
3172 }
3173 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003174
Vladimir Marko23682bf2015-06-24 14:28:03 +01003175 if (UNLIKELY(num_sfields != it.NumStaticFields()) ||
3176 UNLIKELY(num_ifields != it.NumInstanceFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003177 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Vladimir Marko23682bf2015-06-24 14:28:03 +01003178 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields()
3179 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003180 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3181 if (sfields != nullptr) {
3182 sfields->SetSize(num_sfields);
3183 }
3184 if (ifields != nullptr) {
3185 ifields->SetSize(num_ifields);
3186 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003187 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003188 // Set the field arrays.
3189 klass->SetSFieldsPtr(sfields);
3190 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003191 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003192 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
3193 // Load methods.
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003194 bool has_oat_class = false;
3195 const OatFile::OatClass oat_class =
3196 (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler())
3197 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3198 : OatFile::OatClass::Invalid();
3199 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
Alex Lighte64300b2015-12-15 15:02:47 -08003200 klass->SetMethodsPtr(
3201 AllocArtMethodArray(self, allocator, it.NumDirectMethods() + it.NumVirtualMethods()),
3202 it.NumDirectMethods(),
3203 it.NumVirtualMethods());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003204 size_t class_def_method_index = 0;
3205 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
3206 size_t last_class_def_method_index = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08003207 // TODO These should really use the iterators.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003208 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
3209 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003210 LoadMethod(dex_file, it, klass, method);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003211 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003212 uint32_t it_method_index = it.GetMemberIndex();
3213 if (last_dex_method_index == it_method_index) {
3214 // duplicate case
3215 method->SetMethodIndex(last_class_def_method_index);
3216 } else {
3217 method->SetMethodIndex(class_def_method_index);
3218 last_dex_method_index = it_method_index;
3219 last_class_def_method_index = class_def_method_index;
3220 }
3221 class_def_method_index++;
3222 }
3223 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
3224 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003225 LoadMethod(dex_file, it, klass, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003226 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003227 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003228 class_def_method_index++;
3229 }
3230 DCHECK(!it.HasNext());
Ian Rogers0571d352011-11-03 19:51:38 -07003231 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003232 // Ensure that the card is marked so that remembered sets pick up native roots.
3233 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003234 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003235}
3236
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003237void ClassLinker::LoadField(const ClassDataItemIterator& it,
3238 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003239 ArtField* dst) {
3240 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003241 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003242 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07003243 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003244}
3245
Mathieu Chartier268764d2016-09-13 12:09:38 -07003246void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003247 const ClassDataItemIterator& it,
3248 Handle<mirror::Class> klass,
3249 ArtMethod* dst) {
Ian Rogers19846512012-02-24 11:42:47 -08003250 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08003251 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003252 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003253
Mathieu Chartier268764d2016-09-13 12:09:38 -07003254 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003255 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003256 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07003257 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003258
Vladimir Marko05792b92015-08-03 11:56:49 +01003259 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods(), image_pointer_size_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003260
Andreas Gampe51829322014-08-25 15:05:04 -07003261 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07003262
Ian Rogersdfb325e2013-10-30 01:00:44 -07003263 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003264 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003265 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3266 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003267 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003268 klass->SetFinalizable();
3269 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003270 std::string temp;
3271 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003272 // The Enum class declares a "final" finalize() method to prevent subclasses from
3273 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3274 // subclasses, so we exclude it here.
3275 // We also want to avoid setting the flag on Object, where we know that finalize() is
3276 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003277 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3278 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003279 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003280 }
3281 }
3282 }
3283 } else if (method_name[0] == '<') {
3284 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003285 bool is_init = (strcmp("<init>", method_name) == 0);
3286 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003287 if (UNLIKELY(!is_init && !is_clinit)) {
3288 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3289 } else {
3290 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3291 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003292 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003293 access_flags |= kAccConstructor;
3294 }
3295 }
3296 }
3297 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003298}
3299
Ian Rogers7b078e82014-09-10 14:44:24 -07003300void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003301 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003302 self,
3303 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003304 Runtime::Current()->GetLinearAlloc());
3305 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003306 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003307}
3308
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003309void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003310 ObjPtr<mirror::DexCache> dex_cache) {
3311 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003312 boot_class_path_.push_back(&dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003313 RegisterBootClassPathDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003314}
3315
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003316void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003317 ObjPtr<mirror::DexCache> dex_cache,
3318 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003319 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003320 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003321 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003322 // For app images, the dex cache location may be a suffix of the dex file location since the
3323 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003324 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3325 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003326 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3327 std::string dex_file_location = dex_file.GetLocation();
3328 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003329 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003330 // Take suffix.
3331 const std::string dex_file_suffix = dex_file_location.substr(
3332 dex_file_location.length() - dex_cache_length,
3333 dex_cache_length);
3334 // Example dex_cache location is SettingsProvider.apk and
3335 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003336 CHECK_EQ(dex_cache_location, dex_file_suffix);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003337 // Clean up pass to remove null dex caches.
3338 // Null dex caches can occur due to class unloading and we are lazily removing null entries.
3339 JavaVMExt* const vm = self->GetJniEnv()->vm;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003340 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3341 DexCacheData data = *it;
3342 if (self->IsJWeakCleared(data.weak_root)) {
3343 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003344 it = dex_caches_.erase(it);
3345 } else {
3346 ++it;
3347 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003348 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003349 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003350 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003351 DexCacheData data;
3352 data.weak_root = dex_cache_jweak;
3353 data.dex_file = dex_cache->GetDexFile();
Vladimir Marko942fd312017-01-16 20:52:19 +00003354 data.resolved_methods = dex_cache->GetResolvedMethods();
Vladimir Markocd556b02017-02-03 11:47:34 +00003355 data.class_table = ClassTableForClassLoader(class_loader);
3356 DCHECK(data.class_table != nullptr);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003357 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003358}
3359
Vladimir Markocd556b02017-02-03 11:47:34 +00003360ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3361 return data.IsValid()
3362 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3363 : nullptr;
3364}
3365
3366ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3367 Thread* self,
3368 ObjPtr<mirror::DexCache> dex_cache,
3369 const DexCacheData& data,
3370 ObjPtr<mirror::ClassLoader> class_loader) {
3371 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3372 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3373 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3374 "Attempt to register dex file %s with multiple class loaders",
3375 data.dex_file->GetLocation().c_str());
3376 return nullptr;
3377 }
3378 return dex_cache;
3379}
3380
3381ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3382 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003383 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003384 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003385 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003386 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003387 old_data = FindDexCacheDataLocked(dex_file);
3388 }
3389 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3390 if (old_dex_cache != nullptr) {
3391 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003392 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003393 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3394 DCHECK(linear_alloc != nullptr);
3395 ClassTable* table;
3396 {
3397 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3398 table = InsertClassTableForClassLoader(class_loader);
3399 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003400 // Don't alloc while holding the lock, since allocation may need to
3401 // suspend all threads and another thread may need the dex_lock_ to
3402 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003403 StackHandleScope<3> hs(self);
3404 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003405 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003406 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3407 self,
3408 dex_file)));
3409 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003410 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003411 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003412 old_data = FindDexCacheDataLocked(dex_file);
3413 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003414 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003415 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3416 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3417 // that the arrays are null.
3418 mirror::DexCache::InitializeDexCache(self,
3419 h_dex_cache.Get(),
3420 h_location.Get(),
3421 &dex_file,
3422 linear_alloc,
3423 image_pointer_size_);
3424 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003425 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003426 }
3427 if (old_dex_cache != nullptr) {
3428 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3429 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003430 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003431 self->ClearException();
3432 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3433 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3434 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003435 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003436 self->AssertPendingOOMException();
3437 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003438 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003439 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003440 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003441}
3442
Vladimir Markocd556b02017-02-03 11:47:34 +00003443void ClassLinker::RegisterBootClassPathDexFile(const DexFile& dex_file,
3444 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003445 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003446 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader */ nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003447}
3448
Vladimir Markocd556b02017-02-03 11:47:34 +00003449bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003450 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003451 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003452}
3453
Vladimir Markocd556b02017-02-03 11:47:34 +00003454ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3455 ReaderMutexLock mu(self, *Locks::dex_lock_);
3456 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, FindDexCacheDataLocked(dex_file));
3457 if (dex_cache != nullptr) {
3458 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003459 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003460 // Failure, dump diagnostic and abort.
Vladimir Markocd556b02017-02-03 11:47:34 +00003461 std::string location(dex_file.GetLocation());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003462 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003463 if (DecodeDexCache(self, data) != nullptr) {
3464 LOG(ERROR) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003465 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003466 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003467 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003468 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003469}
3470
Vladimir Markocd556b02017-02-03 11:47:34 +00003471ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3472 const DexFile* dex_file = dex_cache->GetDexFile();
3473 DCHECK(dex_file != nullptr);
3474 ReaderMutexLock mu(self, *Locks::dex_lock_);
3475 // Search assuming unique-ness of dex file.
3476 for (const DexCacheData& data : dex_caches_) {
3477 // Avoid decoding (and read barriers) other unrelated dex caches.
3478 if (data.dex_file == dex_file) {
3479 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3480 if (registered_dex_cache != nullptr) {
3481 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3482 return data.class_table;
3483 }
3484 }
3485 }
3486 return nullptr;
3487}
3488
3489ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3490 // Search assuming unique-ness of dex file.
3491 for (const DexCacheData& data : dex_caches_) {
3492 // Avoid decoding (and read barriers) other unrelated dex caches.
3493 if (data.dex_file == &dex_file) {
3494 return data;
3495 }
3496 }
3497 return DexCacheData();
3498}
3499
Mathieu Chartiere401d142015-04-22 13:56:20 -07003500void ClassLinker::FixupDexCaches(ArtMethod* resolution_method) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003501 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003502 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003503 for (const DexCacheData& data : dex_caches_) {
3504 if (!self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07003505 ObjPtr<mirror::DexCache> dex_cache = ObjPtr<mirror::DexCache>::DownCast(
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003506 self->DecodeJObject(data.weak_root));
3507 if (dex_cache != nullptr) {
3508 dex_cache->Fixup(resolution_method, image_pointer_size_);
3509 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003510 }
Ian Rogers19846512012-02-24 11:42:47 -08003511 }
3512}
3513
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003514mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003515 ObjPtr<mirror::Class> klass =
3516 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003517 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003518 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003519 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003520 }
3521 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003522}
3523
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003524mirror::Class* ClassLinker::InitializePrimitiveClass(ObjPtr<mirror::Class> primitive_class,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003525 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003526 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003527 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003528 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003529 StackHandleScope<1> hs(self);
3530 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003531 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003532 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3533 h_class->SetPrimitiveType(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003534 h_class->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003535 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003536 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003537 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3538 h_class.Get(),
3539 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003540 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003541 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003542}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003543
Brian Carlstrombe977852011-07-19 14:54:54 -07003544// Create an array class (i.e. the class object for the array, not the
3545// array itself). "descriptor" looks like "[C" or "[[[[B" or
3546// "[Ljava/lang/String;".
3547//
3548// If "descriptor" refers to an array of primitives, look up the
3549// primitive type's internally-generated class object.
3550//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003551// "class_loader" is the class loader of the class that's referring to
3552// us. It's used to ensure that we're looking for the element type in
3553// the right context. It does NOT become the class loader for the
3554// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003555//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003556// Returns null with an exception raised on failure.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003557mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003558 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003559 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003560 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003561 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003562 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3563 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003564 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003565 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003566 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003567 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3568 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003569 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003570 DCHECK(self->IsExceptionPending());
3571 return nullptr;
3572 } else {
3573 self->ClearException();
3574 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003575 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003576 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3577 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3578 return nullptr;
3579 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003580 // See if the component type is already loaded. Array classes are
3581 // always associated with the class loader of their underlying
3582 // element type -- an array of Strings goes with the loader for
3583 // java/lang/String -- so we need to look for it there. (The
3584 // caller should have checked for the existence of the class
3585 // before calling here, but they did so with *their* class loader,
3586 // not the component type's loader.)
3587 //
3588 // If we find it, the caller adds "loader" to the class' initiating
3589 // loader list, which should prevent us from going through this again.
3590 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003591 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003592 // are the same, because our caller (FindClass) just did the
3593 // lookup. (Even if we get this wrong we still have correct behavior,
3594 // because we effectively do this lookup again when we add the new
3595 // class to the hash table --- necessary because of possible races with
3596 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003597 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003598 ObjPtr<mirror::Class> new_class =
3599 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003600 if (new_class != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003601 return new_class.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003602 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003603 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003604
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003605 // Fill out the fields in the Class.
3606 //
3607 // It is possible to execute some methods against arrays, because
3608 // all arrays are subclasses of java_lang_Object_, so we need to set
3609 // up a vtable. We can just point at the one in java_lang_Object_.
3610 //
3611 // Array classes are simple enough that we don't need to do a full
3612 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003613 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003614 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003615 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003616 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003617 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003618 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003619 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003620 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003621 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003622 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003623 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003624 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003625 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07003626 } else if (strcmp(descriptor, "[J") == 0) {
3627 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003628 }
3629 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003630 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003631 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003632 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003633 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003634 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003635 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003636 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003637 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003638 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003639 DCHECK(new_class->GetComponentType() != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003640 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003641 new_class->SetSuperClass(java_lang_Object);
3642 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003643 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003644 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07003645 if (component_type->IsPrimitive()) {
3646 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
3647 } else {
3648 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
3649 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003650 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00003651 new_class->PopulateEmbeddedVTable(image_pointer_size_);
3652 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
3653 new_class->SetImt(object_imt, image_pointer_size_);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003654 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003655 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003656 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003657
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003658 // All arrays have java/lang/Cloneable and java/io/Serializable as
3659 // interfaces. We need to set that up here, so that stuff like
3660 // "instanceof" works right.
3661 //
3662 // Note: The GC could run during the call to FindSystemClass,
3663 // so we need to make sure the class object is GC-valid while we're in
3664 // there. Do this by clearing the interface list so the GC will just
3665 // think that the entries are null.
3666
3667
3668 // Use the single, global copies of "interfaces" and "iftable"
3669 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003670 {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003671 ObjPtr<mirror::IfTable> array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003672 CHECK(array_iftable != nullptr);
3673 new_class->SetIfTable(array_iftable);
3674 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003675
Elliott Hughes00626c22013-06-14 15:04:14 -07003676 // Inherit access flags from the component type.
3677 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3678 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3679 access_flags &= kAccJavaFlagsMask;
3680 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003681 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003682 access_flags |= kAccAbstract | kAccFinal;
3683 access_flags &= ~kAccInterface;
3684
3685 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003686
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003687 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003688 if (existing == nullptr) {
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003689 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003690 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003691 }
3692 // Another thread must have loaded the class after we
3693 // started but before we finished. Abandon what we've
3694 // done.
3695 //
3696 // (Yes, this happens.)
3697
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003698 return existing.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003699}
3700
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003701mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003702 switch (type) {
3703 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003704 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003705 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003706 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003707 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003708 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003709 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003710 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003711 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003712 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003713 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003714 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003715 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003716 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003717 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003718 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003719 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003720 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003721 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003722 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003723 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003724 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003725 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003726 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003727}
3728
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003729mirror::Class* ClassLinker::InsertClass(const char* descriptor, ObjPtr<mirror::Class> klass, size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003730 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003731 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003732 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003733 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003734 source += " from ";
3735 source += dex_cache->GetLocation()->ToModifiedUtf8();
3736 }
3737 LOG(INFO) << "Loaded class " << descriptor << source;
3738 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003739 {
3740 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003741 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07003742 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003743 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003744 if (existing != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003745 return existing.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07003746 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003747 VerifyObject(klass);
3748 class_table->InsertWithHash(klass, hash);
3749 if (class_loader != nullptr) {
3750 // This is necessary because we need to have the card dirtied for remembered sets.
3751 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3752 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00003753 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07003754 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003755 }
3756 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003757 if (kIsDebugBuild) {
3758 // Test that copied methods correctly can find their holder.
3759 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
3760 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
3761 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08003762 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003763 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003764}
3765
Vladimir Marko1998cd02017-01-13 13:02:58 +00003766void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Vladimir Marko9b03cb42017-02-16 16:37:03 +00003767 if (!kUseReadBarrier) {
3768 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3769 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
3770 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
3771 new_bss_roots_boot_oat_files_.push_back(oat_file);
3772 }
3773 } else {
3774 LOG(FATAL) << "UNREACHABLE";
Vladimir Marko1998cd02017-01-13 13:02:58 +00003775 }
3776}
3777
Alex Lighte64300b2015-12-15 15:02:47 -08003778// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003779void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08003780 LengthPrefixedArray<ArtMethod>* new_methods) {
3781 klass->SetMethodsPtrUnchecked(new_methods,
3782 klass->NumDirectMethods(),
3783 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003784 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003785 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003786}
3787
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003788mirror::Class* ClassLinker::LookupClass(Thread* self,
3789 const char* descriptor,
3790 size_t hash,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003791 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01003792 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3793 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3794 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003795 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01003796 if (result != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003797 return result.Ptr();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003798 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003799 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01003800 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003801}
3802
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003803class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
3804 public:
3805 explicit MoveClassTableToPreZygoteVisitor() {}
3806
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003807 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003808 REQUIRES(Locks::classlinker_classes_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003809 REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003810 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07003811 if (class_table != nullptr) {
3812 class_table->FreezeSnapshot();
3813 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003814 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003815};
3816
3817void ClassLinker::MoveClassTableToPreZygote() {
3818 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3819 boot_class_table_.FreezeSnapshot();
3820 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003821 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003822}
3823
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003824// Look up classes by hash and descriptor and put all matching ones in the result array.
3825class LookupClassesVisitor : public ClassLoaderVisitor {
3826 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003827 LookupClassesVisitor(const char* descriptor,
3828 size_t hash,
3829 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003830 : descriptor_(descriptor),
3831 hash_(hash),
3832 result_(result) {}
3833
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003834 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003835 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003836 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003837 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003838 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
3839 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003840 result_->push_back(klass);
3841 }
3842 }
3843
3844 private:
3845 const char* const descriptor_;
3846 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003847 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003848};
3849
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003850void ClassLinker::LookupClasses(const char* descriptor,
3851 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003852 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003853 Thread* const self = Thread::Current();
3854 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003855 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003856 ObjPtr<mirror::Class> klass = boot_class_table_.Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003857 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003858 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003859 result.push_back(klass);
3860 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003861 LookupClassesVisitor visitor(descriptor, hash, &result);
3862 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003863}
3864
Alex Lightf1f10492015-10-07 16:08:36 -07003865bool ClassLinker::AttemptSupertypeVerification(Thread* self,
3866 Handle<mirror::Class> klass,
3867 Handle<mirror::Class> supertype) {
3868 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003869 DCHECK(klass != nullptr);
3870 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07003871
Alex Lightf1f10492015-10-07 16:08:36 -07003872 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
3873 VerifyClass(self, supertype);
3874 }
3875 if (supertype->IsCompileTimeVerified()) {
3876 // Either we are verified or we soft failed and need to retry at runtime.
3877 return true;
3878 }
3879 // If we got this far then we have a hard failure.
3880 std::string error_msg =
3881 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07003882 klass->PrettyDescriptor().c_str(),
3883 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07003884 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003885 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07003886 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003887 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003888 // Set during VerifyClass call (if at all).
3889 self->ClearException();
3890 }
3891 // Change into a verify error.
3892 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08003893 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003894 self->GetException()->SetCause(cause.Get());
3895 }
3896 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
3897 if (Runtime::Current()->IsAotCompiler()) {
3898 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3899 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07003900 // Need to grab the lock to change status.
3901 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko72ab6842017-01-20 19:32:50 +00003902 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07003903 return false;
3904}
3905
Andreas Gampecc1b5352016-12-01 16:58:38 -08003906// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
3907// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
3908// before.
3909static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
3910 REQUIRES_SHARED(Locks::mutator_lock_) {
3911 if (!klass->WasVerificationAttempted()) {
3912 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
3913 klass->SetVerificationAttempted();
3914 }
3915}
3916
Nicolas Geoffray08025182016-10-25 17:20:18 +01003917verifier::MethodVerifier::FailureKind ClassLinker::VerifyClass(
3918 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07003919 {
3920 // TODO: assert that the monitor on the Class is held
3921 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003922
Andreas Gampe884f3b82016-03-30 19:52:58 -07003923 // Is somebody verifying this now?
3924 mirror::Class::Status old_status = klass->GetStatus();
3925 while (old_status == mirror::Class::kStatusVerifying ||
3926 old_status == mirror::Class::kStatusVerifyingAtRuntime) {
3927 lock.WaitIgnoringInterrupts();
Alex Light06039ba2016-04-04 13:23:14 -07003928 CHECK(klass->IsErroneous() || (klass->GetStatus() > old_status))
David Sehr709b0702016-10-13 09:12:37 -07003929 << "Class '" << klass->PrettyClass()
3930 << "' performed an illegal verification state transition from " << old_status
3931 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003932 old_status = klass->GetStatus();
3933 }
jeffhao98eacac2011-09-14 16:11:53 -07003934
Andreas Gampe884f3b82016-03-30 19:52:58 -07003935 // The class might already be erroneous, for example at compile time if we attempted to verify
3936 // this class as a parent to another.
3937 if (klass->IsErroneous()) {
3938 ThrowEarlierClassFailure(klass.Get());
Nicolas Geoffray08025182016-10-25 17:20:18 +01003939 return verifier::MethodVerifier::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07003940 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003941
Andreas Gampe884f3b82016-03-30 19:52:58 -07003942 // Don't attempt to re-verify if already sufficiently verified.
3943 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003944 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Nicolas Geoffray08025182016-10-25 17:20:18 +01003945 return verifier::MethodVerifier::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07003946 }
3947 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Nicolas Geoffray08025182016-10-25 17:20:18 +01003948 return verifier::MethodVerifier::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07003949 }
jeffhao98eacac2011-09-14 16:11:53 -07003950
Andreas Gampe884f3b82016-03-30 19:52:58 -07003951 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
3952 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
3953 } else {
3954 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07003955 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003956 CHECK(!Runtime::Current()->IsAotCompiler());
3957 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
3958 }
3959
3960 // Skip verification if disabled.
3961 if (!Runtime::Current()->IsVerificationEnabled()) {
3962 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003963 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Nicolas Geoffray08025182016-10-25 17:20:18 +01003964 return verifier::MethodVerifier::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07003965 }
Jeff Hao4a200f52014-04-01 14:58:49 -07003966 }
3967
Ian Rogers9ffb0392012-09-10 11:56:50 -07003968 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003969 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07003970 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
3971 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003972 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07003973 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Nicolas Geoffray08025182016-10-25 17:20:18 +01003974 return verifier::MethodVerifier::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07003975 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08003976
Alex Lightf1f10492015-10-07 16:08:36 -07003977 // Verify all default super-interfaces.
3978 //
3979 // (1) Don't bother if the superclass has already had a soft verification failure.
3980 //
3981 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
3982 // recursive initialization by themselves. This is because when an interface is initialized
3983 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
3984 // but choose not to for an optimization. If the interfaces is being verified due to a class
3985 // initialization (which would need all the default interfaces to be verified) the class code
3986 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003987 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07003988 && !klass->IsInterface()) { // See (2)
3989 int32_t iftable_count = klass->GetIfTableCount();
3990 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
3991 // Loop through all interfaces this class has defined. It doesn't matter the order.
3992 for (int32_t i = 0; i < iftable_count; i++) {
3993 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003994 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07003995 // We only care if we have default interfaces and can skip if we are already verified...
3996 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
3997 continue;
3998 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
3999 // We had a hard failure while verifying this interface. Just return immediately.
4000 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Nicolas Geoffray08025182016-10-25 17:20:18 +01004001 return verifier::MethodVerifier::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004002 } else if (UNLIKELY(!iface->IsVerified())) {
4003 // We softly failed to verify the iface. Stop checking and clean up.
4004 // Put the iface into the supertype handle so we know what caused us to fail.
4005 supertype.Assign(iface.Get());
4006 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004007 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004008 }
4009 }
4010
Alex Lightf1f10492015-10-07 16:08:36 -07004011 // At this point if verification failed, then supertype is the "first" supertype that failed
4012 // verification (without a specific order). If verification succeeded, then supertype is either
4013 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004014 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004015 supertype.Get() == klass->GetSuperClass() ||
4016 !supertype->IsVerified());
4017
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004018 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004019 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004020 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004021 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004022 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4023 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004024 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4025 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004026
Ian Rogers62d6c772013-02-27 08:32:07 -08004027 std::string error_msg;
Nicolas Geoffray08025182016-10-25 17:20:18 +01004028 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004029 if (!preverified) {
Andreas Gampe53e32d12015-12-09 21:03:23 -08004030 Runtime* runtime = Runtime::Current();
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004031 verifier_failure = verifier::MethodVerifier::VerifyClass(self,
4032 klass.Get(),
Andreas Gampe53e32d12015-12-09 21:03:23 -08004033 runtime->GetCompilerCallbacks(),
4034 runtime->IsAotCompiler(),
Andreas Gampe7fe30232016-03-25 16:58:00 -07004035 log_level,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004036 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004037 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004038
4039 // Verification is done, grab the lock again.
4040 ObjectLock<mirror::Class> lock(self, klass);
4041
jeffhaof1e6b7c2012-06-05 18:33:30 -07004042 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07004043 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004044 VLOG(class_linker) << "Soft verification failure in class "
4045 << klass->PrettyDescriptor()
4046 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4047 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004048 }
Ian Rogers1f539342012-10-03 21:09:42 -07004049 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004050 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004051 ResolveClassExceptionHandlerTypes(klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004052 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004053 // Even though there were no verifier failures we need to respect whether the super-class and
4054 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004055 if (supertype == nullptr || supertype->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004056 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004057 } else {
Alex Lightf1f10492015-10-07 16:08:36 -07004058 CHECK_EQ(supertype->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004059 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004060 // Pretend a soft failure occurred so that we don't consider the class verified below.
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004061 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004062 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004063 } else {
4064 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
4065 // Soft failures at compile time should be retried at runtime. Soft
4066 // failures at runtime will be handled by slow paths in the generated
4067 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004068 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004069 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004070 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004071 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004072 // As this is a fake verified status, make sure the methods are _not_ marked
4073 // kAccSkipAccessChecks later.
4074 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004075 }
4076 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004077 } else {
David Sehr709b0702016-10-13 09:12:37 -07004078 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004079 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4080 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004081 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004082 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko72ab6842017-01-20 19:32:50 +00004083 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004084 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004085 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004086 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004087 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004088 // method.
4089 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004090 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004091 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004092
4093 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4094 // Never skip access checks if the verification soft fail is forced.
4095 // Mark the class as having a verification attempt to avoid re-running the verifier.
4096 klass->SetVerificationAttempted();
4097 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004098 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004099 }
Andreas Gampe48498592014-09-10 19:48:05 -07004100 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004101 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004102}
4103
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004104bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004105 ObjPtr<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004106 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004107 // If we're compiling, we can only verify the class using the oat file if
4108 // we are not compiling the image or if the class we're verifying is not part of
4109 // the app. In other words, we will only check for preverification of bootclasspath
4110 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004111 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004112 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07004113 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004114 return false;
4115 }
4116 // We are compiling an app (not the image).
4117
4118 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004119 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004120 return false;
4121 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004122 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004123
Richard Uhler07b3c232015-03-31 15:57:54 -07004124 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004125 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004126 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004127 return false;
4128 }
4129
Andreas Gampe76bd8802014-12-10 16:43:58 -08004130 // We may be running with a preopted oat file but without image. In this case,
Igor Murashkindf707e42016-02-02 16:56:50 -08004131 // we don't skip verification of skip_access_checks classes to ensure we initialize
Andreas Gampe76bd8802014-12-10 16:43:58 -08004132 // dex caches with all types resolved during verification.
4133 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
4134 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
4135 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
4136 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004137 if (!Runtime::Current()->IsAotCompiler() &&
Jeff Haodcdc85b2015-12-04 14:06:18 -08004138 !Runtime::Current()->GetHeap()->HasBootImageSpace() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08004139 klass->GetClassLoader() != nullptr) {
4140 return false;
4141 }
4142
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004143 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004144 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004145 if (oat_file_class_status == mirror::Class::kStatusVerified ||
4146 oat_file_class_status == mirror::Class::kStatusInitialized) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004147 return true;
4148 }
4149 // If we only verified a subset of the classes at compile time, we can end up with classes that
4150 // were resolved by the verifier.
4151 if (oat_file_class_status == mirror::Class::kStatusResolved) {
4152 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004153 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004154 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004155 // Compile time verification failed with a soft error. Compile time verification can fail
4156 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004157 // class ... {
4158 // Foo x;
4159 // .... () {
4160 // if (...) {
4161 // v1 gets assigned a type of resolved class Foo
4162 // } else {
4163 // v1 gets assigned a type of unresolved class Bar
4164 // }
4165 // iput x = v1
4166 // } }
4167 // when we merge v1 following the if-the-else it results in Conflict
4168 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4169 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4170 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4171 // at compile time).
4172 return false;
4173 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004174 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004175 // Compile time verification failed with a hard error. This is caused by invalid instructions
4176 // in the class. These errors are unrecoverable.
4177 return false;
4178 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004179 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004180 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4181 // not loading the class.
4182 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4183 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004184 return false;
4185 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004186 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004187 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004188 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004189 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004190 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004191}
4192
Alex Light5a559862016-01-29 12:24:48 -08004193void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004194 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004195 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004196 }
4197}
4198
Alex Light5a559862016-01-29 12:24:48 -08004199void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004200 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
Alex Light5a559862016-01-29 12:24:48 -08004201 const DexFile::CodeItem* code_item =
4202 method->GetDexFile()->GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004203 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004204 return; // native or abstract method
4205 }
4206 if (code_item->tries_size_ == 0) {
4207 return; // nothing to process
4208 }
Ian Rogers13735952014-10-08 12:43:28 -07004209 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004210 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004211 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4212 CatchHandlerIterator iterator(handlers_ptr);
4213 for (; iterator.HasNext(); iterator.Next()) {
4214 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4215 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004216 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004217 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004218 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004219 DCHECK(Thread::Current()->IsExceptionPending());
4220 Thread::Current()->ClearException();
4221 }
4222 }
4223 }
4224 handlers_ptr = iterator.EndDataPointer();
4225 }
4226}
4227
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004228mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4229 jstring name,
4230 jobjectArray interfaces,
4231 jobject loader,
4232 jobjectArray methods,
4233 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004234 Thread* self = soa.Self();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004235 StackHandleScope<10> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004236 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004237 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004238 if (klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004239 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004240 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004241 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004242 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004243 klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004244 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4245 // the methods.
4246 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
Mathieu Chartier1a5337f2016-10-13 13:48:23 -07004247 klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08004248 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier1a5337f2016-10-13 13:48:23 -07004249 klass->SetName(soa.Decode<mirror::String>(name));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004250 klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004251 // Object has an empty iftable, copy it for that reason.
4252 klass->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004253 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004254 std::string descriptor(GetDescriptorForProxy(klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004255 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004256
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004257 // Needs to be before we insert the class so that the allocator field is set.
4258 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(klass->GetClassLoader());
4259
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004260 // Insert the class before loading the fields as the field roots
4261 // (ArtField::declaring_class_) are only visited from the class
4262 // table. There can't be any suspend points between inserting the
4263 // class and setting the field arrays below.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004264 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004265 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004266
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004267 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004268 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004269 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004270 klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004271
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004272 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4273 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004274 ArtField& interfaces_sfield = sfields->At(0);
4275 interfaces_sfield.SetDexFieldIndex(0);
4276 interfaces_sfield.SetDeclaringClass(klass.Get());
4277 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004278
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004279 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004280 ArtField& throws_sfield = sfields->At(1);
4281 throws_sfield.SetDexFieldIndex(1);
4282 throws_sfield.SetDeclaringClass(klass.Get());
4283 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004284
Ian Rogers466bb252011-10-14 03:29:56 -07004285 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004286 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004287
Alex Lighte64300b2015-12-15 15:02:47 -08004288 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004289 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004290 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
David Sehr709b0702016-10-13 09:12:37 -07004291 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004292 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004293
4294 // Create the methods array.
4295 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4296 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004297 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4298 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004299 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004300 self->AssertPendingOOMException();
4301 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004302 }
Alex Lighte64300b2015-12-15 15:02:47 -08004303 klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
4304
4305 // Create the single direct method.
4306 CreateProxyConstructor(klass, klass->GetDirectMethodUnchecked(0, image_pointer_size_));
4307
4308 // Create virtual method using specified prototypes.
4309 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004310 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004311 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4312 auto* prototype = h_methods->Get(i)->GetArtMethod();
4313 CreateProxyMethod(klass, prototype, virtual_method);
4314 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4315 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004316 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004317
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004318 // The super class is java.lang.reflect.Proxy
4319 klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy));
4320 // Now effectively in the loaded state.
4321 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004322 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004323
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004324 MutableHandle<mirror::Class> new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004325 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004326 // Must hold lock on object when resolved.
4327 ObjectLock<mirror::Class> resolution_lock(self, klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004328 // Link the fields and virtual methods, creating vtable and iftables.
4329 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004330 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004331 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004332 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00004333 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004334 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004335 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004336 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004337 CHECK(klass->IsRetired());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004338 CHECK_NE(klass.Get(), new_class.Get());
4339 klass.Assign(new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004340
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004341 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004342 interfaces_sfield.SetObject<false>(
4343 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004344 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004345 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4346 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004347 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004348 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004349
4350 {
4351 // Lock on klass is released. Lock new class object.
4352 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004353 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004354 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004355
4356 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004357 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004358 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004359 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4360
Ian Rogersc2b44472011-12-14 21:17:17 -08004361 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004362 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4363 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004364 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004365 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004366
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004367 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004368 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004369 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004370 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004371 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004372
4373 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004374 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004375 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004376
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004377 CHECK_EQ(klass.Get()->GetInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004378 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004379 CHECK_EQ(klass.Get()->GetThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004380 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004381 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004382 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004383}
4384
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004385std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004386 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004387 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004388 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004389 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4390}
4391
Mathieu Chartiere401d142015-04-22 13:56:20 -07004392void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4393 // Create constructor for Proxy that must initialize the method.
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004394 CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 23u);
4395
Mathieu Chartiere401d142015-04-22 13:56:20 -07004396 ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->GetDirectMethodUnchecked(
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004397 8, image_pointer_size_);
Igor Murashkine3d4ff52016-02-02 10:46:42 -08004398 DCHECK_EQ(std::string(proxy_constructor->GetName()), "<init>");
Sebastien Hertzae94e352014-08-27 15:32:56 +02004399 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4400 // constructor method.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004401 GetClassRoot(kJavaLangReflectProxy)->GetDexCache()->SetResolvedMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -07004402 proxy_constructor->GetDexMethodIndex(), proxy_constructor, image_pointer_size_);
Jeff Haodb8a6642014-08-14 17:18:52 -07004403 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4404 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004405 DCHECK(out != nullptr);
4406 out->CopyFrom(proxy_constructor, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004407 // Make this constructor public and fix the class to be our Proxy version
Mathieu Chartiere401d142015-04-22 13:56:20 -07004408 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) | kAccPublic);
4409 out->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004410}
4411
Mathieu Chartiere401d142015-04-22 13:56:20 -07004412void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004413 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004414 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4415 CHECK_STREQ(np->GetName(), "<init>");
4416 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004417 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004418}
4419
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004420void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004421 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004422 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4423 // prototype method
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004424 auto* dex_cache = prototype->GetDeclaringClass()->GetDexCache();
4425 // Avoid dirtying the dex cache unless we need to.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004426 if (dex_cache->GetResolvedMethod(prototype->GetDexMethodIndex(), image_pointer_size_) !=
4427 prototype) {
4428 dex_cache->SetResolvedMethod(
4429 prototype->GetDexMethodIndex(), prototype, image_pointer_size_);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004430 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004431 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004432 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004433 DCHECK(out != nullptr);
4434 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004435
Alex Lighte9dd04f2016-03-16 16:09:45 -07004436 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004437 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004438 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4439 // preference to the invocation handler.
4440 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4441 // Make the method final.
4442 const uint32_t kAddFlags = kAccFinal;
4443 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4444
4445 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4446 // method they copy might (if it's a default method).
4447 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004448
Ian Rogers466bb252011-10-14 03:29:56 -07004449 // At runtime the method looks like a reference and argument saving method, clone the code
4450 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004451 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004452}
Jesse Wilson95caa792011-10-12 18:14:17 -04004453
Mathieu Chartiere401d142015-04-22 13:56:20 -07004454void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004455 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004456 CHECK(!prototype->IsFinal());
4457 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004458 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004459
4460 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4461 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Vladimir Marko05792b92015-08-03 11:56:49 +01004462 CHECK(prototype->HasSameDexCacheResolvedMethods(method, image_pointer_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07004463 auto* np = method->GetInterfaceMethodIfProxy(image_pointer_size_);
4464 CHECK_EQ(prototype->GetDeclaringClass()->GetDexCache(), np->GetDexCache());
Ian Rogers19846512012-02-24 11:42:47 -08004465 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4466
Mathieu Chartiere401d142015-04-22 13:56:20 -07004467 CHECK_STREQ(np->GetName(), prototype->GetName());
4468 CHECK_STREQ(np->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004469 // More complex sanity - via dex cache
Vladimir Marko942fd312017-01-16 20:52:19 +00004470 CHECK_EQ(np->GetReturnType(true /* resolve */), prototype->GetReturnType(true /* resolve */));
Jesse Wilson95caa792011-10-12 18:14:17 -04004471}
4472
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004473bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004474 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004475 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004476 return true;
4477 }
4478 if (!can_init_statics) {
4479 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004480 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004481 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004482 return false;
4483 }
4484 // Check if there are encoded static values needing initialization.
4485 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004486 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004487 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004488 if (dex_class_def->static_values_off_ != 0) {
4489 return false;
4490 }
4491 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004492 // If we are a class we need to initialize all interfaces with default methods when we are
4493 // initialized. Check all of them.
4494 if (!klass->IsInterface()) {
4495 size_t num_interfaces = klass->GetIfTableCount();
4496 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004497 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07004498 if (iface->HasDefaultMethods() &&
4499 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
4500 return false;
4501 }
4502 }
4503 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004504 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004505 if (klass->IsInterface() || !klass->HasSuperClass()) {
4506 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004507 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004508 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07004509 if (!can_init_parents && !super_class->IsInitialized()) {
4510 return false;
4511 }
4512 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004513}
4514
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004515bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
4516 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004517 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4518
4519 // Are we already initialized and therefore done?
4520 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4521 // an initialized class will never change its state.
4522 if (klass->IsInitialized()) {
4523 return true;
4524 }
4525
4526 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004527 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004528 return false;
4529 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004530
Ian Rogers7b078e82014-09-10 14:44:24 -07004531 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004532 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004533 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004534 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004535
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004536 // Re-check under the lock in case another thread initialized ahead of us.
4537 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004538 return true;
4539 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004540
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004541 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004542 if (klass->IsErroneous()) {
Andreas Gampecb086952015-11-02 16:20:00 -08004543 ThrowEarlierClassFailure(klass.Get(), true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07004544 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004545 return false;
4546 }
4547
Vladimir Marko72ab6842017-01-20 19:32:50 +00004548 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
4549 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004550
4551 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004552 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004553 if (!klass->IsVerified()) {
4554 // We failed to verify, expect either the klass to be erroneous or verification failed at
4555 // compile time.
4556 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07004557 // The class is erroneous. This may be a verifier error, or another thread attempted
4558 // verification and/or initialization and failed. We can distinguish those cases by
4559 // whether an exception is already pending.
4560 if (self->IsExceptionPending()) {
4561 // Check that it's a VerifyError.
4562 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07004563 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07004564 } else {
4565 // Check that another thread attempted initialization.
4566 DCHECK_NE(0, klass->GetClinitThreadId());
4567 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
4568 // Need to rethrow the previous failure now.
4569 ThrowEarlierClassFailure(klass.Get(), true);
4570 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07004571 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004572 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004573 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004574 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004575 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004576 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004577 } else {
4578 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004579 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07004580
4581 // A separate thread could have moved us all the way to initialized. A "simple" example
4582 // involves a subclass of the current class being initialized at the same time (which
4583 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00004584 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07004585 if (klass->IsInitialized()) {
4586 return true;
4587 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004588 }
4589
Brian Carlstromd1422f82011-09-28 11:37:09 -07004590 // If the class is kStatusInitializing, either this thread is
4591 // initializing higher up the stack or another thread has beat us
4592 // to initializing and we need to wait. Either way, this
4593 // invocation of InitializeClass will not be responsible for
4594 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004595 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004596 // Could have got an exception during verification.
4597 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004598 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004599 return false;
4600 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004601 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004602 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004603 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004604 return true;
4605 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004606 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004607 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004608 }
4609
4610 if (!ValidateSuperClassDescriptors(klass)) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00004611 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004612 return false;
4613 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004614 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004615
David Sehr709b0702016-10-13 09:12:37 -07004616 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07004617 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004618
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004619 // From here out other threads may observe that we're initializing and so changes of state
4620 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004621 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004622 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004623
4624 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004625 }
4626
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004627 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004628 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004629 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004630 if (!super_class->IsInitialized()) {
4631 CHECK(!super_class->IsInterface());
4632 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004633 StackHandleScope<1> hs(self);
4634 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004635 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004636 if (!super_initialized) {
4637 // The super class was verified ahead of entering initializing, we should only be here if
4638 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004639 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004640 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07004641 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004642 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004643 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004644 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004645 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004646 // Initialization failed because the super-class is erroneous.
Vladimir Marko72ab6842017-01-20 19:32:50 +00004647 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004648 return false;
4649 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004650 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004651 }
4652
Alex Lighteb7c1442015-08-31 13:17:42 -07004653 if (!klass->IsInterface()) {
4654 // Initialize interfaces with default methods for the JLS.
4655 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004656 // Only setup the (expensive) handle scope if we actually need to.
4657 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07004658 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07004659 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
4660 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004661 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004662 CHECK(handle_scope_iface != nullptr);
Alex Light56a40f52015-10-14 11:07:41 -07004663 CHECK(handle_scope_iface->IsInterface());
4664 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
4665 // We have already done this for this interface. Skip it.
4666 continue;
4667 }
4668 // We cannot just call initialize class directly because we need to ensure that ALL
4669 // interfaces with default methods are initialized. Non-default interface initialization
4670 // will not affect other non-default super-interfaces.
4671 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
4672 handle_scope_iface,
4673 can_init_statics,
4674 can_init_parents);
4675 if (!iface_initialized) {
4676 ObjectLock<mirror::Class> lock(self, klass);
4677 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko72ab6842017-01-20 19:32:50 +00004678 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07004679 return false;
4680 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004681 }
4682 }
4683 }
4684
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004685 const size_t num_static_fields = klass->NumStaticFields();
4686 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004687 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004688 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004689 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004690 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004691 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004692 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004693
4694 // Eagerly fill in static fields so that the we don't have to do as many expensive
4695 // Class::FindStaticField in ResolveField.
4696 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004697 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004698 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004699 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004700 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004701 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004702 } else {
4703 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004704 }
4705 }
4706
David Sehr9323e6e2016-09-13 08:58:35 -07004707 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_file,
4708 &dex_cache,
4709 &class_loader,
4710 this,
4711 *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004712 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004713 ClassDataItemIterator field_it(dex_file, class_data);
4714 if (value_it.HasNext()) {
4715 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004716 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004717 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004718 ArtField* field = ResolveField(
4719 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004720 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004721 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004722 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004723 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004724 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07004725 if (self->IsExceptionPending()) {
4726 break;
4727 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004728 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004729 }
4730 }
4731 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004732
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004733
Mathieu Chartierda595be2016-08-10 13:57:39 -07004734 if (!self->IsExceptionPending()) {
4735 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4736 if (clinit != nullptr) {
4737 CHECK(can_init_statics);
4738 JValue result;
4739 clinit->Invoke(self, nullptr, 0, &result, "V");
4740 }
4741 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004742 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004743 uint64_t t1 = NanoTime();
4744
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004745 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004746 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004747 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004748
4749 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004750 WrapExceptionInInitializer(klass);
Vladimir Marko72ab6842017-01-20 19:32:50 +00004751 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004752 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004753 } else if (Runtime::Current()->IsTransactionAborted()) {
4754 // The exception thrown when the transaction aborted has been caught and cleared
4755 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07004756 VLOG(compiler) << "Return from class initializer of "
4757 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01004758 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02004759 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko72ab6842017-01-20 19:32:50 +00004760 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004761 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004762 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004763 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4764 RuntimeStats* thread_stats = self->GetStats();
4765 ++global_stats->class_init_count;
4766 ++thread_stats->class_init_count;
4767 global_stats->class_init_time_ns += (t1 - t0);
4768 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004769 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004770 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004771 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004772 std::string temp;
4773 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004774 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004775 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004776 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004777 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004778 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004779 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004780 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004781}
4782
Alex Lighteb7c1442015-08-31 13:17:42 -07004783// We recursively run down the tree of interfaces. We need to do this in the order they are declared
4784// and perform the initialization only on those interfaces that contain default methods.
4785bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
4786 Handle<mirror::Class> iface,
4787 bool can_init_statics,
4788 bool can_init_parents) {
4789 CHECK(iface->IsInterface());
4790 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004791 // Only create the (expensive) handle scope if we need it.
4792 if (UNLIKELY(num_direct_ifaces > 0)) {
4793 StackHandleScope<1> hs(self);
4794 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
4795 // First we initialize all of iface's super-interfaces recursively.
4796 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004797 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
4798 DCHECK(super_iface != nullptr);
Alex Light56a40f52015-10-14 11:07:41 -07004799 if (!super_iface->HasBeenRecursivelyInitialized()) {
4800 // Recursive step
4801 handle_super_iface.Assign(super_iface);
4802 if (!InitializeDefaultInterfaceRecursive(self,
4803 handle_super_iface,
4804 can_init_statics,
4805 can_init_parents)) {
4806 return false;
4807 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004808 }
4809 }
4810 }
4811
4812 bool result = true;
4813 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
4814 // initialize if we don't have default methods.
4815 if (iface->HasDefaultMethods()) {
4816 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
4817 }
4818
4819 // Mark that this interface has undergone recursive default interface initialization so we know we
4820 // can skip it on any later class initializations. We do this even if we are not a default
4821 // interface since we can still avoid the traversal. This is purely a performance optimization.
4822 if (result) {
4823 // TODO This should be done in a better way
4824 ObjectLock<mirror::Class> lock(self, iface);
4825 iface->SetRecursivelyInitialized();
4826 }
4827 return result;
4828}
4829
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004830bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
4831 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004832 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004833 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004834 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004835 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004836 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004837 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004838
4839 // When we wake up, repeat the test for init-in-progress. If
4840 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004841 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004842 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004843 WrapExceptionInInitializer(klass);
Vladimir Marko72ab6842017-01-20 19:32:50 +00004844 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004845 return false;
4846 }
4847 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004848 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004849 continue;
4850 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004851 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
4852 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004853 // Compile time initialization failed.
4854 return false;
4855 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004856 if (klass->IsErroneous()) {
4857 // The caller wants an exception, but it was thrown in a
4858 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004859 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07004860 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004861 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004862 return false;
4863 }
4864 if (klass->IsInitialized()) {
4865 return true;
4866 }
David Sehr709b0702016-10-13 09:12:37 -07004867 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004868 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004869 }
Ian Rogers07140832014-09-30 15:43:59 -07004870 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004871}
4872
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004873static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
4874 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004875 ArtMethod* method,
4876 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004877 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004878 DCHECK(Thread::Current()->IsExceptionPending());
4879 DCHECK(!m->IsProxyMethod());
4880 const DexFile* dex_file = m->GetDexFile();
4881 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
4882 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08004883 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07004884 std::string return_type = dex_file->PrettyType(return_type_idx);
4885 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004886 ThrowWrappedLinkageError(klass.Get(),
4887 "While checking class %s method %s signature against %s %s: "
4888 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07004889 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
4890 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004891 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07004892 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004893 return_type.c_str(), class_loader.c_str());
4894}
4895
4896static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
4897 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004898 ArtMethod* method,
4899 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004900 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08004901 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004902 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004903 DCHECK(Thread::Current()->IsExceptionPending());
4904 DCHECK(!m->IsProxyMethod());
4905 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07004906 std::string arg_type = dex_file->PrettyType(arg_type_idx);
4907 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004908 ThrowWrappedLinkageError(klass.Get(),
4909 "While checking class %s method %s signature against %s %s: "
4910 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07004911 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
4912 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004913 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07004914 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004915 index, arg_type.c_str(), class_loader.c_str());
4916}
4917
4918static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
4919 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004920 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004921 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004922 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004923 ThrowLinkageError(klass.Get(),
4924 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07004925 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
4926 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004927 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07004928 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004929 error_msg.c_str());
4930}
4931
Ian Rogersb5fb2072014-12-02 17:22:02 -08004932static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004933 Handle<mirror::Class> klass,
4934 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004935 ArtMethod* method1,
4936 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004937 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004938 {
4939 StackHandleScope<1> hs(self);
Vladimir Marko942fd312017-01-16 20:52:19 +00004940 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType(true /* resolve */)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004941 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004942 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004943 return false;
4944 }
Vladimir Marko942fd312017-01-16 20:52:19 +00004945 ObjPtr<mirror::Class> other_return_type = method2->GetReturnType(true /* resolve */);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004946 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004947 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004948 return false;
4949 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00004950 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004951 ThrowSignatureMismatch(klass, super_klass, method1,
4952 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07004953 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004954 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07004955 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004956 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08004957 return false;
4958 }
4959 }
4960 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4961 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4962 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004963 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004964 ThrowSignatureMismatch(klass, super_klass, method1,
4965 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07004966 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004967 return false;
4968 }
4969 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08004970 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004971 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004972 ThrowSignatureMismatch(klass, super_klass, method1,
4973 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07004974 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004975 return false;
4976 }
4977 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08004978 }
4979 uint32_t num_types = types1->Size();
4980 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004981 ThrowSignatureMismatch(klass, super_klass, method1,
4982 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07004983 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08004984 return false;
4985 }
4986 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00004987 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08004988 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00004989 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Marko942fd312017-01-16 20:52:19 +00004990 method1->GetClassFromTypeIndex(param_type_idx, true /* resolve */)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004991 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004992 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004993 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004994 return false;
4995 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08004996 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004997 ObjPtr<mirror::Class> other_param_type =
Vladimir Marko942fd312017-01-16 20:52:19 +00004998 method2->GetClassFromTypeIndex(other_param_type_idx, true /* resolve */);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004999 if (UNLIKELY(other_param_type == nullptr)) {
5000 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005001 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005002 return false;
5003 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005004 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005005 ThrowSignatureMismatch(klass, super_klass, method1,
5006 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5007 i,
David Sehr709b0702016-10-13 09:12:37 -07005008 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005009 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005010 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005011 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005012 return false;
5013 }
5014 }
5015 return true;
5016}
5017
5018
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005019bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005020 if (klass->IsInterface()) {
5021 return true;
5022 }
Ian Rogers151f2212014-05-06 11:27:27 -07005023 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005024 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005025 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005026 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005027 if (klass->HasSuperClass() &&
5028 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005029 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005030 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005031 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5032 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5033 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005034 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5035 klass,
5036 super_klass,
5037 m,
5038 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005039 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005040 return false;
5041 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005042 }
5043 }
5044 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005045 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005046 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5047 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5048 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005049 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005050 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5051 j, image_pointer_size_);
5052 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5053 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005054 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5055 klass,
5056 super_klass,
5057 m,
5058 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005059 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005060 return false;
5061 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005062 }
5063 }
5064 }
5065 }
5066 return true;
5067}
5068
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005069bool ClassLinker::EnsureInitialized(Thread* self,
5070 Handle<mirror::Class> c,
5071 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005072 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005073 DCHECK(c != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005074 if (c->IsInitialized()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08005075 EnsureSkipAccessChecksMethods(c, image_pointer_size_);
Mathieu Chartier8502f722016-06-08 15:09:08 -07005076 self->AssertNoPendingException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005077 return true;
5078 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005079 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005080 if (!success) {
5081 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005082 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005083 }
5084 } else {
5085 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005086 }
5087 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005088}
5089
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005090void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5091 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005092 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005093 for (ArtField& field : new_class->GetIFields()) {
5094 if (field.GetDeclaringClass() == temp_class) {
5095 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005096 }
5097 }
5098
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005099 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005100 for (ArtField& field : new_class->GetSFields()) {
5101 if (field.GetDeclaringClass() == temp_class) {
5102 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005103 }
5104 }
5105
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005106 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005107 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005108 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005109 if (method.GetDeclaringClass() == temp_class) {
5110 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005111 }
5112 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005113
5114 // Make sure the remembered set and mod-union tables know that we updated some of the native
5115 // roots.
5116 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005117}
5118
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005119void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005120 CHECK(class_loader->GetAllocator() == nullptr);
5121 CHECK(class_loader->GetClassTable() == nullptr);
5122 Thread* const self = Thread::Current();
5123 ClassLoaderData data;
5124 data.weak_root = self->GetJniEnv()->vm->AddWeakGlobalRef(self, class_loader);
5125 // Create and set the class table.
5126 data.class_table = new ClassTable;
5127 class_loader->SetClassTable(data.class_table);
5128 // Create and set the linear allocator.
5129 data.allocator = Runtime::Current()->CreateLinearAlloc();
5130 class_loader->SetAllocator(data.allocator);
5131 // Add to the list so that we know to free the data later.
5132 class_loaders_.push_back(data);
5133}
5134
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005135ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005136 if (class_loader == nullptr) {
5137 return &boot_class_table_;
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005138 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005139 ClassTable* class_table = class_loader->GetClassTable();
5140 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005141 RegisterClassLoader(class_loader);
5142 class_table = class_loader->GetClassTable();
5143 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005144 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005145 return class_table;
5146}
5147
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005148ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005149 return class_loader == nullptr ? &boot_class_table_ : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005150}
5151
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005152static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005153 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005154 while (klass->HasSuperClass()) {
5155 klass = klass->GetSuperClass();
5156 if (klass->ShouldHaveImt()) {
5157 return klass->GetImt(pointer_size);
5158 }
5159 }
5160 return nullptr;
5161}
5162
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005163bool ClassLinker::LinkClass(Thread* self,
5164 const char* descriptor,
5165 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005166 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005167 MutableHandle<mirror::Class>* h_new_class_out) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005168 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005169
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005170 if (!LinkSuperClass(klass)) {
5171 return false;
5172 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005173 ArtMethod* imt_data[ImTable::kSize];
5174 // If there are any new conflicts compared to super class.
5175 bool new_conflict = false;
5176 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
5177 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005178 return false;
5179 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005180 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005181 return false;
5182 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005183 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005184 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005185 return false;
5186 }
5187 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005188 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005189
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005190 ImTable* imt = nullptr;
5191 if (klass->ShouldHaveImt()) {
5192 // If there are any new conflicts compared to the super class we can not make a copy. There
5193 // can be cases where both will have a conflict method at the same slot without having the same
5194 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5195 // will possibly create a table that is incorrect for either of the classes.
5196 // Same IMT with new_conflict does not happen very often.
5197 if (!new_conflict) {
5198 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5199 if (super_imt != nullptr) {
5200 bool imt_equals = true;
5201 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5202 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5203 }
5204 if (imt_equals) {
5205 imt = super_imt;
5206 }
5207 }
5208 }
5209 if (imt == nullptr) {
5210 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5211 imt = reinterpret_cast<ImTable*>(
5212 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5213 if (imt == nullptr) {
5214 return false;
5215 }
5216 imt->Populate(imt_data, image_pointer_size_);
5217 }
5218 }
5219
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005220 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5221 // We don't need to retire this class as it has no embedded tables or it was created the
5222 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005223 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005224
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005225 if (klass->ShouldHaveEmbeddedVTable()) {
5226 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005227 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005228 if (klass->ShouldHaveImt()) {
5229 klass->SetImt(imt, image_pointer_size_);
5230 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005231
5232 // Update CHA info based on whether we override methods.
5233 // Have to do this before setting the class as resolved which allows
5234 // instantiation of klass.
5235 Runtime::Current()->GetClassHierarchyAnalysis()->UpdateAfterLoadingOf(klass);
5236
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005237 // This will notify waiters on klass that saw the not yet resolved
5238 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07005239 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005240 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005241 } else {
5242 CHECK(!klass->IsResolved());
5243 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005244 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005245 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005246 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5247 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5248 // may not see any references to the target space and clean the card for a class if another
5249 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005250 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005251 klass->SetSFieldsPtrUnchecked(nullptr);
5252 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005253 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005254 self->AssertPendingOOMException();
Vladimir Marko72ab6842017-01-20 19:32:50 +00005255 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005256 return false;
5257 }
5258
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005259 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5260 ObjectLock<mirror::Class> lock(self, h_new_class);
5261 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005262
5263 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005264 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005265 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005266 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005267 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005268 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005269 if (class_loader != nullptr) {
5270 // We updated the class in the class table, perform the write barrier so that the GC knows
5271 // about the change.
5272 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
5273 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005274 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005275 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005276 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5277 }
5278 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005279
Mingyao Yang063fc772016-08-02 11:02:54 -07005280 // Update CHA info based on whether we override methods.
5281 // Have to do this before setting the class as resolved which allows
5282 // instantiation of klass.
5283 Runtime::Current()->GetClassHierarchyAnalysis()->UpdateAfterLoadingOf(h_new_class);
5284
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005285 // This will notify waiters on temp class that saw the not yet resolved class in the
5286 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07005287 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005288
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005289 CHECK_EQ(h_new_class->GetStatus(), mirror::Class::kStatusResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005290 // This will notify waiters on new_class that saw the not yet resolved
5291 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005292 mirror::Class::SetStatus(h_new_class, mirror::Class::kStatusResolved, self);
5293 // Return the new class.
5294 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005295 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005296 return true;
5297}
5298
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005299static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
5300 size_t* virtual_methods,
5301 size_t* direct_methods,
5302 size_t* static_fields,
5303 size_t* instance_fields) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005304 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
5305
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005306 while (dex_data.HasNextStaticField()) {
5307 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08005308 (*static_fields)++;
5309 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005310 while (dex_data.HasNextInstanceField()) {
5311 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08005312 (*instance_fields)++;
5313 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005314 while (dex_data.HasNextDirectMethod()) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005315 (*direct_methods)++;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005316 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08005317 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005318 while (dex_data.HasNextVirtualMethod()) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005319 (*virtual_methods)++;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005320 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08005321 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005322 DCHECK(!dex_data.HasNext());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005323}
5324
5325static void DumpClass(std::ostream& os,
5326 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
5327 const char* suffix) {
5328 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
5329 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
5330 os << " Static fields:\n";
5331 while (dex_data.HasNextStaticField()) {
5332 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
5333 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
5334 dex_data.Next();
5335 }
5336 os << " Instance fields:\n";
5337 while (dex_data.HasNextInstanceField()) {
5338 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
5339 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
5340 dex_data.Next();
5341 }
5342 os << " Direct methods:\n";
5343 while (dex_data.HasNextDirectMethod()) {
5344 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
5345 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
5346 dex_data.Next();
5347 }
5348 os << " Virtual methods:\n";
5349 while (dex_data.HasNextVirtualMethod()) {
5350 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
5351 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
5352 dex_data.Next();
5353 }
5354}
5355
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005356static std::string DumpClasses(const DexFile& dex_file1,
5357 const DexFile::ClassDef& dex_class_def1,
5358 const DexFile& dex_file2,
5359 const DexFile::ClassDef& dex_class_def2) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005360 std::ostringstream os;
5361 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
5362 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
5363 return os.str();
5364}
5365
5366
5367// Very simple structural check on whether the classes match. Only compares the number of
5368// methods and fields.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005369static bool SimpleStructuralCheck(const DexFile& dex_file1,
5370 const DexFile::ClassDef& dex_class_def1,
5371 const DexFile& dex_file2,
5372 const DexFile::ClassDef& dex_class_def2,
Andreas Gampefd9eb392014-11-06 16:52:58 -08005373 std::string* error_msg) {
5374 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
5375 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
5376
5377 // Counters for current dex file.
5378 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005379 CountMethodsAndFields(dex_data1,
5380 &dex_virtual_methods1,
5381 &dex_direct_methods1,
5382 &dex_static_fields1,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005383 &dex_instance_fields1);
Andreas Gampefd9eb392014-11-06 16:52:58 -08005384 // Counters for compile-time dex file.
5385 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005386 CountMethodsAndFields(dex_data2,
5387 &dex_virtual_methods2,
5388 &dex_direct_methods2,
5389 &dex_static_fields2,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005390 &dex_instance_fields2);
Andreas Gampefd9eb392014-11-06 16:52:58 -08005391
5392 if (dex_virtual_methods1 != dex_virtual_methods2) {
5393 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005394 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s",
5395 dex_virtual_methods1,
5396 dex_virtual_methods2,
5397 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005398 return false;
5399 }
5400 if (dex_direct_methods1 != dex_direct_methods2) {
5401 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005402 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s",
5403 dex_direct_methods1,
5404 dex_direct_methods2,
5405 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005406 return false;
5407 }
5408 if (dex_static_fields1 != dex_static_fields2) {
5409 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005410 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s",
5411 dex_static_fields1,
5412 dex_static_fields2,
5413 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005414 return false;
5415 }
5416 if (dex_instance_fields1 != dex_instance_fields2) {
5417 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005418 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s",
5419 dex_instance_fields1,
5420 dex_instance_fields2,
5421 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005422 return false;
5423 }
5424
5425 return true;
5426}
5427
5428// Checks whether a the super-class changed from what we had at compile-time. This would
5429// invalidate quickening.
5430static bool CheckSuperClassChange(Handle<mirror::Class> klass,
5431 const DexFile& dex_file,
5432 const DexFile::ClassDef& class_def,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005433 ObjPtr<mirror::Class> super_class)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005434 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005435 // Check for unexpected changes in the superclass.
5436 // Quick check 1) is the super_class class-loader the boot class loader? This always has
5437 // precedence.
5438 if (super_class->GetClassLoader() != nullptr &&
5439 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
5440 // which is implied by different dex cache.
5441 klass->GetDexCache() != super_class->GetDexCache()) {
5442 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
5443 // definition for the super-class, and (b) the files are in separate oat files. The oat files
5444 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
Richard Uhler07b3c232015-03-31 15:57:54 -07005445 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
5446 const OatFile* class_oat_file = nullptr;
5447 if (class_oat_dex_file != nullptr) {
5448 class_oat_file = class_oat_dex_file->GetOatFile();
5449 }
5450
Andreas Gampefd9eb392014-11-06 16:52:58 -08005451 if (class_oat_file != nullptr) {
Richard Uhler07b3c232015-03-31 15:57:54 -07005452 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
5453 const OatFile* loaded_super_oat_file = nullptr;
5454 if (loaded_super_oat_dex_file != nullptr) {
5455 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
5456 }
5457
Andreas Gampefd9eb392014-11-06 16:52:58 -08005458 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
5459 // Now check (a).
5460 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
5461 if (super_class_def != nullptr) {
5462 // Uh-oh, we found something. Do our check.
5463 std::string error_msg;
5464 if (!SimpleStructuralCheck(dex_file, *super_class_def,
5465 super_class->GetDexFile(), *super_class->GetClassDef(),
5466 &error_msg)) {
5467 // Print a warning to the log. This exception might be caught, e.g., as common in test
5468 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
5469 // only save the type of the exception.
5470 LOG(WARNING) << "Incompatible structural change detected: " <<
5471 StringPrintf(
5472 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
David Sehr709b0702016-10-13 09:12:37 -07005473 dex_file.PrettyType(super_class_def->class_idx_).c_str(),
Andreas Gampefd9eb392014-11-06 16:52:58 -08005474 class_oat_file->GetLocation().c_str(),
5475 loaded_super_oat_file->GetLocation().c_str(),
5476 error_msg.c_str());
5477 ThrowIncompatibleClassChangeError(klass.Get(),
5478 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
David Sehr709b0702016-10-13 09:12:37 -07005479 dex_file.PrettyType(super_class_def->class_idx_).c_str(),
Andreas Gampefd9eb392014-11-06 16:52:58 -08005480 class_oat_file->GetLocation().c_str(),
5481 loaded_super_oat_file->GetLocation().c_str(),
5482 error_msg.c_str());
5483 return false;
5484 }
5485 }
5486 }
5487 }
5488 }
5489 return true;
5490}
5491
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005492bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005493 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005494 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005495 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5496 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005497 // Check that a class does not inherit from itself directly.
5498 //
5499 // TODO: This is a cheap check to detect the straightforward case
5500 // of a class extending itself (b/28685551), but we should do a
5501 // proper cycle detection on loaded classes, to detect all cases
5502 // of class circularity errors (b/28830038).
5503 if (super_class_idx == class_def.class_idx_) {
5504 ThrowClassCircularityError(klass.Get(),
5505 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005506 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005507 return false;
5508 }
5509
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005510 ObjPtr<mirror::Class> super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005511 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005512 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005513 return false;
5514 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005515 // Verify
5516 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005517 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005518 super_class->PrettyDescriptor().c_str(),
5519 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005520 return false;
5521 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005522 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005523 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08005524
5525 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
5526 DCHECK(Thread::Current()->IsExceptionPending());
5527 return false;
5528 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005529 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005530 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005531 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005532 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005533 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005534 ObjPtr<mirror::Class> interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005535 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005536 DCHECK(Thread::Current()->IsExceptionPending());
5537 return false;
5538 }
5539 // Verify
5540 if (!klass->CanAccess(interface)) {
5541 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005542 ThrowIllegalAccessError(klass.Get(),
5543 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005544 interface->PrettyDescriptor().c_str(),
5545 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005546 return false;
5547 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005548 }
5549 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005550 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07005551 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005552 return true;
5553}
5554
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005555bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005556 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005557 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005558 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005559 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005560 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005561 return false;
5562 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005563 return true;
5564 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005565 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005566 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005567 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005568 return false;
5569 }
5570 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07005571 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005572 ThrowIncompatibleClassChangeError(klass.Get(),
5573 "Superclass %s of %s is %s",
David Sehr709b0702016-10-13 09:12:37 -07005574 super->PrettyDescriptor().c_str(),
5575 klass->PrettyDescriptor().c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005576 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005577 return false;
5578 }
5579 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005580 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005581 super->PrettyDescriptor().c_str(),
5582 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005583 return false;
5584 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005585
Brian Carlstromf3632832014-05-20 15:36:53 -07005586 // Inherit kAccClassIsFinalizable from the superclass in case this
5587 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005588 if (super->IsFinalizable()) {
5589 klass->SetFinalizable();
5590 }
5591
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005592 // Inherit class loader flag form super class.
5593 if (super->IsClassLoaderClass()) {
5594 klass->SetClassLoaderClass();
5595 }
5596
Elliott Hughes2da50362011-10-10 16:57:08 -07005597 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005598 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005599 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005600 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005601 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005602 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005603 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07005604 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005605 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005606 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005607 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005608 return false;
5609 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005610
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005611 if (kIsDebugBuild) {
5612 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005613 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005614 CHECK(super->IsResolved());
5615 super = super->GetSuperClass();
5616 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005617 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005618 return true;
5619}
5620
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005621// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005622bool ClassLinker::LinkMethods(Thread* self,
5623 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005624 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005625 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005626 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005627 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005628 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5629 // need to have default methods be in the virtuals array of each class but we don't set that up
5630 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07005631 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07005632 // Link virtual methods then interface methods.
5633 // We set up the interface lookup table first because we need it to determine if we need to update
5634 // any vtable entries with new default method implementations.
5635 return SetupInterfaceLookupTable(self, klass, interfaces)
5636 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005637 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005638}
5639
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005640// Comparator for name and signature of a method, used in finding overriding methods. Implementation
5641// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
5642// caches in the implementation below.
5643class MethodNameAndSignatureComparator FINAL : public ValueObject {
5644 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005645 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005646 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005647 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
5648 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07005649 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005650 }
5651
5652 const char* GetName() {
5653 if (name_ == nullptr) {
5654 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
5655 }
5656 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005657 }
5658
Mathieu Chartiere401d142015-04-22 13:56:20 -07005659 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005660 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07005661 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005662 const DexFile* other_dex_file = other->GetDexFile();
5663 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
5664 if (dex_file_ == other_dex_file) {
5665 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
5666 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005667 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005668 uint32_t other_name_len;
5669 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
5670 &other_name_len);
5671 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
5672 return false;
5673 }
5674 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
5675 }
5676
5677 private:
5678 // Dex file for the method to compare against.
5679 const DexFile* const dex_file_;
5680 // MethodId for the method to compare against.
5681 const DexFile::MethodId* const mid_;
5682 // Lazily computed name from the dex file's strings.
5683 const char* name_;
5684 // Lazily computed name length.
5685 uint32_t name_len_;
5686};
5687
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005688class LinkVirtualHashTable {
5689 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005690 LinkVirtualHashTable(Handle<mirror::Class> klass,
5691 size_t hash_size,
5692 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07005693 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005694 : klass_(klass),
5695 hash_size_(hash_size),
5696 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07005697 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005698 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
5699 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005700
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005701 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005702 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
5703 virtual_method_index, image_pointer_size_);
5704 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005705 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005706 uint32_t index = hash % hash_size_;
5707 // Linear probe until we have an empty slot.
5708 while (hash_table_[index] != invalid_index_) {
5709 if (++index == hash_size_) {
5710 index = 0;
5711 }
5712 }
5713 hash_table_[index] = virtual_method_index;
5714 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005715
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005716 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005717 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005718 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005719 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005720 size_t index = hash % hash_size_;
5721 while (true) {
5722 const uint32_t value = hash_table_[index];
5723 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
5724 // the block and can safely assume not found.
5725 if (value == invalid_index_) {
5726 break;
5727 }
5728 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005729 ArtMethod* virtual_method =
5730 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
5731 if (comparator->HasSameNameAndSignature(
5732 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005733 hash_table_[index] = removed_index_;
5734 return value;
5735 }
5736 }
5737 if (++index == hash_size_) {
5738 index = 0;
5739 }
5740 }
5741 return GetNotFoundIndex();
5742 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005743
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005744 static uint32_t GetNotFoundIndex() {
5745 return invalid_index_;
5746 }
5747
5748 private:
5749 static const uint32_t invalid_index_;
5750 static const uint32_t removed_index_;
5751
5752 Handle<mirror::Class> klass_;
5753 const size_t hash_size_;
5754 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07005755 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005756};
5757
5758const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
5759const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
5760
Stephen Hines1ddd9132017-02-08 01:51:18 -08005761bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07005762 Thread* self,
5763 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07005764 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005765 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07005766 if (klass->IsInterface()) {
5767 // No vtable.
5768 if (!IsUint<16>(num_virtual_methods)) {
5769 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
5770 return false;
5771 }
5772 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07005773 // Assign each method an IMT index and set the default flag.
5774 for (size_t i = 0; i < num_virtual_methods; ++i) {
5775 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5776 m->SetMethodIndex(i);
5777 if (!m->IsAbstract()) {
5778 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
5779 has_defaults = true;
5780 }
5781 }
5782 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
5783 // during initialization. This is a performance optimization. We could simply traverse the
5784 // virtual_methods_ array again during initialization.
5785 if (has_defaults) {
5786 klass->SetHasDefaultMethods();
5787 }
5788 return true;
5789 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005790 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
5791 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005792 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07005793 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07005794 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005795 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005796 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005797 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005798 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005799 return false;
5800 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005801 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005802 vtable->SetElementPtrSize(
5803 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005804 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005805 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5806 // might give us new default methods). If no new interfaces then we can skip the rest since
5807 // the class cannot override any of the super-class's methods. This is required for
5808 // correctness since without it we might not update overridden default method vtable entries
5809 // correctly.
5810 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005811 klass->SetVTable(vtable.Get());
5812 return true;
5813 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005814 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07005815 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005816 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07005817 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07005818 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5819 // might give us new default methods). See comment above.
5820 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005821 klass->SetVTable(super_vtable);
5822 return true;
5823 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005824 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
5825 super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005826 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005827 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005828 return false;
5829 }
Ian Rogersa436fde2013-08-27 23:34:06 -07005830 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005831 // How the algorithm works:
5832 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
5833 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
5834 // method which has not been matched to a vtable method, and j if the virtual method at the
5835 // index overrode the super virtual method at index j.
5836 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
5837 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
5838 // the need for the initial vtable which we later shrink back down).
5839 // 3. Add non overridden methods to the end of the vtable.
5840 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07005841 // + 1 so that even if we only have new default methods we will still be able to use this hash
5842 // table (i.e. it will never have 0 size).
5843 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005844 uint32_t* hash_table_ptr;
5845 std::unique_ptr<uint32_t[]> hash_heap_storage;
5846 if (hash_table_size <= kMaxStackHash) {
5847 hash_table_ptr = reinterpret_cast<uint32_t*>(
5848 alloca(hash_table_size * sizeof(*hash_table_ptr)));
5849 } else {
5850 hash_heap_storage.reset(new uint32_t[hash_table_size]);
5851 hash_table_ptr = hash_heap_storage.get();
5852 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005853 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005854 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005855 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005856 DCHECK(klass->GetVirtualMethodDuringLinking(
5857 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005858 hash_table.Add(i);
5859 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005860 // Loop through each super vtable method and see if they are overridden by a method we added to
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005861 // the hash table.
5862 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005863 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005864 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005865 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
5866 super_method->GetAccessFlags())) {
5867 // Continue on to the next method since this one is package private and canot be overridden.
5868 // Before Android 4.1, the package-private method super_method might have been incorrectly
5869 // overridden.
5870 continue;
5871 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005872 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005873 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07005874 // We remove the method so that subsequent lookups will be faster by making the hash-map
5875 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005876 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5877 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005878 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
5879 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005880 if (super_method->IsFinal()) {
5881 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5882 virtual_method->PrettyMethod().c_str(),
5883 super_method->GetDeclaringClassDescriptor());
5884 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005885 }
Alex Lightc7a420c2016-10-18 14:33:18 -07005886 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
5887 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07005888 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005889 // We didn't directly override this method but we might through default methods...
5890 // Check for default method update.
5891 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07005892 switch (FindDefaultMethodImplementation(self,
5893 super_method,
5894 klass,
5895 /*out*/&default_method)) {
5896 case DefaultMethodSearchResult::kDefaultConflict: {
5897 // A conflict was found looking for default methods. Note this (assuming it wasn't
5898 // pre-existing) in the translations map.
5899 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
5900 // Don't generate another conflict method to reduce memory use as an optimization.
5901 default_translations->insert(
5902 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
5903 }
5904 break;
5905 }
5906 case DefaultMethodSearchResult::kAbstractFound: {
5907 // No conflict but method is abstract.
5908 // We note that this vtable entry must be made abstract.
5909 if (UNLIKELY(!super_method->IsAbstract())) {
5910 default_translations->insert(
5911 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
5912 }
5913 break;
5914 }
5915 case DefaultMethodSearchResult::kDefaultFound: {
5916 if (UNLIKELY(super_method->IsDefaultConflicting() ||
5917 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
5918 // Found a default method implementation that is new.
5919 // TODO Refactor this add default methods to virtuals here and not in
5920 // LinkInterfaceMethods maybe.
5921 // The problem is default methods might override previously present
5922 // default-method or miranda-method vtable entries from the superclass.
5923 // Unfortunately we need these to be entries in this class's virtuals. We do not
5924 // give these entries there until LinkInterfaceMethods so we pass this map around
5925 // to let it know which vtable entries need to be updated.
5926 // Make a note that vtable entry j must be updated, store what it needs to be updated
5927 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
5928 // then.
5929 default_translations->insert(
5930 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07005931 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
5932 << " overridden by default "
5933 << default_method->PrettyMethod()
5934 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07005935 }
5936 break;
5937 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005938 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005939 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005940 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005941 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07005942 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005943 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005944 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005945 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5946 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07005947 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005948 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005949 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005950 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005951 local_method->SetMethodIndex(actual_count);
5952 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005953 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005954 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005955 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005956 return false;
5957 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005958 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005959 CHECK_LE(actual_count, max_count);
5960 if (actual_count < max_count) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005961 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005962 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005963 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005964 return false;
5965 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005966 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005967 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005968 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005969 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005970 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005971 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5972 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005973 return false;
5974 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005975 auto* vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005976 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005977 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005978 return false;
5979 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005980 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005981 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5982 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005983 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005984 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005985 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005986 }
5987 return true;
5988}
5989
Alex Light9139e002015-10-09 15:59:48 -07005990// Determine if the given iface has any subinterface in the given list that declares the method
5991// specified by 'target'.
5992//
5993// Arguments
5994// - self: The thread we are running on
5995// - target: A comparator that will match any method that overrides the method we are checking for
5996// - iftable: The iftable we are searching for an overriding method on.
5997// - ifstart: The index of the interface we are checking to see if anything overrides
5998// - iface: The interface we are checking to see if anything overrides.
5999// - image_pointer_size:
6000// The image pointer size.
6001//
6002// Returns
6003// - True: There is some method that matches the target comparator defined in an interface that
6004// is a subtype of iface.
6005// - False: There is no method that matches the target comparator in any interface that is a subtype
6006// of iface.
6007static bool ContainsOverridingMethodOf(Thread* self,
6008 MethodNameAndSignatureComparator& target,
6009 Handle<mirror::IfTable> iftable,
6010 size_t ifstart,
6011 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006012 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006013 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006014 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006015 DCHECK(iface != nullptr);
6016 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006017 DCHECK_GE(ifstart, 0u);
6018 DCHECK_LT(ifstart, iftable->Count());
6019 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6020 DCHECK(iface->IsInterface());
6021
6022 size_t iftable_count = iftable->Count();
6023 StackHandleScope<1> hs(self);
6024 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6025 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6026 // Skip ifstart since our current interface obviously cannot override itself.
6027 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006028 // Iterate through every method on this interface. The order does not matter.
6029 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006030 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006031 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006032 // Check if the i'th interface is a subtype of this one.
6033 if (iface->IsAssignableFrom(current_iface.Get())) {
6034 return true;
6035 }
6036 break;
6037 }
6038 }
6039 }
6040 return false;
6041}
6042
Alex Lighteb7c1442015-08-31 13:17:42 -07006043// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006044// out_default_method and returns kDefaultFound on success. If no default method was found return
6045// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6046// default_method conflict) it will return kDefaultConflict.
6047ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6048 Thread* self,
6049 ArtMethod* target_method,
6050 Handle<mirror::Class> klass,
6051 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006052 DCHECK(self != nullptr);
6053 DCHECK(target_method != nullptr);
6054 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006055
6056 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006057
6058 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6059 // table. This lets us walk the table backwards when searching for default methods. The first one
6060 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6061 // track of it and then continue checking all other interfaces, since we need to throw an error if
6062 // we encounter conflicting default method implementations (one is not a subtype of the other).
6063 //
6064 // The order of unrelated interfaces does not matter and is not defined.
6065 size_t iftable_count = klass->GetIfTableCount();
6066 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006067 // No interfaces. We have already reset out to null so just return kAbstractFound.
6068 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006069 }
6070
Alex Light9139e002015-10-09 15:59:48 -07006071 StackHandleScope<3> hs(self);
6072 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006073 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006074 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006075 MethodNameAndSignatureComparator target_name_comparator(
6076 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6077 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006078 for (size_t k = iftable_count; k != 0; ) {
6079 --k;
6080
Alex Lighteb7c1442015-08-31 13:17:42 -07006081 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006082
6083 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006084 // Iterate through every declared method on this interface. The order does not matter.
6085 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6086 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006087 // Skip abstract methods and methods with different names.
6088 if (current_method->IsAbstract() ||
6089 !target_name_comparator.HasSameNameAndSignature(
6090 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6091 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006092 } else if (!current_method->IsPublic()) {
6093 // The verifier should have caught the non-public method for dex version 37. Just warn and
6094 // skip it since this is from before default-methods so we don't really need to care that it
6095 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006096 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6097 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006098 << "This will be a fatal error in subsequent versions of android. "
6099 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006100 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006101 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006102 // We have multiple default impls of the same method. This is a potential default conflict.
6103 // We need to check if this possibly conflicting method is either a superclass of the chosen
6104 // default implementation or is overridden by a non-default interface method. In either case
6105 // there is no conflict.
6106 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6107 !ContainsOverridingMethodOf(self,
6108 target_name_comparator,
6109 iftable,
6110 k,
6111 iface,
6112 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006113 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006114 << current_method->PrettyMethod() << " and "
6115 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6116 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006117 *out_default_method = nullptr;
6118 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006119 } else {
6120 break; // Continue checking at the next interface.
6121 }
6122 } else {
Alex Light9139e002015-10-09 15:59:48 -07006123 // chosen_iface == null
6124 if (!ContainsOverridingMethodOf(self,
6125 target_name_comparator,
6126 iftable,
6127 k,
6128 iface,
6129 image_pointer_size_)) {
6130 // Don't set this as the chosen interface if something else is overriding it (because that
6131 // other interface would be potentially chosen instead if it was default). If the other
6132 // interface was abstract then we wouldn't select this interface as chosen anyway since
6133 // the abstract method masks it.
6134 *out_default_method = current_method;
6135 chosen_iface.Assign(iface.Get());
6136 // We should now finish traversing the graph to find if we have default methods that
6137 // conflict.
6138 } else {
David Sehr709b0702016-10-13 09:12:37 -07006139 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6140 << "' was "
6141 << "skipped because it was overridden by an abstract method in a "
6142 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006143 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006144 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006145 break;
6146 }
6147 }
Alex Light9139e002015-10-09 15:59:48 -07006148 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006149 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6150 << "' selected "
6151 << "as the implementation for '" << target_method->PrettyMethod()
6152 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006153 return DefaultMethodSearchResult::kDefaultFound;
6154 } else {
6155 return DefaultMethodSearchResult::kAbstractFound;
6156 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006157}
6158
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006159ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006160 ArtMethod* conflict_method,
6161 ArtMethod* interface_method,
6162 ArtMethod* method,
6163 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006164 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006165 Runtime* const runtime = Runtime::Current();
6166 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6167 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6168
6169 // Create a new entry if the existing one is the shared conflict method.
6170 ArtMethod* new_conflict_method = new_entry
6171 ? runtime->CreateImtConflictMethod(linear_alloc)
6172 : conflict_method;
6173
6174 // Allocate a new table. Note that we will leak this table at the next conflict,
6175 // but that's a tradeoff compared to making the table fixed size.
6176 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006177 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6178 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006179 if (data == nullptr) {
6180 LOG(ERROR) << "Failed to allocate conflict table";
6181 return conflict_method;
6182 }
6183 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6184 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006185 method,
6186 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006187
6188 // Do a fence to ensure threads see the data in the table before it is assigned
6189 // to the conflict method.
6190 // Note that there is a race in the presence of multiple threads and we may leak
6191 // memory from the LinearAlloc, but that's a tradeoff compared to using
6192 // atomic operations.
6193 QuasiAtomic::ThreadFenceRelease();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006194 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006195 return new_conflict_method;
6196}
6197
Vladimir Marko921094a2017-01-12 18:37:06 +00006198bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6199 Handle<mirror::Class> klass,
6200 Handle<mirror::IfTable> iftable) {
6201 DCHECK(!klass->IsInterface());
6202 const bool has_superclass = klass->HasSuperClass();
6203 const bool extend_super_iftable = has_superclass;
6204 const size_t ifcount = klass->GetIfTableCount();
6205 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6206 for (size_t i = 0; i < ifcount; ++i) {
6207 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6208 if (num_methods > 0) {
6209 const bool is_super = i < super_ifcount;
6210 // This is an interface implemented by a super-class. Therefore we can just copy the method
6211 // array from the superclass.
6212 const bool super_interface = is_super && extend_super_iftable;
6213 ObjPtr<mirror::PointerArray> method_array;
6214 if (super_interface) {
6215 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6216 DCHECK(if_table != nullptr);
6217 DCHECK(if_table->GetMethodArray(i) != nullptr);
6218 // If we are working on a super interface, try extending the existing method array.
6219 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
6220 } else {
6221 method_array = AllocPointerArray(self, num_methods);
6222 }
6223 if (UNLIKELY(method_array == nullptr)) {
6224 self->AssertPendingOOMException();
6225 return false;
6226 }
6227 iftable->SetMethodArray(i, method_array);
6228 }
6229 }
6230 return true;
6231}
6232
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006233void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6234 ArtMethod* imt_conflict_method,
6235 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006236 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006237 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006238 // Place method in imt if entry is empty, place conflict otherwise.
6239 if (*imt_ref == unimplemented_method) {
6240 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006241 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006242 // If we are not a conflict and we have the same signature and name as the imt
6243 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006244 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6245 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006246 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006247 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006248 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006249 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006250 *imt_ref = current_method;
6251 } else {
Alex Light9139e002015-10-09 15:59:48 -07006252 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006253 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006254 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006255 } else {
6256 // Place the default conflict method. Note that there may be an existing conflict
6257 // method in the IMT, but it could be one tailored to the super class, with a
6258 // specific ImtConflictTable.
6259 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006260 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006261 }
6262}
6263
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006264void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006265 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6266 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006267 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006268 Runtime* const runtime = Runtime::Current();
6269 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6270 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006271 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006272 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006273 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006274 FillIMTFromIfTable(klass->GetIfTable(),
6275 unimplemented_method,
6276 conflict_method,
6277 klass,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006278 /*create_conflict_tables*/true,
6279 /*ignore_copied_methods*/false,
6280 &new_conflict,
6281 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006282 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006283 if (!klass->ShouldHaveImt()) {
6284 return;
6285 }
6286 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6287 // we can just use the same pointer.
6288 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006289 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006290 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6291 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6292 bool same = true;
6293 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6294 ArtMethod* method = imt_data[i];
6295 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6296 if (method != super_method) {
6297 bool is_conflict_table = method->IsRuntimeMethod() &&
6298 method != unimplemented_method &&
6299 method != conflict_method;
6300 // Verify conflict contents.
6301 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6302 super_method != unimplemented_method &&
6303 super_method != conflict_method;
6304 if (!is_conflict_table || !super_conflict_table) {
6305 same = false;
6306 } else {
6307 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6308 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6309 same = same && table1->Equals(table2, image_pointer_size_);
6310 }
6311 }
6312 }
6313 if (same) {
6314 imt = super_imt;
6315 }
6316 }
6317 if (imt == nullptr) {
6318 imt = klass->GetImt(image_pointer_size_);
6319 DCHECK(imt != nullptr);
6320 imt->Populate(imt_data, image_pointer_size_);
6321 } else {
6322 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006323 }
6324}
6325
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006326ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6327 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006328 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006329 void* data = linear_alloc->Alloc(Thread::Current(),
6330 ImtConflictTable::ComputeSize(count,
6331 image_pointer_size));
6332 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6333}
6334
6335ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6336 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6337}
6338
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006339void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006340 ArtMethod* unimplemented_method,
6341 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006342 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006343 bool create_conflict_tables,
6344 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006345 /*out*/bool* new_conflict,
6346 /*out*/ArtMethod** imt) {
6347 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006348 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006349 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006350 const size_t num_virtuals = interface->NumVirtualMethods();
6351 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6352 // Virtual methods can be larger than the if table methods if there are default methods.
6353 DCHECK_GE(num_virtuals, method_array_count);
6354 if (kIsDebugBuild) {
6355 if (klass->IsInterface()) {
6356 DCHECK_EQ(method_array_count, 0u);
6357 } else {
6358 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6359 }
6360 }
6361 if (method_array_count == 0) {
6362 continue;
6363 }
6364 auto* method_array = if_table->GetMethodArray(i);
6365 for (size_t j = 0; j < method_array_count; ++j) {
6366 ArtMethod* implementation_method =
6367 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6368 if (ignore_copied_methods && implementation_method->IsCopied()) {
6369 continue;
6370 }
6371 DCHECK(implementation_method != nullptr);
6372 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6373 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6374 // or interface methods in the IMT here they will not create extra conflicts since we compare
6375 // names and signatures in SetIMTRef.
6376 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006377 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006378
6379 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6380 // the same implementation method, keep track of this to avoid creating a conflict table in
6381 // this case.
6382
6383 // Conflict table size for each IMT slot.
6384 ++conflict_counts[imt_index];
6385
6386 SetIMTRef(unimplemented_method,
6387 imt_conflict_method,
6388 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006389 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006390 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006391 }
6392 }
6393
6394 if (create_conflict_tables) {
6395 // Create the conflict tables.
6396 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006397 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006398 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006399 if (imt[i] == imt_conflict_method) {
6400 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6401 if (new_table != nullptr) {
6402 ArtMethod* new_conflict_method =
6403 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6404 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6405 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006406 } else {
6407 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006408 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006409 }
6410 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006411 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006412 }
6413 }
6414
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006415 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006416 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006417 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6418 // Virtual methods can be larger than the if table methods if there are default methods.
6419 if (method_array_count == 0) {
6420 continue;
6421 }
6422 auto* method_array = if_table->GetMethodArray(i);
6423 for (size_t j = 0; j < method_array_count; ++j) {
6424 ArtMethod* implementation_method =
6425 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6426 if (ignore_copied_methods && implementation_method->IsCopied()) {
6427 continue;
6428 }
6429 DCHECK(implementation_method != nullptr);
6430 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006431 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006432 if (!imt[imt_index]->IsRuntimeMethod() ||
6433 imt[imt_index] == unimplemented_method ||
6434 imt[imt_index] == imt_conflict_method) {
6435 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006436 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006437 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6438 const size_t num_entries = table->NumEntries(image_pointer_size_);
6439 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6440 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006441 }
6442 }
6443 }
6444}
6445
Alex Lighteb7c1442015-08-31 13:17:42 -07006446// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6447// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006448static bool NotSubinterfaceOfAny(
6449 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6450 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006451 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006452 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006453 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006454 for (ObjPtr<mirror::Class> c : classes) {
6455 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006456 return false;
6457 }
6458 }
6459 return true;
6460}
6461
6462// Fills in and flattens the interface inheritance hierarchy.
6463//
6464// By the end of this function all interfaces in the transitive closure of to_process are added to
6465// the iftable and every interface precedes all of its sub-interfaces in this list.
6466//
6467// all I, J: Interface | I <: J implies J precedes I
6468//
6469// (note A <: B means that A is a subtype of B)
6470//
6471// This returns the total number of items in the iftable. The iftable might be resized down after
6472// this call.
6473//
6474// We order this backwards so that we do not need to reorder superclass interfaces when new
6475// interfaces are added in subclass's interface tables.
6476//
6477// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6478// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6479// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6480// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006481static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006482 size_t super_ifcount,
6483 std::vector<mirror::Class*> to_process)
6484 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006485 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006486 // This is the set of all class's already in the iftable. Used to make checking if a class has
6487 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006488 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006489 // The first super_ifcount elements are from the superclass. We note that they are already added.
6490 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006491 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006492 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6493 classes_in_iftable.insert(iface);
6494 }
6495 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006496 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006497 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6498 // At this point in the loop current-iface-list has the invariant that:
6499 // for every pair of interfaces I,J within it:
6500 // if index_of(I) < index_of(J) then I is not a subtype of J
6501
6502 // If we have already seen this element then all of its super-interfaces must already be in the
6503 // current-iface-list so we can skip adding it.
6504 if (!ContainsElement(classes_in_iftable, interface)) {
6505 // We haven't seen this interface so add all of its super-interfaces onto the
6506 // current-iface-list, skipping those already on it.
6507 int32_t ifcount = interface->GetIfTableCount();
6508 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006509 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006510 if (!ContainsElement(classes_in_iftable, super_interface)) {
6511 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6512 classes_in_iftable.insert(super_interface);
6513 iftable->SetInterface(filled_ifcount, super_interface);
6514 filled_ifcount++;
6515 }
6516 }
6517 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6518 // Place this interface onto the current-iface-list after all of its super-interfaces.
6519 classes_in_iftable.insert(interface);
6520 iftable->SetInterface(filled_ifcount, interface);
6521 filled_ifcount++;
6522 } else if (kIsDebugBuild) {
6523 // Check all super-interfaces are already in the list.
6524 int32_t ifcount = interface->GetIfTableCount();
6525 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006526 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006527 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006528 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6529 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006530 }
6531 }
6532 }
6533 if (kIsDebugBuild) {
6534 // Check that the iftable is ordered correctly.
6535 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006536 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006537 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006538 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006539 // !(if_a <: if_b)
6540 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006541 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6542 << ") extends "
6543 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006544 << "interface list.";
6545 }
6546 }
6547 }
6548 return filled_ifcount;
6549}
6550
6551bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6552 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6553 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006554 const bool has_superclass = klass->HasSuperClass();
6555 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006556 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006557 const size_t num_interfaces =
6558 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006559 if (num_interfaces == 0) {
6560 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006561 if (LIKELY(has_superclass)) {
6562 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6563 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006564 // Class implements no interfaces.
6565 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006566 return true;
6567 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006568 // Class implements same interfaces as parent, are any of these not marker interfaces?
6569 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006570 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006571 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006572 if (super_iftable->GetMethodArrayCount(i) > 0) {
6573 has_non_marker_interface = true;
6574 break;
6575 }
6576 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006577 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006578 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006579 klass->SetIfTable(super_iftable);
6580 return true;
6581 }
6582 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006583 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006584 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006585 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006586 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006587 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006588 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006589 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006590 if (UNLIKELY(!interface->IsInterface())) {
6591 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006592 ThrowIncompatibleClassChangeError(klass.Get(),
6593 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006594 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006595 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6596 return false;
6597 }
6598 ifcount += interface->GetIfTableCount();
6599 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006600 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006601 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006602 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006603 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006604 return false;
6605 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006606 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006607 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006608 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006609 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006610 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006611 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006612 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006613 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006614
6615 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6616 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6617 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006618 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006619
6620 size_t new_ifcount;
6621 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006622 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Alex Lighteb7c1442015-08-31 13:17:42 -07006623 std::vector<mirror::Class*> to_add;
6624 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006625 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006626 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006627 to_add.push_back(interface.Ptr());
Ian Rogersb52b01a2012-01-12 17:01:38 -08006628 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006629
6630 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006631 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006632
Ian Rogers7b078e82014-09-10 14:44:24 -07006633 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006634
Ian Rogersb52b01a2012-01-12 17:01:38 -08006635 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07006636 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006637 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006638 iftable.Assign(down_cast<mirror::IfTable*>(
Alex Lighteb7c1442015-08-31 13:17:42 -07006639 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006640 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006641 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006642 return false;
6643 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006644 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08006645 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006646 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006647 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006648 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07006649 return true;
6650}
6651
Alex Light1f3925d2016-09-07 12:04:20 -07006652// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
6653// of methods must be unique.
6654static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
6655 return nullptr;
6656}
6657
6658template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07006659static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07006660 const ScopedArenaVector<ArtMethod*>& list,
6661 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006662 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006663 for (ArtMethod* method : list) {
6664 if (cmp.HasSameNameAndSignature(method)) {
6665 return method;
6666 }
6667 }
Alex Light1f3925d2016-09-07 12:04:20 -07006668 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07006669}
6670
Alex Light1f3925d2016-09-07 12:04:20 -07006671// Check that all vtable entries are present in this class's virtuals or are the same as a
6672// superclasses vtable entry.
6673static void CheckClassOwnsVTableEntries(Thread* self,
6674 Handle<mirror::Class> klass,
6675 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006676 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07006677 StackHandleScope<2> hs(self);
6678 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006679 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07006680 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006681 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006682 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6683 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6684 CHECK(m != nullptr);
6685
Alex Light1f3925d2016-09-07 12:04:20 -07006686 CHECK_EQ(m->GetMethodIndexDuringLinking(), i)
David Sehr709b0702016-10-13 09:12:37 -07006687 << m->PrettyMethod()
6688 << " has an unexpected method index for its spot in the vtable for class"
6689 << klass->PrettyClass();
Alex Lighte64300b2015-12-15 15:02:47 -08006690 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6691 auto is_same_method = [m] (const ArtMethod& meth) {
6692 return &meth == m;
6693 };
6694 CHECK((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6695 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())
David Sehr709b0702016-10-13 09:12:37 -07006696 << m->PrettyMethod() << " does not seem to be owned by current class "
6697 << klass->PrettyClass() << " or any of its superclasses!";
Alex Lighte64300b2015-12-15 15:02:47 -08006698 }
6699}
6700
Alex Light1f3925d2016-09-07 12:04:20 -07006701// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
6702// method is overridden in a subclass.
6703static void CheckVTableHasNoDuplicates(Thread* self,
6704 Handle<mirror::Class> klass,
6705 PointerSize pointer_size)
6706 REQUIRES_SHARED(Locks::mutator_lock_) {
6707 StackHandleScope<1> hs(self);
6708 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6709 int32_t num_entries = vtable->GetLength();
6710 for (int32_t i = 0; i < num_entries; i++) {
6711 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6712 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe).
6713 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6714 vtable_entry->GetAccessFlags())) {
6715 continue;
6716 }
6717 MethodNameAndSignatureComparator name_comparator(
6718 vtable_entry->GetInterfaceMethodIfProxy(pointer_size));
Alex Lightc7a420c2016-10-18 14:33:18 -07006719 for (int32_t j = i + 1; j < num_entries; j++) {
Alex Light1f3925d2016-09-07 12:04:20 -07006720 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Alex Lightc7a420c2016-10-18 14:33:18 -07006721 if (!klass->CanAccessMember(other_entry->GetDeclaringClass(),
6722 other_entry->GetAccessFlags())) {
6723 continue;
6724 }
Alex Light1f3925d2016-09-07 12:04:20 -07006725 CHECK(vtable_entry != other_entry &&
6726 !name_comparator.HasSameNameAndSignature(
6727 other_entry->GetInterfaceMethodIfProxy(pointer_size)))
6728 << "vtable entries " << i << " and " << j << " are identical for "
Alex Lightc7a420c2016-10-18 14:33:18 -07006729 << klass->PrettyClass() << " in method " << vtable_entry->PrettyMethod() << " (0x"
6730 << std::hex << reinterpret_cast<uintptr_t>(vtable_entry) << ") and "
6731 << other_entry->PrettyMethod() << " (0x" << std::hex
6732 << reinterpret_cast<uintptr_t>(other_entry) << ")";
Alex Light1f3925d2016-09-07 12:04:20 -07006733 }
6734 }
6735}
6736
6737static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
6738 REQUIRES_SHARED(Locks::mutator_lock_) {
6739 CheckClassOwnsVTableEntries(self, klass, pointer_size);
6740 CheckVTableHasNoDuplicates(self, klass, pointer_size);
6741}
6742
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006743void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
6744 ArtMethod* unimplemented_method,
6745 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006746 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006747 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07006748 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006749 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006750 if (super_class->ShouldHaveImt()) {
6751 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6752 for (size_t i = 0; i < ImTable::kSize; ++i) {
6753 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07006754 }
6755 } else {
6756 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006757 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08006758 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006759 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006760 FillIMTFromIfTable(if_table,
6761 unimplemented_method,
6762 imt_conflict_method,
6763 klass.Get(),
6764 /*create_conflict_table*/false,
6765 /*ignore_copied_methods*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006766 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006767 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07006768 }
6769 }
6770}
6771
Vladimir Marko921094a2017-01-12 18:37:06 +00006772class ClassLinker::LinkInterfaceMethodsHelper {
6773 public:
6774 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
6775 Handle<mirror::Class> klass,
6776 Thread* self,
6777 Runtime* runtime)
6778 : class_linker_(class_linker),
6779 klass_(klass),
6780 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
6781 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
6782 self_(self),
6783 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
6784 allocator_(&stack_),
6785 default_conflict_methods_(allocator_.Adapter()),
6786 overriding_default_conflict_methods_(allocator_.Adapter()),
6787 miranda_methods_(allocator_.Adapter()),
6788 default_methods_(allocator_.Adapter()),
6789 overriding_default_methods_(allocator_.Adapter()),
6790 move_table_(allocator_.Adapter()) {
6791 }
6792
6793 ArtMethod* FindMethod(ArtMethod* interface_method,
6794 MethodNameAndSignatureComparator& interface_name_comparator,
6795 ArtMethod* vtable_impl)
6796 REQUIRES_SHARED(Locks::mutator_lock_);
6797
6798 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
6799 MethodNameAndSignatureComparator& interface_name_comparator)
6800 REQUIRES_SHARED(Locks::mutator_lock_);
6801
6802 bool HasNewVirtuals() const {
6803 return !(miranda_methods_.empty() &&
6804 default_methods_.empty() &&
6805 overriding_default_methods_.empty() &&
6806 overriding_default_conflict_methods_.empty() &&
6807 default_conflict_methods_.empty());
6808 }
6809
6810 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
6811
6812 ObjPtr<mirror::PointerArray> UpdateVtable(
6813 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
6814 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
6815
6816 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
6817
6818 void UpdateIMT(ArtMethod** out_imt);
6819
6820 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
6821 if (kIsDebugBuild) {
6822 PointerSize pointer_size = class_linker_->GetImagePointerSize();
6823 // Check that there are no stale methods are in the dex cache array.
6824 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
6825 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
6826 auto* m = mirror::DexCache::GetElementPtrSize(resolved_methods, i, pointer_size);
6827 CHECK(move_table_.find(m) == move_table_.end() ||
6828 // The original versions of copied methods will still be present so allow those too.
6829 // Note that if the first check passes this might fail to GetDeclaringClass().
6830 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
6831 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
6832 [m] (ArtMethod& meth) {
6833 return &meth == m;
6834 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
6835 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
6836 }
6837 }
6838 }
6839
6840 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
6841 LengthPrefixedArray<ArtMethod>* methods) {
6842 if (kIsDebugBuild) {
6843 CHECK(methods != nullptr);
6844 // Put some random garbage in old methods to help find stale pointers.
6845 if (methods != old_methods && old_methods != nullptr) {
6846 // Need to make sure the GC is not running since it could be scanning the methods we are
6847 // about to overwrite.
6848 ScopedThreadStateChange tsc(self_, kSuspended);
6849 gc::ScopedGCCriticalSection gcs(self_,
6850 gc::kGcCauseClassLinker,
6851 gc::kCollectorTypeClassLinker);
6852 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
6853 method_size_,
6854 method_alignment_);
6855 memset(old_methods, 0xFEu, old_size);
6856 }
6857 }
6858 }
6859
6860 private:
6861 size_t NumberOfNewVirtuals() const {
6862 return miranda_methods_.size() +
6863 default_methods_.size() +
6864 overriding_default_conflict_methods_.size() +
6865 overriding_default_methods_.size() +
6866 default_conflict_methods_.size();
6867 }
6868
6869 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
6870 return !klass_->IsInterface();
6871 }
6872
6873 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
6874 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
6875 << "Interfaces should only have default-conflict methods appended to them.";
6876 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
6877 << miranda_methods_.size()
6878 << " default_methods=" << default_methods_.size()
6879 << " overriding_default_methods=" << overriding_default_methods_.size()
6880 << " default_conflict_methods=" << default_conflict_methods_.size()
6881 << " overriding_default_conflict_methods="
6882 << overriding_default_conflict_methods_.size();
6883 }
6884
6885 ClassLinker* class_linker_;
6886 Handle<mirror::Class> klass_;
6887 size_t method_alignment_;
6888 size_t method_size_;
6889 Thread* const self_;
6890
6891 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
6892 // the virtual methods array.
6893 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
6894 // during cross compilation.
6895 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
6896 ArenaStack stack_;
6897 ScopedArenaAllocator allocator_;
6898
6899 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
6900 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
6901 ScopedArenaVector<ArtMethod*> miranda_methods_;
6902 ScopedArenaVector<ArtMethod*> default_methods_;
6903 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
6904
6905 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
6906};
6907
6908ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
6909 ArtMethod* interface_method,
6910 MethodNameAndSignatureComparator& interface_name_comparator,
6911 ArtMethod* vtable_impl) {
6912 ArtMethod* current_method = nullptr;
6913 switch (class_linker_->FindDefaultMethodImplementation(self_,
6914 interface_method,
6915 klass_,
6916 /*out*/&current_method)) {
6917 case DefaultMethodSearchResult::kDefaultConflict: {
6918 // Default method conflict.
6919 DCHECK(current_method == nullptr);
6920 ArtMethod* default_conflict_method = nullptr;
6921 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
6922 // We can reuse the method from the superclass, don't bother adding it to virtuals.
6923 default_conflict_method = vtable_impl;
6924 } else {
6925 // See if we already have a conflict method for this method.
6926 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
6927 interface_name_comparator,
6928 default_conflict_methods_,
6929 overriding_default_conflict_methods_);
6930 if (LIKELY(preexisting_conflict != nullptr)) {
6931 // We already have another conflict we can reuse.
6932 default_conflict_method = preexisting_conflict;
6933 } else {
6934 // Note that we do this even if we are an interface since we need to create this and
6935 // cannot reuse another classes.
6936 // Create a new conflict method for this to use.
6937 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6938 new(default_conflict_method) ArtMethod(interface_method,
6939 class_linker_->GetImagePointerSize());
6940 if (vtable_impl == nullptr) {
6941 // Save the conflict method. We need to add it to the vtable.
6942 default_conflict_methods_.push_back(default_conflict_method);
6943 } else {
6944 // Save the conflict method but it is already in the vtable.
6945 overriding_default_conflict_methods_.push_back(default_conflict_method);
6946 }
6947 }
6948 }
6949 current_method = default_conflict_method;
6950 break;
6951 } // case kDefaultConflict
6952 case DefaultMethodSearchResult::kDefaultFound: {
6953 DCHECK(current_method != nullptr);
6954 // Found a default method.
6955 if (vtable_impl != nullptr &&
6956 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
6957 // We found a default method but it was the same one we already have from our
6958 // superclass. Don't bother adding it to our vtable again.
6959 current_method = vtable_impl;
6960 } else if (LIKELY(FillTables())) {
6961 // Interfaces don't need to copy default methods since they don't have vtables.
6962 // Only record this default method if it is new to save space.
6963 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
6964 // would make lookup for interface super much faster. (We would only need to scan
6965 // the iftable to find if there is a NSME or AME.)
6966 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
6967 default_methods_,
6968 overriding_default_methods_);
6969 if (old == nullptr) {
6970 // We found a default method implementation and there were no conflicts.
6971 if (vtable_impl == nullptr) {
6972 // Save the default method. We need to add it to the vtable.
6973 default_methods_.push_back(current_method);
6974 } else {
6975 // Save the default method but it is already in the vtable.
6976 overriding_default_methods_.push_back(current_method);
6977 }
6978 } else {
6979 CHECK(old == current_method) << "Multiple default implementations selected!";
6980 }
6981 }
6982 break;
6983 } // case kDefaultFound
6984 case DefaultMethodSearchResult::kAbstractFound: {
6985 DCHECK(current_method == nullptr);
6986 // Abstract method masks all defaults.
6987 if (vtable_impl != nullptr &&
6988 vtable_impl->IsAbstract() &&
6989 !vtable_impl->IsDefaultConflicting()) {
6990 // We need to make this an abstract method but the version in the vtable already is so
6991 // don't do anything.
6992 current_method = vtable_impl;
6993 }
6994 break;
6995 } // case kAbstractFound
6996 }
6997 return current_method;
6998}
6999
7000ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7001 ArtMethod* interface_method,
7002 MethodNameAndSignatureComparator& interface_name_comparator) {
7003 // Find out if there is already a miranda method we can use.
7004 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7005 miranda_methods_);
7006 if (miranda_method == nullptr) {
7007 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7008 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7009 CHECK(miranda_method != nullptr);
7010 // Point the interface table at a phantom slot.
7011 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7012 miranda_methods_.push_back(miranda_method);
7013 }
7014 return miranda_method;
7015}
7016
7017void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7018 LogNewVirtuals();
7019
7020 const size_t old_method_count = klass_->NumMethods();
7021 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7022 DCHECK_NE(old_method_count, new_method_count);
7023
7024 // Attempt to realloc to save RAM if possible.
7025 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7026 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7027 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7028 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7029 // CopyFrom has internal read barriers.
7030 //
7031 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7032 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7033 method_size_,
7034 method_alignment_);
7035 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7036 method_size_,
7037 method_alignment_);
7038 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7039 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
7040 Runtime::Current()->GetLinearAlloc()->Realloc(
7041 self_, old_methods, old_methods_ptr_size, new_size));
7042 CHECK(methods != nullptr); // Native allocation failure aborts.
7043
7044 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7045 if (methods != old_methods) {
7046 // Maps from heap allocated miranda method to linear alloc miranda method.
7047 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7048 // Copy over the old methods.
7049 for (auto& m : klass_->GetMethods(pointer_size)) {
7050 move_table_.emplace(&m, &*out);
7051 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7052 // barriers when it copies.
7053 out->CopyFrom(&m, pointer_size);
7054 ++out;
7055 }
7056 }
7057 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7058 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7059 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007060 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7061 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007062 ArtMethod& new_method = *out;
7063 new_method.CopyFrom(mir_method, pointer_size);
7064 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7065 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7066 << "Miranda method should be abstract!";
7067 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007068 // Update the entry in the method array, as the array will be used for future lookups,
7069 // where thread suspension is allowed.
7070 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7071 // would not see them.
7072 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007073 ++out;
7074 }
7075 // We need to copy the default methods into our own method table since the runtime requires that
7076 // every method on a class's vtable be in that respective class's virtual method table.
7077 // NOTE This means that two classes might have the same implementation of a method from the same
7078 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7079 // default method found on a class with one found on the declaring interface directly and must
7080 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007081 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7082 &overriding_default_methods_}) {
7083 for (size_t i = 0; i < methods_vec->size(); ++i) {
7084 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007085 ArtMethod& new_method = *out;
7086 new_method.CopyFrom(def_method, pointer_size);
7087 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7088 // verified yet it shouldn't have methods that are skipping access checks.
7089 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7090 // methods are skip_access_checks.
7091 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7092 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7093 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7094 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007095 // Update the entry in the method array, as the array will be used for future lookups,
7096 // where thread suspension is allowed.
7097 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7098 // would not see them.
7099 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007100 ++out;
7101 }
7102 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007103 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7104 &overriding_default_conflict_methods_}) {
7105 for (size_t i = 0; i < methods_vec->size(); ++i) {
7106 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007107 ArtMethod& new_method = *out;
7108 new_method.CopyFrom(conf_method, pointer_size);
7109 // This is a type of default method (there are default method impls, just a conflict) so
7110 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7111 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7112 // methods that are skipping access checks.
7113 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
7114 constexpr uint32_t kMaskFlags = ~(kAccAbstract | kAccSkipAccessChecks);
7115 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7116 DCHECK(new_method.IsDefaultConflicting());
7117 // The actual method might or might not be marked abstract since we just copied it from a
7118 // (possibly default) interface method. We need to set it entry point to be the bridge so
7119 // that the compiler will not invoke the implementation of whatever method we copied from.
7120 EnsureThrowsInvocationError(class_linker_, &new_method);
7121 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007122 // Update the entry in the method array, as the array will be used for future lookups,
7123 // where thread suspension is allowed.
7124 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7125 // would not see them.
7126 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007127 ++out;
7128 }
7129 }
7130 methods->SetSize(new_method_count);
7131 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7132}
7133
7134ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7135 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7136 ObjPtr<mirror::PointerArray> old_vtable) {
7137 // Update the vtable to the new method structures. We can skip this for interfaces since they
7138 // do not have vtables.
7139 const size_t old_vtable_count = old_vtable->GetLength();
7140 const size_t new_vtable_count = old_vtable_count +
7141 miranda_methods_.size() +
7142 default_methods_.size() +
7143 default_conflict_methods_.size();
7144
7145 ObjPtr<mirror::PointerArray> vtable =
7146 down_cast<mirror::PointerArray*>(old_vtable->CopyOf(self_, new_vtable_count));
7147 if (UNLIKELY(vtable == nullptr)) {
7148 self_->AssertPendingOOMException();
7149 return nullptr;
7150 }
7151
7152 size_t vtable_pos = old_vtable_count;
7153 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7154 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7155 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7156 default_conflict_methods_,
7157 miranda_methods_}) {
7158 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007159 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007160 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7161 // fields are references into the dex file the method was defined in. Since the ArtMethod
7162 // does not store that information it uses declaring_class_->dex_cache_.
7163 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7164 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7165 ++vtable_pos;
7166 }
7167 }
7168 DCHECK_EQ(vtable_pos, new_vtable_count);
7169
7170 // Update old vtable methods. We use the default_translations map to figure out what each
7171 // vtable entry should be updated to, if they need to be at all.
7172 for (size_t i = 0; i < old_vtable_count; ++i) {
7173 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7174 // Try and find what we need to change this method to.
7175 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007176 if (translation_it != default_translations.end()) {
7177 if (translation_it->second.IsInConflict()) {
7178 // Find which conflict method we are to use for this method.
7179 MethodNameAndSignatureComparator old_method_comparator(
7180 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7181 // We only need to look through overriding_default_conflict_methods since this is an
7182 // overridden method we are fixing up here.
7183 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7184 old_method_comparator, overriding_default_conflict_methods_);
7185 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7186 translated_method = new_conflict_method;
7187 } else if (translation_it->second.IsAbstract()) {
7188 // Find which miranda method we are to use for this method.
7189 MethodNameAndSignatureComparator old_method_comparator(
7190 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7191 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7192 miranda_methods_);
7193 DCHECK(miranda_method != nullptr);
7194 translated_method = miranda_method;
7195 } else {
7196 // Normal default method (changed from an older default or abstract interface method).
7197 DCHECK(translation_it->second.IsTranslation());
7198 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007199 auto it = move_table_.find(translated_method);
7200 DCHECK(it != move_table_.end());
7201 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007202 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007203 } else {
7204 auto it = move_table_.find(translated_method);
7205 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007206 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007207
7208 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007209 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007210 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007211 if (kIsDebugBuild) {
7212 auto* methods = klass_->GetMethodsPtr();
7213 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007214 reinterpret_cast<uintptr_t>(translated_method));
7215 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007216 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7217 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007218 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007219 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007220 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007221 }
7222 }
7223 klass_->SetVTable(vtable.Ptr());
7224 return vtable;
7225}
7226
7227void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7228 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7229 const size_t ifcount = klass_->GetIfTableCount();
7230 // Go fix up all the stale iftable pointers.
7231 for (size_t i = 0; i < ifcount; ++i) {
7232 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7233 auto* method_array = iftable->GetMethodArray(i);
7234 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7235 DCHECK(m != nullptr) << klass_->PrettyClass();
7236 auto it = move_table_.find(m);
7237 if (it != move_table_.end()) {
7238 auto* new_m = it->second;
7239 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7240 method_array->SetElementPtrSize(j, new_m, pointer_size);
7241 }
7242 }
7243 }
7244}
7245
7246void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7247 // Fix up IMT next.
7248 for (size_t i = 0; i < ImTable::kSize; ++i) {
7249 auto it = move_table_.find(out_imt[i]);
7250 if (it != move_table_.end()) {
7251 out_imt[i] = it->second;
7252 }
7253 }
7254}
7255
Alex Light705ad492015-09-21 11:36:30 -07007256// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007257bool ClassLinker::LinkInterfaceMethods(
7258 Thread* self,
7259 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007260 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007261 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007262 ArtMethod** out_imt) {
7263 StackHandleScope<3> hs(self);
7264 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007265
7266 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007267 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007268 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007269 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007270 const size_t ifcount = klass->GetIfTableCount();
7271
Vladimir Marko921094a2017-01-12 18:37:06 +00007272 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007273
7274 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7275 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007276 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007277 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007278 const bool extend_super_iftable = has_superclass;
7279 if (has_superclass && fill_tables) {
7280 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007281 unimplemented_method,
7282 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007283 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007284 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007285 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007286 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7287 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007288 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007289 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7290 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007291 }
7292 }
7293
Vladimir Marko921094a2017-01-12 18:37:06 +00007294 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7295
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007296 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007297 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007298 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7299 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7300 // they will already be null. This has the additional benefit that the declarer of a miranda
7301 // method will actually declare an abstract method.
7302 for (size_t i = ifcount; i != 0; ) {
7303 --i;
7304
7305 DCHECK_GE(i, 0u);
7306 DCHECK_LT(i, ifcount);
7307
Alex Light705ad492015-09-21 11:36:30 -07007308 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007309 if (num_methods > 0) {
7310 StackHandleScope<2> hs2(self);
7311 const bool is_super = i < super_ifcount;
7312 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007313 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7314 // conflict methods. Just set this as nullptr in those cases.
7315 Handle<mirror::PointerArray> method_array(fill_tables
7316 ? hs2.NewHandle(iftable->GetMethodArray(i))
7317 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007318
Alex Lighte64300b2015-12-15 15:02:47 -08007319 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007320 ScopedNullHandle<mirror::PointerArray> null_handle;
7321 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007322 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007323
Alex Light9139e002015-10-09 15:59:48 -07007324 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7325 // and confusing. Default methods should always look through all the superclasses
7326 // because they are the last choice of an implementation. We get around this by looking
7327 // at the super-classes iftable methods (copied into method_array previously) when we are
7328 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007329 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007330 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007331 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007332 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007333 using_virtuals = true;
7334 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7335 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007336 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007337 // For a new interface, however, we need the whole vtable in case a new
7338 // interface method is implemented in the whole superclass.
7339 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007340 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007341 input_vtable_array = vtable;
7342 input_array_length = input_vtable_array->GetLength();
7343 }
Alex Lighte64300b2015-12-15 15:02:47 -08007344
Alex Lighteb7c1442015-08-31 13:17:42 -07007345 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007346 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007347 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007348 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007349 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Andreas Gampe75a7db62016-09-26 12:04:26 -07007350 uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Alex Lighteb7c1442015-08-31 13:17:42 -07007351 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007352 // For each method listed in the interface's method list, find the
7353 // matching method in our class's method list. We want to favor the
7354 // subclass over the superclass, which just requires walking
7355 // back from the end of the vtable. (This only matters if the
7356 // superclass defines a private method and this class redefines
7357 // it -- otherwise it would use the same vtable slot. In .dex files
7358 // those don't end up in the virtual method table, so it shouldn't
7359 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007360 //
7361 // To find defaults we need to do the same but also go over interfaces.
7362 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007363 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007364 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007365 ArtMethod* vtable_method = using_virtuals ?
7366 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007367 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7368 ArtMethod* vtable_method_for_name_comparison =
7369 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007370 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007371 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007372 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007373 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7374 // allocations.
7375 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007376 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007377 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007378 vtable_method->PrettyMethod().c_str(),
7379 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007380 return false;
Alex Light9139e002015-10-09 15:59:48 -07007381 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007382 // We might have a newer, better, default method for this, so we just skip it. If we
7383 // are still using this we will select it again when scanning for default methods. To
7384 // obviate the need to copy the method again we will make a note that we already found
7385 // a default here.
7386 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007387 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007388 break;
7389 } else {
7390 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007391 if (LIKELY(fill_tables)) {
7392 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7393 // Place method in imt if entry is empty, place conflict otherwise.
7394 SetIMTRef(unimplemented_method,
7395 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007396 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007397 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007398 /*out*/imt_ptr);
7399 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007400 break;
7401 }
7402 }
Alex Light9139e002015-10-09 15:59:48 -07007403 }
7404 // Continue on to the next method if we are done.
7405 if (LIKELY(found_impl)) {
7406 continue;
7407 } else if (LIKELY(super_interface)) {
7408 // Don't look for a default implementation when the super-method is implemented directly
7409 // by the class.
7410 //
7411 // See if we can use the superclasses method and skip searching everything else.
7412 // Note: !found_impl && super_interface
7413 CHECK(extend_super_iftable);
7414 // If this is a super_interface method it is possible we shouldn't override it because a
7415 // superclass could have implemented it directly. We get the method the superclass used
7416 // to implement this to know if we can override it with a default method. Doing this is
7417 // safe since we know that the super_iftable is filled in so we can simply pull it from
7418 // there. We don't bother if this is not a super-classes interface since in that case we
7419 // have scanned the entire vtable anyway and would have found it.
7420 // TODO This is rather dirty but it is faster than searching through the entire vtable
7421 // every time.
7422 ArtMethod* supers_method =
7423 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7424 DCHECK(supers_method != nullptr);
7425 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007426 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007427 // The method is not overridable by a default method (i.e. it is directly implemented
7428 // in some class). Therefore move onto the next interface method.
7429 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007430 } else {
7431 // If the super-classes method is override-able by a default method we need to keep
7432 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7433 // If it turns out not to be overridden and we did not keep track of it we might add it
Alex Light66630be2016-05-04 09:23:09 -07007434 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7435 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7436 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007437 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007438 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7439 << " and not 'nullptr' or "
7440 << supers_method->PrettyMethod()
7441 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007442 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007443 }
7444 }
7445 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007446 ArtMethod* current_method = helper.FindMethod(interface_method,
7447 interface_name_comparator,
7448 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007449 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007450 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007451 // We could not find an implementation for this method and since it is a brand new
7452 // interface we searched the entire vtable (and all default methods) for an
7453 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007454 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7455 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007456 }
7457
7458 if (current_method != nullptr) {
7459 // We found a default method implementation. Record it in the iftable and IMT.
7460 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7461 SetIMTRef(unimplemented_method,
7462 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007463 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007464 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007465 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007466 }
7467 }
Alex Light705ad492015-09-21 11:36:30 -07007468 } // For each method in interface end.
7469 } // if (num_methods > 0)
7470 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007471 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007472 if (helper.HasNewVirtuals()) {
7473 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7474 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7475 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7476
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007477 // Done copying methods, they are all roots in the class now, so we can end the no thread
Mathieu Chartiere401d142015-04-22 13:56:20 -07007478 // suspension assert.
7479 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007480
Alex Light705ad492015-09-21 11:36:30 -07007481 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007482 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007483 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007484 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07007485 return false;
7486 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007487 helper.UpdateIfTable(iftable);
7488 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007489 }
Alex Light705ad492015-09-21 11:36:30 -07007490
Vladimir Marko921094a2017-01-12 18:37:06 +00007491 helper.CheckNoStaleMethodsInDexCache();
7492 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007493 } else {
7494 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007495 }
Alex Light705ad492015-09-21 11:36:30 -07007496 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007497 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007498 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007499 return true;
7500}
7501
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007502bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007503 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007504 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007505}
7506
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007507bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007508 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007509 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007510}
7511
Brian Carlstromdbc05252011-09-09 01:59:59 -07007512struct LinkFieldsComparator {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007513 explicit LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07007514 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007515 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007516 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007517 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07007518 // First come reference fields, then 64-bit, then 32-bit, and then 16-bit, then finally 8-bit.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007519 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7520 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08007521 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00007522 if (type1 == Primitive::kPrimNot) {
7523 // Reference always goes first.
7524 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08007525 }
Vladimir Markod5777482014-11-12 17:02:02 +00007526 if (type2 == Primitive::kPrimNot) {
7527 // Reference always goes first.
7528 return false;
7529 }
7530 size_t size1 = Primitive::ComponentSize(type1);
7531 size_t size2 = Primitive::ComponentSize(type2);
7532 if (size1 != size2) {
7533 // Larger primitive types go first.
7534 return size1 > size2;
7535 }
7536 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7537 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007538 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007539 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7540 // by name and for equal names by type id index.
7541 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7542 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07007543 }
7544};
7545
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007546bool ClassLinker::LinkFields(Thread* self,
7547 Handle<mirror::Class> klass,
7548 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007549 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07007550 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07007551 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007552 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7553 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007554
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007555 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07007556 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007557 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007558 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007559 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007560 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007561 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07007562 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007563 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007564 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007565 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007566 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007567
David Sehr709b0702016-10-13 09:12:37 -07007568 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007569
Brian Carlstromdbc05252011-09-09 01:59:59 -07007570 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07007571 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08007572 //
7573 // The overall sort order order is:
7574 // 1) All object reference fields, sorted alphabetically.
7575 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7576 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7577 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7578 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7579 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7580 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7581 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7582 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7583 //
7584 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7585 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007586 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07007587 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07007588 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07007589 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007590 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007591 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07007592 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7593 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07007594
Fred Shih381e4ca2014-08-25 17:24:27 -07007595 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07007596 size_t current_field = 0;
7597 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07007598 FieldGaps gaps;
7599
Brian Carlstromdbc05252011-09-09 01:59:59 -07007600 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007601 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007602 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07007603 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007604 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07007605 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007606 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007607 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7608 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07007609 MemberOffset old_offset = field_offset;
7610 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7611 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7612 }
Roland Levillain14d90572015-07-16 10:52:26 +01007613 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007614 grouped_and_sorted_fields.pop_front();
7615 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007616 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00007617 field_offset = MemberOffset(field_offset.Uint32Value() +
7618 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007619 }
Fred Shih381e4ca2014-08-25 17:24:27 -07007620 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7621 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00007622 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7623 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7624 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7625 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07007626 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
7627 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07007628 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007629
Elliott Hughesadb460d2011-10-05 17:02:34 -07007630 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
Mathieu Chartier0cd81352014-05-22 16:48:55 -07007631 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07007632 // We know there are no non-reference fields in the Reference classes, and we know
7633 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07007634 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007635 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07007636 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07007637 --num_reference_fields;
7638 }
7639
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007640 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007641 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007642 if (is_static) {
7643 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007644 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007645 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007646 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007647 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007648 if (num_reference_fields == 0 || super_class == nullptr) {
7649 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007650 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007651 if (super_class == nullptr ||
7652 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
7653 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007654 }
7655 }
7656 if (kIsDebugBuild) {
7657 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
7658 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007659 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007660 while (cur_super != nullptr) {
7661 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
7662 cur_super = cur_super->GetSuperClass();
7663 }
7664 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07007665 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007666 } else {
7667 // Check that there is at least num_reference_fields other than Object.class.
7668 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07007669 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007670 }
7671 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07007672 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007673 std::string temp;
7674 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
7675 size_t previous_size = klass->GetObjectSize();
7676 if (previous_size != 0) {
7677 // Make sure that we didn't originally have an incorrect size.
7678 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07007679 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007680 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007681 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007682 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007683
7684 if (kIsDebugBuild) {
7685 // Make sure that the fields array is ordered by name but all reference
7686 // offsets are at the beginning as far as alignment allows.
7687 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07007688 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00007689 : klass->GetFirstReferenceInstanceFieldOffset();
7690 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
7691 num_reference_fields *
7692 sizeof(mirror::HeapReference<mirror::Object>));
7693 MemberOffset current_ref_offset = start_ref_offset;
7694 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007695 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007696 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07007697 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
7698 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007699 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007700 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007701 // NOTE: The field names can be the same. This is not possible in the Java language
7702 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007703 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00007704 }
7705 Primitive::Type type = field->GetTypeAsPrimitiveType();
7706 bool is_primitive = type != Primitive::kPrimNot;
7707 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
7708 strcmp("referent", field->GetName()) == 0) {
7709 is_primitive = true; // We lied above, so we have to expect a lie here.
7710 }
7711 MemberOffset offset = field->GetOffsetDuringLinking();
7712 if (is_primitive) {
7713 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
7714 // Shuffled before references.
7715 size_t type_size = Primitive::ComponentSize(type);
7716 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
7717 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
7718 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
7719 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
7720 }
7721 } else {
7722 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
7723 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
7724 sizeof(mirror::HeapReference<mirror::Object>));
7725 }
7726 }
7727 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
7728 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007729 return true;
7730}
7731
Vladimir Marko76649e82014-11-10 18:32:59 +00007732// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007733void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007734 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007735 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007736 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007737 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007738 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007739 // Compute reference offsets unless our superclass overflowed.
7740 if (reference_offsets != mirror::Class::kClassWalkSuper) {
7741 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007742 if (num_reference_fields != 0u) {
7743 // All of the fields that contain object references are guaranteed be grouped in memory
7744 // starting at an appropriately aligned address after super class object data.
7745 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
7746 sizeof(mirror::HeapReference<mirror::Object>));
7747 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007748 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00007749 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007750 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007751 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00007752 reference_offsets |= (0xffffffffu << start_bit) &
7753 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007754 }
7755 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07007756 }
7757 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07007758 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007759}
7760
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007761mirror::String* ClassLinker::ResolveString(const DexFile& dex_file,
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007762 dex::StringIndex string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007763 Handle<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007764 DCHECK(dex_cache != nullptr);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007765 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007766 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007767 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007768 return resolved.Ptr();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007769 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07007770 uint32_t utf16_length;
7771 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007772 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Mathieu Chartier5812e202017-02-13 18:32:04 -08007773 dex_cache->SetResolvedString(string_idx, string);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007774 return string.Ptr();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007775}
7776
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007777mirror::String* ClassLinker::LookupString(const DexFile& dex_file,
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007778 dex::StringIndex string_idx,
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007779 Handle<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007780 DCHECK(dex_cache != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007781 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007782 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007783 return resolved.Ptr();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007784 }
7785 uint32_t utf16_length;
7786 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007787 ObjPtr<mirror::String> string =
7788 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007789 if (string != nullptr) {
7790 dex_cache->SetResolvedString(string_idx, string);
7791 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007792 return string.Ptr();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007793}
7794
Mathieu Chartierb8901302016-09-30 10:27:43 -07007795ObjPtr<mirror::Class> ClassLinker::LookupResolvedType(const DexFile& dex_file,
Andreas Gampea5b09a62016-11-17 15:21:22 -08007796 dex::TypeIndex type_idx,
Mathieu Chartierb8901302016-09-30 10:27:43 -07007797 ObjPtr<mirror::DexCache> dex_cache,
7798 ObjPtr<mirror::ClassLoader> class_loader) {
7799 ObjPtr<mirror::Class> type = dex_cache->GetResolvedType(type_idx);
7800 if (type == nullptr) {
7801 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
7802 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
7803 if (descriptor[1] == '\0') {
7804 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
7805 // for primitive classes that aren't backed by dex files.
7806 type = FindPrimitiveClass(descriptor[0]);
7807 } else {
7808 Thread* const self = Thread::Current();
7809 DCHECK(self != nullptr);
7810 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
7811 // Find the class in the loaded classes table.
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07007812 type = LookupClass(self, descriptor, hash, class_loader.Ptr());
Mathieu Chartierb8901302016-09-30 10:27:43 -07007813 }
7814 }
Mathieu Chartier5812e202017-02-13 18:32:04 -08007815 if (type != nullptr && type->IsResolved()) {
7816 return type.Ptr();
7817 }
7818 return nullptr;
Mathieu Chartierb8901302016-09-30 10:27:43 -07007819}
7820
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007821mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
Andreas Gampea5b09a62016-11-17 15:21:22 -08007822 dex::TypeIndex type_idx,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007823 ObjPtr<mirror::Class> referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007824 StackHandleScope<2> hs(Thread::Current());
7825 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
7826 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07007827 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
7828}
7829
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007830mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
Andreas Gampea5b09a62016-11-17 15:21:22 -08007831 dex::TypeIndex type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007832 Handle<mirror::DexCache> dex_cache,
7833 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007834 DCHECK(dex_cache != nullptr);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007835 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007836 ObjPtr<mirror::Class> resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007837 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08007838 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07007839 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08007840 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007841 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05007842 // TODO: we used to throw here if resolved's class loader was not the
7843 // boot class loader. This was to permit different classes with the
7844 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007845 dex_cache->SetResolvedType(type_idx, resolved);
7846 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08007847 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08007848 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08007849 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007850 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00007851 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08007852 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007853 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08007854 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08007855 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00007856 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08007857 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007858 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007859 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00007860 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007861 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007862 return resolved.Ptr();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007863}
7864
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007865template <ClassLinker::ResolveMode kResolveMode>
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007866ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file,
7867 uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07007868 Handle<mirror::DexCache> dex_cache,
7869 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007870 ArtMethod* referrer,
7871 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007872 DCHECK(dex_cache != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07007873 // Check for hit in the dex cache.
Mathieu Chartiere401d142015-04-22 13:56:20 -07007874 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007875 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07007876 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007877 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007878 if (kResolveMode == ClassLinker::kForceICCECheck) {
7879 if (resolved->CheckIncompatibleClassChange(type)) {
7880 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
7881 return nullptr;
7882 }
7883 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007884 return resolved;
7885 }
Ian Rogers08f753d2012-08-24 14:35:25 -07007886 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007887 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007888 ObjPtr<mirror::Class> klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007889 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07007890 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007891 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007892 }
Ian Rogers08f753d2012-08-24 14:35:25 -07007893 // Scan using method_idx, this saves string compares but will only hit for matching dex
7894 // caches/files.
7895 switch (type) {
7896 case kDirect: // Fall-through.
7897 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007898 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7899 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07007900 break;
7901 case kInterface:
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007902 // We have to check whether the method id really belongs to an interface (dex static bytecode
7903 // constraint A15). Otherwise you must not invoke-interface on it.
7904 //
7905 // This is not symmetric to A12-A14 (direct, static, virtual), as using FindInterfaceMethod
7906 // assumes that the given type is an interface, and will check the interface table if the
7907 // method isn't declared in the class. So it may find an interface method (usually by name
7908 // in the handling below, but we do the constraint check early). In that case,
7909 // CheckIncompatibleClassChange will succeed (as it is called on an interface method)
7910 // unexpectedly.
7911 // Example:
7912 // interface I {
7913 // foo()
7914 // }
7915 // class A implements I {
7916 // ...
7917 // }
7918 // class B extends A {
7919 // ...
7920 // }
7921 // invoke-interface B.foo
7922 // -> FindInterfaceMethod finds I.foo (interface method), not A.foo (miranda method)
7923 if (UNLIKELY(!klass->IsInterface())) {
7924 ThrowIncompatibleClassChangeError(klass,
7925 "Found class %s, but interface was expected",
David Sehr709b0702016-10-13 09:12:37 -07007926 klass->PrettyDescriptor().c_str());
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007927 return nullptr;
7928 } else {
7929 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7930 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
7931 }
Ian Rogers08f753d2012-08-24 14:35:25 -07007932 break;
Alex Light705ad492015-09-21 11:36:30 -07007933 case kSuper:
7934 if (klass->IsInterface()) {
7935 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7936 } else {
7937 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7938 }
7939 break;
Ian Rogers08f753d2012-08-24 14:35:25 -07007940 case kVirtual:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007941 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07007942 break;
7943 default:
7944 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07007945 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07007946 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007947 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07007948 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08007949 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07007950 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07007951 switch (type) {
7952 case kDirect: // Fall-through.
7953 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007954 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_);
7955 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07007956 break;
7957 case kInterface:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007958 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007959 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07007960 break;
Alex Light705ad492015-09-21 11:36:30 -07007961 case kSuper:
7962 if (klass->IsInterface()) {
7963 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
7964 } else {
7965 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
7966 }
7967 break;
Ian Rogers08f753d2012-08-24 14:35:25 -07007968 case kVirtual:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007969 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07007970 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08007971 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007972 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007973 // If we found a method, check for incompatible class changes.
7974 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07007975 // Be a good citizen and update the dex cache to speed subsequent calls.
Mathieu Chartiere401d142015-04-22 13:56:20 -07007976 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07007977 return resolved;
7978 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007979 // If we had a method, it's an incompatible-class-change error.
7980 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007981 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007982 } else {
7983 // We failed to find the method which means either an access error, an incompatible class
7984 // change, or no such method. First try to find the method among direct and virtual methods.
7985 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
7986 const Signature signature = dex_file.GetMethodSignature(method_id);
7987 switch (type) {
7988 case kDirect:
7989 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007990 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007991 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
7992 // have had a resolved method before, which triggers the "true" branch above.
7993 break;
7994 case kInterface:
7995 case kVirtual:
7996 case kSuper:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007997 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007998 break;
7999 }
8000
8001 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08008002 bool exception_generated = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008003 if (resolved != nullptr && referrer != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008004 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8005 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008006 if (!referring_class->CanAccess(methods_class)) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008007 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class,
8008 methods_class,
8009 resolved,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008010 type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008011 exception_generated = true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008012 } else if (!referring_class->CanAccessMember(methods_class, resolved->GetAccessFlags())) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008013 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008014 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008015 }
8016 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008017 if (!exception_generated) {
8018 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
8019 // interface methods and throw if we find the method there. If we find nothing, throw a
8020 // NoSuchMethodError.
8021 switch (type) {
8022 case kDirect:
8023 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008024 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008025 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008026 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008027 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008028 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008029 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008030 } else {
8031 ThrowNoSuchMethodError(type, klass, name, signature);
8032 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008033 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008034 break;
8035 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008036 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008037 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008038 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008039 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008040 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008041 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008042 } else {
8043 ThrowNoSuchMethodError(type, klass, name, signature);
8044 }
8045 }
8046 break;
8047 case kSuper:
8048 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008049 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008050 } else {
8051 ThrowNoSuchMethodError(type, klass, name, signature);
8052 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008053 break;
8054 case kVirtual:
8055 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008056 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008057 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008058 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008059 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008060 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008061 } else {
8062 ThrowNoSuchMethodError(type, klass, name, signature);
8063 }
8064 }
8065 break;
8066 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008067 }
Ian Rogers08f753d2012-08-24 14:35:25 -07008068 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008069 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008070 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008071 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008072}
8073
Jeff Hao13e748b2015-08-25 20:44:19 +00008074ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(const DexFile& dex_file,
8075 uint32_t method_idx,
8076 Handle<mirror::DexCache> dex_cache,
8077 Handle<mirror::ClassLoader> class_loader) {
8078 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008079 Thread::PoisonObjectPointersIfDebug();
Jeff Hao13e748b2015-08-25 20:44:19 +00008080 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
8081 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8082 return resolved;
8083 }
8084 // Fail, get the declaring class.
8085 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008086 ObjPtr<mirror::Class> klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008087 if (klass == nullptr) {
8088 Thread::Current()->AssertPendingException();
8089 return nullptr;
8090 }
8091 if (klass->IsInterface()) {
David Sehr709b0702016-10-13 09:12:37 -07008092 LOG(FATAL) << "ResolveAmbiguousMethod: unexpected method in interface: "
8093 << klass->PrettyClass();
Jeff Hao13e748b2015-08-25 20:44:19 +00008094 return nullptr;
8095 }
8096
8097 // Search both direct and virtual methods
8098 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8099 if (resolved == nullptr) {
8100 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8101 }
8102
8103 return resolved;
8104}
8105
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008106ArtField* ClassLinker::ResolveField(const DexFile& dex_file,
8107 uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008108 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008109 Handle<mirror::ClassLoader> class_loader,
8110 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008111 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008112 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008113 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008114 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008115 return resolved;
8116 }
8117 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07008118 Thread* const self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00008119 ObjPtr<mirror::Class> klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
8120 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008121 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008122 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008123 }
8124
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008125 if (is_static) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008126 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008127 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07008128 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008129 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008130
Andreas Gampe58a5af82014-07-31 16:23:49 -07008131 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008132 const char* name = dex_file.GetFieldName(field_id);
8133 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8134 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07008135 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008136 } else {
8137 resolved = klass->FindInstanceField(name, type);
8138 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07008139 if (resolved == nullptr) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008140 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008141 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008142 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008143 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07008144 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08008145 return resolved;
8146}
8147
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008148ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
8149 uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008150 Handle<mirror::DexCache> dex_cache,
8151 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008152 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008153 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008154 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008155 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008156 return resolved;
8157 }
8158 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07008159 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00008160 ObjPtr<mirror::Class> klass(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader));
8161 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008162 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008163 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008164 }
8165
Ian Rogersdfb325e2013-10-30 01:00:44 -07008166 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
8167 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07008168 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07008169 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008170 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008171 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08008172 } else {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008173 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008174 }
8175 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008176}
8177
Narayan Kamath25352fc2016-08-03 12:46:58 +01008178mirror::MethodType* ClassLinker::ResolveMethodType(const DexFile& dex_file,
8179 uint32_t proto_idx,
8180 Handle<mirror::DexCache> dex_cache,
8181 Handle<mirror::ClassLoader> class_loader) {
8182 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008183 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008184
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008185 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008186 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008187 return resolved.Ptr();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008188 }
8189
8190 Thread* const self = Thread::Current();
8191 StackHandleScope<4> hs(self);
8192
8193 // First resolve the return type.
8194 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
8195 Handle<mirror::Class> return_type(hs.NewHandle(
8196 ResolveType(dex_file, proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008197 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008198 DCHECK(self->IsExceptionPending());
8199 return nullptr;
8200 }
8201
8202 // Then resolve the argument types.
8203 //
8204 // TODO: Is there a better way to figure out the number of method arguments
8205 // other than by looking at the shorty ?
8206 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8207
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008208 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008209 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008210 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8211 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008212 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008213 DCHECK(self->IsExceptionPending());
8214 return nullptr;
8215 }
8216
8217 DexFileParameterIterator it(dex_file, proto_id);
8218 int32_t i = 0;
8219 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8220 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008221 const dex::TypeIndex type_idx = it.GetTypeIdx();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008222 param_class.Assign(ResolveType(dex_file, type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008223 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008224 DCHECK(self->IsExceptionPending());
8225 return nullptr;
8226 }
8227
8228 method_params->Set(i++, param_class.Get());
8229 }
8230
8231 DCHECK(!it.HasNext());
8232
8233 Handle<mirror::MethodType> type = hs.NewHandle(
8234 mirror::MethodType::Create(self, return_type, method_params));
8235 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8236
8237 return type.Get();
8238}
8239
Orion Hodsonc069a302017-01-18 09:23:12 +00008240mirror::MethodHandle* ClassLinker::ResolveMethodHandle(uint32_t method_handle_idx,
8241 ArtMethod* referrer)
8242 REQUIRES_SHARED(Locks::mutator_lock_) {
8243 Thread* const self = Thread::Current();
8244 const DexFile* const dex_file = referrer->GetDexFile();
8245 const DexFile::MethodHandleItem& mh = dex_file->GetMethodHandle(method_handle_idx);
8246
8247 union {
8248 ArtField* field;
8249 ArtMethod* method;
8250 uintptr_t field_or_method;
8251 } target;
8252 uint32_t num_params;
8253 mirror::MethodHandle::Kind kind;
8254 DexFile::MethodHandleType handle_type =
8255 static_cast<DexFile::MethodHandleType>(mh.method_handle_type_);
8256 switch (handle_type) {
8257 case DexFile::MethodHandleType::kStaticPut: {
8258 kind = mirror::MethodHandle::Kind::kStaticPut;
8259 target.field = ResolveField(mh.field_or_method_idx_, referrer, true /* is_static */);
8260 num_params = 1;
8261 break;
8262 }
8263 case DexFile::MethodHandleType::kStaticGet: {
8264 kind = mirror::MethodHandle::Kind::kStaticGet;
8265 target.field = ResolveField(mh.field_or_method_idx_, referrer, true /* is_static */);
8266 num_params = 0;
8267 break;
8268 }
8269 case DexFile::MethodHandleType::kInstancePut: {
8270 kind = mirror::MethodHandle::Kind::kInstancePut;
8271 target.field = ResolveField(mh.field_or_method_idx_, referrer, false /* is_static */);
8272 num_params = 2;
8273 break;
8274 }
8275 case DexFile::MethodHandleType::kInstanceGet: {
8276 kind = mirror::MethodHandle::Kind::kInstanceGet;
8277 target.field = ResolveField(mh.field_or_method_idx_, referrer, false /* is_static */);
8278 num_params = 1;
8279 break;
8280 }
8281 case DexFile::MethodHandleType::kInvokeStatic: {
8282 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8283 target.method = ResolveMethod<kNoICCECheckForCache>(self,
8284 mh.field_or_method_idx_,
8285 referrer,
8286 InvokeType::kStatic);
8287 uint32_t shorty_length;
8288 target.method->GetShorty(&shorty_length);
8289 num_params = shorty_length - 1; // Remove 1 for return value.
8290 break;
8291 }
8292 case DexFile::MethodHandleType::kInvokeInstance: {
8293 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8294 target.method = ResolveMethod<kNoICCECheckForCache>(self,
8295 mh.field_or_method_idx_,
8296 referrer,
8297 InvokeType::kVirtual);
8298 uint32_t shorty_length;
8299 target.method->GetShorty(&shorty_length);
8300 num_params = shorty_length - 1; // Remove 1 for return value.
8301 break;
8302 }
8303 case DexFile::MethodHandleType::kInvokeConstructor: {
8304 UNIMPLEMENTED(FATAL) << "Invoke constructor is implemented as a transform.";
8305 num_params = 0;
8306 }
8307 }
8308
8309 StackHandleScope<5> hs(self);
8310 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8311 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8312 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8313 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
8314 if (method_params.Get() == nullptr) {
8315 DCHECK(self->IsExceptionPending());
8316 return nullptr;
8317 }
8318
8319 Handle<mirror::Class> return_type;
8320 switch (handle_type) {
8321 case DexFile::MethodHandleType::kStaticPut: {
8322 method_params->Set(0, target.field->GetType<true>());
8323 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8324 break;
8325 }
8326 case DexFile::MethodHandleType::kStaticGet: {
8327 return_type = hs.NewHandle(target.field->GetType<true>());
8328 break;
8329 }
8330 case DexFile::MethodHandleType::kInstancePut: {
8331 method_params->Set(0, target.field->GetDeclaringClass());
8332 method_params->Set(1, target.field->GetType<true>());
8333 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8334 break;
8335 }
8336 case DexFile::MethodHandleType::kInstanceGet: {
8337 method_params->Set(0, target.field->GetDeclaringClass());
8338 return_type = hs.NewHandle(target.field->GetType<true>());
8339 break;
8340 }
8341 case DexFile::MethodHandleType::kInvokeStatic:
8342 case DexFile::MethodHandleType::kInvokeInstance: {
8343 // TODO(oth): This will not work for varargs methods as this
8344 // requires instantiating a Transformer. This resolution step
8345 // would be best done in managed code rather than in the run
8346 // time (b/35235705)
8347 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8348 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8349 DexFileParameterIterator it(*dex_file, target.method->GetPrototype());
8350 for (int32_t i = 0; it.HasNext(); i++, it.Next()) {
8351 const dex::TypeIndex type_idx = it.GetTypeIdx();
8352 mirror::Class* klass = ResolveType(*dex_file, type_idx, dex_cache, class_loader);
8353 if (nullptr == klass) {
8354 DCHECK(self->IsExceptionPending());
8355 return nullptr;
8356 }
8357 method_params->Set(i, klass);
8358 }
8359 return_type = hs.NewHandle(target.method->GetReturnType(true));
8360 break;
8361 }
8362 case DexFile::MethodHandleType::kInvokeConstructor: {
8363 // TODO(oth): b/35235705
8364 UNIMPLEMENTED(FATAL) << "Invoke constructor is implemented as a transform.";
8365 }
8366 }
8367
8368 if (return_type.IsNull()) {
8369 DCHECK(self->IsExceptionPending());
8370 return nullptr;
8371 }
8372
8373 Handle<mirror::MethodType>
8374 mt(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8375 if (mt.IsNull()) {
8376 DCHECK(self->IsExceptionPending());
8377 return nullptr;
8378 }
8379 return mirror::MethodHandleImpl::Create(self, target.field_or_method, kind, mt);
8380}
8381
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008382bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
8383 return (entry_point == GetQuickResolutionStub()) ||
8384 (quick_resolution_trampoline_ == entry_point);
8385}
8386
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008387bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
8388 return (entry_point == GetQuickToInterpreterBridge()) ||
8389 (quick_to_interpreter_bridge_trampoline_ == entry_point);
8390}
8391
8392bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
8393 return (entry_point == GetQuickGenericJniStub()) ||
8394 (quick_generic_jni_trampoline_ == entry_point);
8395}
8396
8397const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
8398 return GetQuickGenericJniStub();
8399}
8400
Andreas Gampecc1b5352016-12-01 16:58:38 -08008401void ClassLinker::SetEntryPointsToCompiledCode(ArtMethod* method, const void* code) const {
8402 CHECK(code != nullptr);
8403 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
8404 base -= sizeof(void*); // Move backward so that code_offset != 0.
8405 const uint32_t code_offset = sizeof(void*);
8406 OatFile::OatMethod oat_method(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008407 oat_method.LinkMethod(method);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008408}
8409
Mathieu Chartiere401d142015-04-22 13:56:20 -07008410void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008411 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008412 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
8413 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08008414 SetEntryPointsToCompiledCode(method, GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008415 }
8416}
8417
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008418void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07008419 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07008420 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008421 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
8422 << NumNonZygoteClasses() << "\n";
8423}
8424
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008425class CountClassesVisitor : public ClassLoaderVisitor {
8426 public:
8427 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
8428
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008429 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07008430 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008431 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07008432 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00008433 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
8434 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07008435 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008436 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008437
8438 size_t num_zygote_classes;
8439 size_t num_non_zygote_classes;
8440};
8441
8442size_t ClassLinker::NumZygoteClasses() const {
8443 CountClassesVisitor visitor;
8444 VisitClassLoaders(&visitor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00008445 return visitor.num_zygote_classes + boot_class_table_.NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008446}
8447
8448size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008449 CountClassesVisitor visitor;
8450 VisitClassLoaders(&visitor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00008451 return visitor.num_non_zygote_classes + boot_class_table_.NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07008452}
8453
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008454size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07008455 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08008456 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008457 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07008458}
8459
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008460pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07008461 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008462}
8463
8464pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08008465 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07008466}
8467
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008468void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008469 DCHECK(!init_done_);
8470
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008471 DCHECK(klass != nullptr);
8472 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008473
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07008474 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008475 DCHECK(class_roots != nullptr);
8476 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07008477 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008478}
8479
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008480const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
8481 static const char* class_roots_descriptors[] = {
8482 "Ljava/lang/Class;",
8483 "Ljava/lang/Object;",
8484 "[Ljava/lang/Class;",
8485 "[Ljava/lang/Object;",
8486 "Ljava/lang/String;",
8487 "Ljava/lang/DexCache;",
8488 "Ljava/lang/ref/Reference;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008489 "Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008490 "Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008491 "Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008492 "Ljava/lang/reflect/Proxy;",
8493 "[Ljava/lang/String;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008494 "[Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008495 "[Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008496 "[Ljava/lang/reflect/Method;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008497 "Ljava/lang/invoke/CallSite;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008498 "Ljava/lang/invoke/MethodHandleImpl;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008499 "Ljava/lang/invoke/MethodHandles$Lookup;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008500 "Ljava/lang/invoke/MethodType;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008501 "Ljava/lang/ClassLoader;",
8502 "Ljava/lang/Throwable;",
8503 "Ljava/lang/ClassNotFoundException;",
8504 "Ljava/lang/StackTraceElement;",
Narayan Kamath000e1882016-10-24 17:14:25 +01008505 "Ldalvik/system/EmulatedStackFrame;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008506 "Z",
8507 "B",
8508 "C",
8509 "D",
8510 "F",
8511 "I",
8512 "J",
8513 "S",
8514 "V",
8515 "[Z",
8516 "[B",
8517 "[C",
8518 "[D",
8519 "[F",
8520 "[I",
8521 "[J",
8522 "[S",
8523 "[Ljava/lang/StackTraceElement;",
Alex Lightd6251582016-10-31 11:12:30 -07008524 "Ldalvik/system/ClassExt;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008525 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08008526 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
8527 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008528
8529 const char* descriptor = class_roots_descriptors[class_root];
8530 CHECK(descriptor != nullptr);
8531 return descriptor;
8532}
8533
Jeff Hao5872d7c2016-04-27 11:07:41 -07008534jobject ClassLinker::CreatePathClassLoader(Thread* self,
8535 const std::vector<const DexFile*>& dex_files) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008536 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
8537 // We could move the jobject to the callers, but all call-sites do this...
8538 ScopedObjectAccessUnchecked soa(self);
8539
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008540 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Vladimir Marko19a4d372016-12-08 14:41:46 +00008541 StackHandleScope<6> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008542
Mathieu Chartierc7853442015-03-27 14:35:38 -07008543 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008544 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008545
Mathieu Chartier3398c782016-09-30 10:27:43 -07008546 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->GetType<true>()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008547 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008548 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008549 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07008550 mirror::ObjectArray<mirror::Object>::Alloc(self,
8551 dex_elements_class.Get(),
8552 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008553 Handle<mirror::Class> h_dex_element_class =
8554 hs.NewHandle(dex_elements_class->GetComponentType());
8555
Mathieu Chartierc7853442015-03-27 14:35:38 -07008556 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008557 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008558 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008559
Andreas Gampe08883de2016-11-08 13:20:52 -08008560 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008561 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008562
Andreas Gampe08883de2016-11-08 13:20:52 -08008563 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008564 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->GetType<false>());
8565
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008566 // Fill the elements array.
8567 int32_t index = 0;
8568 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008569 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008570
Mathieu Chartier966878d2016-01-14 14:33:29 -08008571 // CreatePathClassLoader is only used by gtests. Index 0 of h_long_array is supposed to be the
8572 // oat file but we can leave it null.
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008573 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
8574 self,
8575 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008576 DCHECK(h_long_array != nullptr);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008577 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008578
8579 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008580 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008581 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008582 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008583
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008584 Handle<mirror::String> h_file_name = hs2.NewHandle(
8585 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008586 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008587 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
8588
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008589 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008590 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008591 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008592
8593 h_dex_elements->Set(index, h_element.Get());
8594 index++;
8595 }
8596 DCHECK_EQ(index, h_dex_elements->GetLength());
8597
8598 // Create DexPathList.
8599 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008600 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008601 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008602 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008603 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008604
8605 // Create PathClassLoader.
8606 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -07008607 soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008608 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
8609 h_path_class_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008610 DCHECK(h_path_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008611 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008612 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008613 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008614 DCHECK(path_list_field != nullptr);
8615 path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008616
8617 // Make a pretend boot-classpath.
8618 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07008619 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00008620 mirror::Class::FindField(self,
8621 h_path_class_loader->GetClass(),
8622 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07008623 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01008624 DCHECK(parent_field != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07008625 ObjPtr<mirror::Object> boot_cl =
Mathieu Chartier0795f232016-09-27 18:43:30 -07008626 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
Mathieu Chartier966878d2016-01-14 14:33:29 -08008627 parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008628
8629 // Make it a global ref and return.
8630 ScopedLocalRef<jobject> local_ref(
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07008631 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008632 return soa.Env()->NewGlobalRef(local_ref.get());
8633}
8634
Andreas Gampe8ac75952015-06-02 21:01:45 -07008635void ClassLinker::DropFindArrayClassCache() {
8636 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
8637 find_array_class_cache_next_victim_ = 0;
8638}
8639
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07008640void ClassLinker::ClearClassTableStrongRoots() const {
8641 Thread* const self = Thread::Current();
8642 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8643 for (const ClassLoaderData& data : class_loaders_) {
8644 if (data.class_table != nullptr) {
8645 data.class_table->ClearStrongRoots();
8646 }
8647 }
8648}
8649
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008650void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008651 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008652 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07008653 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008654 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
8655 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008656 if (class_loader != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008657 visitor->Visit(class_loader.Ptr());
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008658 }
8659 }
8660}
8661
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008662void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
8663 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008664 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07008665 Thread* const self = Thread::Current();
8666 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008667 ClassTable* const table = ClassTableForClassLoader(class_loader.Ptr());
Mathieu Chartier00310e02015-10-17 12:46:42 -07008668 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07008669 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008670 // It was not already inserted, perform the write barrier to let the GC know the class loader's
8671 // class table was modified.
8672 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
8673 }
8674}
8675
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008676void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008677 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07008678 std::vector<ClassLoaderData> to_delete;
8679 // Do the delete outside the lock to avoid lock violation in jit code cache.
8680 {
8681 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8682 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
8683 const ClassLoaderData& data = *it;
8684 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008685 ObjPtr<mirror::ClassLoader> class_loader =
8686 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07008687 if (class_loader != nullptr) {
8688 ++it;
8689 } else {
8690 VLOG(class_linker) << "Freeing class loader";
8691 to_delete.push_back(data);
8692 it = class_loaders_.erase(it);
8693 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008694 }
8695 }
Mathieu Chartier65975772016-08-05 10:46:36 -07008696 for (ClassLoaderData& data : to_delete) {
8697 DeleteClassLoader(self, data);
8698 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008699}
8700
Vladimir Marko21300532017-01-24 18:06:55 +00008701class GetResolvedClassesVisitor : public ClassVisitor {
8702 public:
8703 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
8704 : result_(result),
8705 ignore_boot_classes_(ignore_boot_classes),
8706 last_resolved_classes_(result->end()),
8707 last_dex_file_(nullptr),
8708 vlog_is_on_(VLOG_IS_ON(class_linker)),
8709 extra_stats_(),
8710 last_extra_stats_(extra_stats_.end()) { }
8711
8712 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
8713 if (!klass->IsProxyClass() &&
8714 !klass->IsArrayClass() &&
8715 klass->IsResolved() &&
8716 !klass->IsErroneousResolved() &&
8717 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
8718 const DexFile& dex_file = klass->GetDexFile();
8719 if (&dex_file != last_dex_file_) {
8720 last_dex_file_ = &dex_file;
8721 DexCacheResolvedClasses resolved_classes(dex_file.GetLocation(),
8722 dex_file.GetBaseLocation(),
8723 dex_file.GetLocationChecksum());
8724 last_resolved_classes_ = result_->find(resolved_classes);
8725 if (last_resolved_classes_ == result_->end()) {
8726 last_resolved_classes_ = result_->insert(resolved_classes).first;
8727 }
8728 }
8729 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
8730 if (UNLIKELY(vlog_is_on_) && added) {
8731 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
8732 if (last_extra_stats_ == extra_stats_.end() ||
8733 last_extra_stats_->first != resolved_classes) {
8734 last_extra_stats_ = extra_stats_.find(resolved_classes);
8735 if (last_extra_stats_ == extra_stats_.end()) {
8736 last_extra_stats_ =
8737 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
8738 }
8739 }
8740 }
8741 }
8742 return true;
8743 }
8744
8745 void PrintStatistics() const {
8746 if (vlog_is_on_) {
8747 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
8748 auto it = extra_stats_.find(std::addressof(resolved_classes));
8749 DCHECK(it != extra_stats_.end());
8750 const ExtraStats& extra_stats = it->second;
8751 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
8752 << " has " << resolved_classes.GetClasses().size() << " / "
8753 << extra_stats.number_of_class_defs_ << " resolved classes";
8754 }
8755 }
8756 }
8757
8758 private:
8759 struct ExtraStats {
8760 explicit ExtraStats(uint32_t number_of_class_defs)
8761 : number_of_class_defs_(number_of_class_defs) {}
8762 uint32_t number_of_class_defs_;
8763 };
8764
8765 std::set<DexCacheResolvedClasses>* result_;
8766 bool ignore_boot_classes_;
8767 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
8768 const DexFile* last_dex_file_;
8769
8770 // Statistics.
8771 bool vlog_is_on_;
8772 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
8773 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
8774};
8775
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008776std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08008777 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008778 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07008779 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008780 std::set<DexCacheResolvedClasses> ret;
8781 VLOG(class_linker) << "Collecting resolved classes";
8782 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00008783 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
8784 VisitClasses(&visitor);
8785 if (VLOG_IS_ON(class_linker)) {
8786 visitor.PrintStatistics();
8787 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008788 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008789 return ret;
8790}
8791
8792std::unordered_set<std::string> ClassLinker::GetClassDescriptorsForProfileKeys(
8793 const std::set<DexCacheResolvedClasses>& classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08008794 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008795 std::unordered_set<std::string> ret;
8796 Thread* const self = Thread::Current();
8797 std::unordered_map<std::string, const DexFile*> location_to_dex_file;
8798 ScopedObjectAccess soa(self);
Mathieu Chartier268764d2016-09-13 12:09:38 -07008799 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Andreas Gampecc1b5352016-12-01 16:58:38 -08008800 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008801 for (const ClassLinker::DexCacheData& data : GetDexCachesData()) {
8802 if (!self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008803 ObjPtr<mirror::DexCache> dex_cache = soa.Decode<mirror::DexCache>(data.weak_root);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008804 if (dex_cache != nullptr) {
8805 const DexFile* dex_file = dex_cache->GetDexFile();
8806 // There could be duplicates if two dex files with the same location are mapped.
8807 location_to_dex_file.emplace(
8808 ProfileCompilationInfo::GetProfileDexFileKey(dex_file->GetLocation()), dex_file);
8809 }
8810 }
8811 }
8812 for (const DexCacheResolvedClasses& info : classes) {
8813 const std::string& profile_key = info.GetDexLocation();
8814 auto found = location_to_dex_file.find(profile_key);
8815 if (found != location_to_dex_file.end()) {
8816 const DexFile* dex_file = found->second;
8817 VLOG(profiler) << "Found opened dex file for " << dex_file->GetLocation() << " with "
8818 << info.GetClasses().size() << " classes";
8819 DCHECK_EQ(dex_file->GetLocationChecksum(), info.GetLocationChecksum());
Andreas Gampea5b09a62016-11-17 15:21:22 -08008820 for (dex::TypeIndex type_idx : info.GetClasses()) {
Jeff Hao54b58552016-11-16 15:15:04 -08008821 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_idx);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008822 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
8823 ret.insert(descriptor);
8824 }
8825 } else {
8826 VLOG(class_linker) << "Failed to find opened dex file for profile key " << profile_key;
8827 }
8828 }
8829 return ret;
8830}
8831
Mathieu Chartier65975772016-08-05 10:46:36 -07008832class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
8833 public:
8834 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
8835 : method_(method),
8836 pointer_size_(pointer_size) {}
8837
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008838 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier65975772016-08-05 10:46:36 -07008839 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
8840 holder_ = klass;
8841 }
8842 // Return false to stop searching if holder_ is not null.
8843 return holder_ == nullptr;
8844 }
8845
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008846 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07008847 const ArtMethod* const method_;
8848 const PointerSize pointer_size_;
8849};
8850
8851mirror::Class* ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
8852 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
8853 CHECK(method->IsCopied());
8854 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
8855 VisitClasses(&visitor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008856 return visitor.holder_.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07008857}
8858
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008859// Instantiate ResolveMethod.
8860template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::kForceICCECheck>(
8861 const DexFile& dex_file,
8862 uint32_t method_idx,
8863 Handle<mirror::DexCache> dex_cache,
8864 Handle<mirror::ClassLoader> class_loader,
8865 ArtMethod* referrer,
8866 InvokeType type);
8867template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::kNoICCECheckForCache>(
8868 const DexFile& dex_file,
8869 uint32_t method_idx,
8870 Handle<mirror::DexCache> dex_cache,
8871 Handle<mirror::ClassLoader> class_loader,
8872 ArtMethod* referrer,
8873 InvokeType type);
8874
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008875} // namespace art