blob: fe91272ef74825ffba9944027e9bb5783fdc9e00 [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
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070019#include <unistd.h>
20
Alex Lighteb7c1442015-08-31 13:17:42 -070021#include <algorithm>
Brian Carlstromdbc05252011-09-09 01:59:59 -070022#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070023#include <iostream>
Vladimir Marko21300532017-01-24 18:06:55 +000024#include <map>
Ian Rogers700a4022014-05-19 16:49:03 -070025#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070026#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070027#include <string>
Alex Lighteb7c1442015-08-31 13:17:42 -070028#include <tuple>
Alex Lighteb7c1442015-08-31 13:17:42 -070029#include <unordered_map>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070030#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070031#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070032
Andreas Gampe46ee31b2016-12-14 10:11:49 -080033#include "android-base/stringprintf.h"
34
Mathieu Chartierc7853442015-03-27 14:35:38 -070035#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070036#include "art_method-inl.h"
37#include "base/arena_allocator.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080038#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080039#include "base/logging.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070040#include "base/scoped_arena_containers.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010041#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080042#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080043#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010044#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080045#include "base/unix_file/fd_file.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070046#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070047#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080048#include "class_linker-inl.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070049#include "class_loader_utils.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070050#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000051#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080052#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070053#include "dex_file-inl.h"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070054#include "dex_file_loader.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070055#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070056#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070057#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070058#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080059#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000060#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070061#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070062#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070063#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070064#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000065#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070066#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070067#include "handle_scope-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080068#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070069#include "imt_conflict_table.h"
70#include "imtable-inl.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070071#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070072#include "interpreter/interpreter.h"
Andreas Gampec15a2f42017-04-21 12:09:39 -070073#include "java_vm_ext.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080074#include "jit/jit.h"
75#include "jit/jit_code_cache.h"
Calin Juravle33083d62017-01-18 15:29:12 -080076#include "jit/profile_compilation_info.h"
Andreas Gampe08883de2016-11-08 13:20:52 -080077#include "jni_internal.h"
Ian Rogers0571d352011-11-03 19:51:38 -070078#include "leb128.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070079#include "linear_alloc.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000080#include "mirror/call_site.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080081#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070082#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -070083#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080084#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070085#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070086#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +010087#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070088#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080089#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070090#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +010091#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000092#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -070093#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080094#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000095#include "mirror/object-refvisitor-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070096#include "mirror/object_array-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080097#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070098#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080099#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700100#include "mirror/string-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700101#include "native/dalvik_system_DexFile.h"
Steven Morelande431e272017-07-18 16:53:49 -0700102#include "nativehelper/ScopedLocalRef.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700103#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700104#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700105#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700106#include "oat_file_assistant.h"
107#include "oat_file_manager.h"
108#include "object_lock.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800109#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700110#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800111#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700112#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700113#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700114#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700115#include "trace.h"
Andreas Gampe2ff3b972017-06-05 18:14:53 -0700116#include "utf.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700117#include "utils.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100118#include "utils/dex_cache_arrays_layout-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800119#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700120#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700121
122namespace art {
123
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800124using android::base::StringPrintf;
125
Mathieu Chartierc7853442015-03-27 14:35:38 -0700126static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700127static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700128
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700129static void ThrowNoClassDefFoundError(const char* fmt, ...)
130 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700131 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700132static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700133 va_list args;
134 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800135 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000136 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800137 va_end(args);
138}
139
Andreas Gampe99babb62015-11-02 16:20:00 -0800140static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700141 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700142 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700143 StackHandleScope<1> hs(self);
144 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700145 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700146 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700147
148 if (exception_class == nullptr) {
149 // No exc class ~ no <init>-with-string.
150 CHECK(self->IsExceptionPending());
151 self->ClearException();
152 return false;
153 }
154
Vladimir Markoba118822017-06-12 15:41:56 +0100155 ArtMethod* exception_init_method = exception_class->FindConstructor(
156 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700157 return exception_init_method != nullptr;
158}
159
Alex Lightd6251582016-10-31 11:12:30 -0700160static mirror::Object* GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700161 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700162 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
163 if (ext == nullptr) {
164 return nullptr;
165 } else {
166 return ext->GetVerifyError();
167 }
168}
169
170// Helper for ThrowEarlierClassFailure. Throws the stored error.
171static void HandleEarlierVerifyError(Thread* self,
172 ClassLinker* class_linker,
173 ObjPtr<mirror::Class> c)
174 REQUIRES_SHARED(Locks::mutator_lock_) {
175 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800176 DCHECK(obj != nullptr);
177 self->AssertNoPendingException();
178 if (obj->IsClass()) {
179 // Previous error has been stored as class. Create a new exception of that type.
180
181 // It's possible the exception doesn't have a <init>(String).
182 std::string temp;
183 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
184
185 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700186 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800187 } else {
188 self->ThrowNewException(descriptor, nullptr);
189 }
190 } else {
191 // Previous error has been stored as an instance. Just rethrow.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700192 ObjPtr<mirror::Class> throwable_class =
Andreas Gampe99babb62015-11-02 16:20:00 -0800193 self->DecodeJObject(WellKnownClasses::java_lang_Throwable)->AsClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700194 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800195 CHECK(throwable_class->IsAssignableFrom(error_class));
196 self->SetException(obj->AsThrowable());
197 }
198 self->AssertPendingException();
199}
200
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700201void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c, bool wrap_in_no_class_def) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700202 // The class failed to initialize on a previous attempt, so we want to throw
203 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
204 // failed in verification, in which case v2 5.4.1 says we need to re-throw
205 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800206 Runtime* const runtime = Runtime::Current();
207 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700208 std::string extra;
Alex Lightd6251582016-10-31 11:12:30 -0700209 if (GetVerifyError(c) != nullptr) {
210 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
Andreas Gampe369c8512016-01-28 15:31:39 -0800211 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700212 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800213 } else {
214 extra = verify_error->AsThrowable()->Dump();
215 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700216 }
David Sehr709b0702016-10-13 09:12:37 -0700217 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
218 << ": " << extra;
Ian Rogers87e552d2012-08-31 15:54:48 -0700219 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700220
David Sehr709b0702016-10-13 09:12:37 -0700221 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800222 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800223 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700224 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700225 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000226 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700227 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700228 if (GetVerifyError(c) != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800229 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800230 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800231 }
Alex Lightd6251582016-10-31 11:12:30 -0700232 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
233 // might have meant to go down the earlier if statement with the original error but it got
234 // swallowed by the OOM so we end up here.
235 if (GetVerifyError(c) == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800236 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
237 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
238 // exception will be a cause.
239 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700240 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700241 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700242 }
243}
244
Brian Carlstromb23eab12014-10-08 17:55:21 -0700245static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700246 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700247 if (VLOG_IS_ON(class_linker)) {
248 std::string temp;
249 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000250 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700251 }
252}
253
254static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700255 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700256 Thread* self = Thread::Current();
257 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700258
259 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700260 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700261
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800262 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
263 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
264 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800265 std::string tmp;
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800266 LOG(kIsDebugBuild ? FATAL : WARNING) << klass->GetDescriptor(&tmp) << " failed initialization";
Andreas Gampe22f71d22016-11-21 10:10:08 -0800267 }
268
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700269 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700270 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
271 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700272
Elliott Hughesa4f94742012-05-29 16:28:38 -0700273 // We only wrap non-Error exceptions; an Error can just be used as-is.
274 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000275 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700276 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700277 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700278}
279
Fred Shih381e4ca2014-08-25 17:24:27 -0700280// Gap between two fields in object layout.
281struct FieldGap {
282 uint32_t start_offset; // The offset from the start of the object.
283 uint32_t size; // The gap size of 1, 2, or 4 bytes.
284};
285struct FieldGapsComparator {
286 explicit FieldGapsComparator() {
287 }
288 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
289 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800290 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700291 // Note that the priority queue returns the largest element, so operator()
292 // should return true if lhs is less than rhs.
293 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700294 }
295};
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700296typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
Fred Shih381e4ca2014-08-25 17:24:27 -0700297
298// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800299static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700300 DCHECK(gaps != nullptr);
301
302 uint32_t current_offset = gap_start;
303 while (current_offset != gap_end) {
304 size_t remaining = gap_end - current_offset;
305 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
306 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
307 current_offset += sizeof(uint32_t);
308 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
309 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
310 current_offset += sizeof(uint16_t);
311 } else {
312 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
313 current_offset += sizeof(uint8_t);
314 }
315 DCHECK_LE(current_offset, gap_end) << "Overran gap";
316 }
317}
318// Shuffle fields forward, making use of gaps whenever possible.
319template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000320static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700321 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700322 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700323 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700324 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700325 DCHECK(current_field_idx != nullptr);
326 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700327 DCHECK(gaps != nullptr);
328 DCHECK(field_offset != nullptr);
329
330 DCHECK(IsPowerOfTwo(n));
331 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700332 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700333 Primitive::Type type = field->GetTypeAsPrimitiveType();
334 if (Primitive::ComponentSize(type) < n) {
335 break;
336 }
337 if (!IsAligned<n>(field_offset->Uint32Value())) {
338 MemberOffset old_offset = *field_offset;
339 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
340 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
341 }
David Sehr709b0702016-10-13 09:12:37 -0700342 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700343 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700344 if (!gaps->empty() && gaps->top().size >= n) {
345 FieldGap gap = gaps->top();
346 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100347 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700348 field->SetOffset(MemberOffset(gap.start_offset));
349 if (gap.size > n) {
350 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
351 }
352 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100353 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700354 field->SetOffset(*field_offset);
355 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
356 }
357 ++(*current_field_idx);
358 }
359}
360
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800361ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampe2af99022017-04-25 08:32:59 -0700362 : boot_class_table_(new ClassTable()),
363 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800364 class_roots_(nullptr),
365 array_iftable_(nullptr),
366 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700367 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000368 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700369 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800370 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800371 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100372 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800373 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700374 image_pointer_size_(kRuntimePointerSize),
Andreas Gampe7dface32017-07-25 21:32:59 -0700375 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
376 // For CHA disabled during Aot, see b/34193647.
377
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700378 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700379 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
380 "Array cache size wrong.");
381 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700382}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700383
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800384void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700385 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800386 if (c2 == nullptr) {
387 LOG(FATAL) << "Could not find class " << descriptor;
388 UNREACHABLE();
389 }
390 if (c1.Get() != c2) {
391 std::ostringstream os1, os2;
392 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
393 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
394 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
395 << ". This is most likely the result of a broken build. Make sure that "
396 << "libcore and art projects match.\n\n"
397 << os1.str() << "\n\n" << os2.str();
398 UNREACHABLE();
399 }
400}
401
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800402bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
403 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800404 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700405
Mathieu Chartiere401d142015-04-22 13:56:20 -0700406 Thread* const self = Thread::Current();
407 Runtime* const runtime = Runtime::Current();
408 gc::Heap* const heap = runtime->GetHeap();
409
Jeff Haodcdc85b2015-12-04 14:06:18 -0800410 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700411 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700412
Mathieu Chartiere401d142015-04-22 13:56:20 -0700413 // Use the pointer size from the runtime since we are probably creating the image.
414 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
415
Elliott Hughes30646832011-10-13 16:59:46 -0700416 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700417 // 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 -0800418 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700419 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700420 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700421 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700422 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800423 CHECK(java_lang_Class != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700424 mirror::Class::SetClassClass(java_lang_Class.Get());
425 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700426 if (kUseBakerReadBarrier) {
427 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800428 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700429 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700430 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800431 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700432 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700433
Elliott Hughes418d20f2011-09-22 14:00:39 -0700434 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700435 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700436 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700437 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700438 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700439
Ian Rogers23435d02012-09-24 11:23:12 -0700440 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700441 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700442 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800443 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700444 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700445 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700446 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700447
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700448 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800449 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
450 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
451 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
452 java_lang_Object.Get(),
453 java_lang_Object->GetObjectSize(),
454 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700455
Ian Rogers23435d02012-09-24 11:23:12 -0700456 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700457 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700458 AllocClass(self, java_lang_Class.Get(),
459 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700460 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700461
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700462 // Setup the char (primitive) class to be used for char[].
463 Handle<mirror::Class> char_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700464 AllocClass(self, java_lang_Class.Get(),
465 mirror::Class::PrimitiveClassSize(image_pointer_size_))));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700466 // The primitive char class won't be initialized by
467 // InitializePrimitiveClass until line 459, but strings (and
468 // internal char arrays) will be allocated before that and the
469 // component size, which is computed from the primitive type, needs
470 // to be set here.
471 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700472
Ian Rogers23435d02012-09-24 11:23:12 -0700473 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700474 Handle<mirror::Class> char_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700475 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700476 char_array_class->SetComponentType(char_class.Get());
477 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700478
Ian Rogers23435d02012-09-24 11:23:12 -0700479 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700480 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700481 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700482 java_lang_String->SetStringClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700483 mirror::String::SetClass(java_lang_String.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700484 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400485
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700486 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700487 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700488 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700489 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
490 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700491 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700492
Ian Rogers23435d02012-09-24 11:23:12 -0700493 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700494 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700495 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
496 kClassRootsMax));
497 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700498 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
499 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
500 SetClassRoot(kClassArrayClass, class_array_class.Get());
501 SetClassRoot(kObjectArrayClass, object_array_class.Get());
502 SetClassRoot(kCharArrayClass, char_array_class.Get());
503 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700504 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700505
Mathieu Chartier6beced42016-11-15 15:51:31 -0800506 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
507 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
508
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700509 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700510 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
511 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
512 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
513 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
514 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
515 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
516 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
517 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700518
Ian Rogers23435d02012-09-24 11:23:12 -0700519 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700520 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700521
Ian Rogers23435d02012-09-24 11:23:12 -0700522 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700523 Handle<mirror::Class> int_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700524 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700525 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700526 mirror::IntArray::SetArrayClass(int_array_class.Get());
527 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700528
Mathieu Chartierc7853442015-03-27 14:35:38 -0700529 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
530 Handle<mirror::Class> long_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700531 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700532 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
533 mirror::LongArray::SetArrayClass(long_array_class.Get());
534 SetClassRoot(kLongArrayClass, long_array_class.Get());
535
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700536 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700537
Ian Rogers52813c92012-10-11 11:50:38 -0700538 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700539 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700540 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700541 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100542 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700543 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700544 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700545
Alex Lightd6251582016-10-31 11:12:30 -0700546
547 // Setup dalvik.system.ClassExt
548 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
549 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
550 SetClassRoot(kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
551 mirror::ClassExt::SetClass(dalvik_system_ClassExt.Get());
552 mirror::Class::SetStatus(dalvik_system_ClassExt, mirror::Class::kStatusResolved, self);
553
Mathieu Chartier66f19252012-09-18 08:57:04 -0700554 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700555 Handle<mirror::Class> object_array_string(hs.NewHandle(
556 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700557 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700558 object_array_string->SetComponentType(java_lang_String.Get());
559 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700560
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000561 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700562 // Create runtime resolution and imt conflict methods.
563 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000564 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
565 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700566
Ian Rogers23435d02012-09-24 11:23:12 -0700567 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
568 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
569 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800570 if (boot_class_path.empty()) {
571 *error_msg = "Boot classpath is empty.";
572 return false;
573 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800574 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800575 if (dex_file.get() == nullptr) {
576 *error_msg = "Null dex file.";
577 return false;
578 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700579 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800580 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700581 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700582
583 // now we can use FindSystemClass
584
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700585 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700586 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
587 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700588
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700589 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
590 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700591 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800592 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700593 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700594 quick_resolution_trampoline_ = GetQuickResolutionStub();
595 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
596 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700597 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700598
Alex Lightd6251582016-10-31 11:12:30 -0700599 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700600 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800601 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700602 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700603 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800604 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700605 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800606 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700607 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Alex Lightd6251582016-10-31 11:12:30 -0700608 mirror::Class::SetStatus(dalvik_system_ClassExt, mirror::Class::kStatusNotReady, self);
609 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
610 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700611
Ian Rogers23435d02012-09-24 11:23:12 -0700612 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800613 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800614 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700615
Ian Rogers98379392014-02-24 16:53:16 -0800616 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800617 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700618
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800619 CheckSystemClass(self, char_array_class, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700620
Ian Rogers98379392014-02-24 16:53:16 -0800621 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800622 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700623
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800624 CheckSystemClass(self, int_array_class, "[I");
625 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700626
Ian Rogers98379392014-02-24 16:53:16 -0800627 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800628 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700629
Ian Rogers98379392014-02-24 16:53:16 -0800630 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800631 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700632
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800633 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
634 // in class_table_.
635 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700636
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800637 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
638 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700639
Ian Rogers23435d02012-09-24 11:23:12 -0700640 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700641 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800642 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700643 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800644 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700645 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
646 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700647 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
648 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700649
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700650 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
651 // suspension.
652 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000653 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700654 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000655 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700656 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000657 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700658 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000659 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700660
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700661 CHECK_EQ(object_array_string.Get(),
662 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700663
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800664 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700665
Ian Rogers23435d02012-09-24 11:23:12 -0700666 // Create java.lang.reflect.Proxy root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700667 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700668
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700669 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700670 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
671 CHECK(class_root != nullptr);
672 SetClassRoot(kJavaLangReflectField, class_root);
673 mirror::Field::SetClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700674
675 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700676 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
677 CHECK(class_root != nullptr);
678 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
679 mirror::Field::SetArrayClass(class_root);
680
681 // Create java.lang.reflect.Constructor.class root and array root.
682 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
683 CHECK(class_root != nullptr);
684 SetClassRoot(kJavaLangReflectConstructor, class_root);
685 mirror::Constructor::SetClass(class_root);
686 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
687 CHECK(class_root != nullptr);
688 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
689 mirror::Constructor::SetArrayClass(class_root);
690
691 // Create java.lang.reflect.Method.class root and array root.
692 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
693 CHECK(class_root != nullptr);
694 SetClassRoot(kJavaLangReflectMethod, class_root);
695 mirror::Method::SetClass(class_root);
696 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
697 CHECK(class_root != nullptr);
698 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
699 mirror::Method::SetArrayClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700700
Narayan Kamathafa48272016-08-03 12:46:58 +0100701 // Create java.lang.invoke.MethodType.class root
702 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
703 CHECK(class_root != nullptr);
704 SetClassRoot(kJavaLangInvokeMethodType, class_root);
705 mirror::MethodType::SetClass(class_root);
706
707 // Create java.lang.invoke.MethodHandleImpl.class root
708 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
709 CHECK(class_root != nullptr);
710 SetClassRoot(kJavaLangInvokeMethodHandleImpl, class_root);
711 mirror::MethodHandleImpl::SetClass(class_root);
712
Orion Hodsonc069a302017-01-18 09:23:12 +0000713 // Create java.lang.invoke.MethodHandles.Lookup.class root
714 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
715 CHECK(class_root != nullptr);
716 SetClassRoot(kJavaLangInvokeMethodHandlesLookup, class_root);
717 mirror::MethodHandlesLookup::SetClass(class_root);
718
719 // Create java.lang.invoke.CallSite.class root
720 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
721 CHECK(class_root != nullptr);
722 SetClassRoot(kJavaLangInvokeCallSite, class_root);
723 mirror::CallSite::SetClass(class_root);
724
Narayan Kamath000e1882016-10-24 17:14:25 +0100725 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
726 CHECK(class_root != nullptr);
727 SetClassRoot(kDalvikSystemEmulatedStackFrame, class_root);
728 mirror::EmulatedStackFrame::SetClass(class_root);
729
Brian Carlstrom1f870082011-08-23 16:02:11 -0700730 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700731 // finish initializing Reference class
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700732 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800733 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700734 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700735 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
736 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700737 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700738 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700739 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700740 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700741 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700742 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700743 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700744 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700745 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700746 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700747 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700748 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700749
Ian Rogers23435d02012-09-24 11:23:12 -0700750 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700751 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700752 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700753 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
754 SetClassRoot(kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700755
jeffhao8cd6dda2012-02-22 10:15:34 -0800756 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700757 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800758 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800759 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700760 SetClassRoot(kJavaLangClassNotFoundException,
761 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800762 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700763 SetClassRoot(kJavaLangStackTraceElementArrayClass,
764 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800765 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700766
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700767 // Create conflict tables that depend on the class linker.
768 runtime->FixupConflictTables();
769
Ian Rogers98379392014-02-24 16:53:16 -0800770 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700771
Brian Carlstroma004aa92012-02-08 18:05:09 -0800772 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800773
774 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700775}
776
Ian Rogers98379392014-02-24 16:53:16 -0800777void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800778 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700779
780 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700781 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700782 // as the types of the field can't be resolved prior to the runtime being
783 // fully initialized
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700784 StackHandleScope<2> hs(self);
785 Handle<mirror::Class> java_lang_ref_Reference = hs.NewHandle(GetClassRoot(kJavaLangRefReference));
786 Handle<mirror::Class> java_lang_ref_FinalizerReference =
787 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800788
Mathieu Chartierc7853442015-03-27 14:35:38 -0700789 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700790 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
791 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700792
Mathieu Chartierc7853442015-03-27 14:35:38 -0700793 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700794 CHECK_STREQ(queue->GetName(), "queue");
795 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700796
Mathieu Chartierc7853442015-03-27 14:35:38 -0700797 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700798 CHECK_STREQ(queueNext->GetName(), "queueNext");
799 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700800
Mathieu Chartierc7853442015-03-27 14:35:38 -0700801 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700802 CHECK_STREQ(referent->GetName(), "referent");
803 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700804
Mathieu Chartierc7853442015-03-27 14:35:38 -0700805 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700806 CHECK_STREQ(zombie->GetName(), "zombie");
807 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700808
Brian Carlstroma663ea52011-08-19 23:33:41 -0700809 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700810 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700811 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700812 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700813 CHECK(klass != nullptr);
814 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700815 // note SetClassRoot does additional validation.
816 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700817 }
818
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700819 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700820
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700821 // disable the slow paths in FindClass and CreatePrimitiveClass now
822 // that Object, Class, and Object[] are setup
823 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700824
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800825 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700826}
827
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700828void ClassLinker::RunRootClinits() {
829 Thread* self = Thread::Current();
830 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700831 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700832 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700833 StackHandleScope<1> hs(self);
834 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700835 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700836 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700837 }
838 }
839}
840
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200841// Set image methods' entry point to interpreter.
842class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
843 public:
Andreas Gampe542451c2016-07-26 09:02:02 -0700844 explicit SetInterpreterEntrypointArtMethodVisitor(PointerSize image_pointer_size)
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200845 : image_pointer_size_(image_pointer_size) {}
846
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700847 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200848 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
849 CHECK(method->GetDeclaringClass() != nullptr);
850 }
851 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
852 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
853 image_pointer_size_);
854 }
855 }
856
857 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700858 const PointerSize image_pointer_size_;
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200859
860 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
861};
862
Jeff Haodcdc85b2015-12-04 14:06:18 -0800863struct TrampolineCheckData {
864 const void* quick_resolution_trampoline;
865 const void* quick_imt_conflict_trampoline;
866 const void* quick_generic_jni_trampoline;
867 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700868 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800869 ArtMethod* m;
870 bool error;
871};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800872
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800873bool ClassLinker::InitFromBootImage(std::string* error_msg) {
874 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700875 CHECK(!init_done_);
876
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700877 Runtime* const runtime = Runtime::Current();
878 Thread* const self = Thread::Current();
879 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800880 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
881 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700882 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
883 if (!ValidPointerSize(pointer_size_unchecked)) {
884 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800885 return false;
886 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700887 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800888 if (!runtime->IsAotCompiler()) {
889 // Only the Aot compiler supports having an image with a different pointer size than the
890 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
891 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700892 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800893 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700894 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800895 sizeof(void*));
896 return false;
897 }
898 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800899 std::vector<const OatFile*> oat_files =
900 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
901 DCHECK(!oat_files.empty());
902 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800903 CHECK_EQ(default_oat_header.GetImageFileLocationOatDataBegin(), 0U);
904 const char* image_file_location = oat_files[0]->GetOatHeader().
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700905 GetStoreValueByKey(OatHeader::kImageLocationKey);
906 CHECK(image_file_location == nullptr || *image_file_location == 0);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800907 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
908 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
909 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
910 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
911 if (kIsDebugBuild) {
912 // Check that the other images use the same trampoline.
913 for (size_t i = 1; i < oat_files.size(); ++i) {
914 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
915 const void* ith_quick_resolution_trampoline =
916 ith_oat_header.GetQuickResolutionTrampoline();
917 const void* ith_quick_imt_conflict_trampoline =
918 ith_oat_header.GetQuickImtConflictTrampoline();
919 const void* ith_quick_generic_jni_trampoline =
920 ith_oat_header.GetQuickGenericJniTrampoline();
921 const void* ith_quick_to_interpreter_bridge_trampoline =
922 ith_oat_header.GetQuickToInterpreterBridge();
923 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
924 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
925 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
926 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
927 // Make sure that all methods in this image do not contain those trampolines as
928 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
929 TrampolineCheckData data;
930 data.error = false;
931 data.pointer_size = GetImagePointerSize();
932 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
933 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
934 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
935 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
936 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700937 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
938 if (obj->IsClass()) {
939 ObjPtr<mirror::Class> klass = obj->AsClass();
940 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
941 const void* entrypoint =
942 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
943 if (entrypoint == data.quick_resolution_trampoline ||
944 entrypoint == data.quick_imt_conflict_trampoline ||
945 entrypoint == data.quick_generic_jni_trampoline ||
946 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
947 data.m = &m;
948 data.error = true;
949 return;
950 }
951 }
952 }
953 };
954 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800955 if (data.error) {
956 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -0700957 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800958 *error_msg = "Found an ArtMethod with a bad entrypoint";
959 return false;
960 }
961 }
962 }
963 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700964
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800965 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
966 down_cast<mirror::ObjectArray<mirror::Class>*>(
967 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)));
968 mirror::Class::SetClassClass(class_roots_.Read()->Get(kJavaLangClass));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700969
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700970 // Special case of setting up the String class early so that we can test arbitrary objects
971 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700972 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800973
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700974 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot(kJavaLangObject);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700975 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800976 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
977 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800978 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
979 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700980
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800981 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700982 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800983 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800984 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700985 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
986 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700987 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
988 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
989 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
990 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
Narayan Kamathafa48272016-08-03 12:46:58 +0100991 mirror::MethodType::SetClass(GetClassRoot(kJavaLangInvokeMethodType));
992 mirror::MethodHandleImpl::SetClass(GetClassRoot(kJavaLangInvokeMethodHandleImpl));
Orion Hodsonc069a302017-01-18 09:23:12 +0000993 mirror::MethodHandlesLookup::SetClass(GetClassRoot(kJavaLangInvokeMethodHandlesLookup));
994 mirror::CallSite::SetClass(GetClassRoot(kJavaLangInvokeCallSite));
Fred Shih4ee7a662014-07-11 09:59:27 -0700995 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800996 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
997 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
998 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
999 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1000 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1001 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1002 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1003 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1004 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1005 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Narayan Kamath000e1882016-10-24 17:14:25 +01001006 mirror::EmulatedStackFrame::SetClass(GetClassRoot(kDalvikSystemEmulatedStackFrame));
Alex Lightd6251582016-10-31 11:12:30 -07001007 mirror::ClassExt::SetClass(GetClassRoot(kDalvikSystemClassExt));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001008
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001009 for (gc::space::ImageSpace* image_space : spaces) {
1010 // Boot class loader, use a null handle.
1011 std::vector<std::unique_ptr<const DexFile>> dex_files;
1012 if (!AddImageSpace(image_space,
1013 ScopedNullHandle<mirror::ClassLoader>(),
1014 /*dex_elements*/nullptr,
1015 /*dex_location*/nullptr,
1016 /*out*/&dex_files,
1017 error_msg)) {
1018 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001019 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001020 // Append opened dex files at the end.
1021 boot_dex_files_.insert(boot_dex_files_.end(),
1022 std::make_move_iterator(dex_files.begin()),
1023 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001024 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001025 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1026 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1027 }
Ian Rogers98379392014-02-24 16:53:16 -08001028 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001029
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001030 VLOG(startup) << __FUNCTION__ << " exiting";
1031 return true;
1032}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001033
Jeff Hao5872d7c2016-04-27 11:07:41 -07001034bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001035 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001036 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001037 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1038 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001039}
1040
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001041static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1042 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001043 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001044 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001045 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001046 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001047 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001048 DCHECK(dex_file_field != nullptr);
1049 DCHECK(dex_file_name_field != nullptr);
1050 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001051 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001052 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001053 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001054 // Null dex file means it was probably a jar with no dex files, return a null string.
1055 *out_name = nullptr;
1056 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001057 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001058 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001059 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001060 *out_name = name_object->AsString();
1061 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001062 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001063 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001064}
1065
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001066static bool FlattenPathClassLoader(ObjPtr<mirror::ClassLoader> class_loader,
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001067 std::list<ObjPtr<mirror::String>>* out_dex_file_names,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001068 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001069 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001070 DCHECK(out_dex_file_names != nullptr);
1071 DCHECK(error_msg != nullptr);
1072 ScopedObjectAccessUnchecked soa(Thread::Current());
1073 ArtField* const dex_path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001074 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001075 ArtField* const dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001076 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001077 CHECK(dex_path_list_field != nullptr);
1078 CHECK(dex_elements_field != nullptr);
Jeff Hao5872d7c2016-04-27 11:07:41 -07001079 while (!ClassLinker::IsBootClassLoader(soa, class_loader)) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07001080 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1081 class_loader->GetClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001082 *error_msg = StringPrintf("Unknown class loader type %s",
1083 class_loader->PrettyTypeOf().c_str());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001084 // Unsupported class loader.
1085 return false;
1086 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001087 ObjPtr<mirror::Object> dex_path_list = dex_path_list_field->GetObject(class_loader);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001088 if (dex_path_list != nullptr) {
1089 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
Mathieu Chartier3398c782016-09-30 10:27:43 -07001090 ObjPtr<mirror::Object> dex_elements_obj = dex_elements_field->GetObject(dex_path_list);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001091 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1092 // at the mCookie which is a DexFile vector.
1093 if (dex_elements_obj != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001094 ObjPtr<mirror::ObjectArray<mirror::Object>> dex_elements =
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001095 dex_elements_obj->AsObjectArray<mirror::Object>();
1096 // Reverse order since we insert the parent at the front.
1097 for (int32_t i = dex_elements->GetLength() - 1; i >= 0; --i) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001098 ObjPtr<mirror::Object> element = dex_elements->GetWithoutChecks(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001099 if (element == nullptr) {
1100 *error_msg = StringPrintf("Null dex element at index %d", i);
1101 return false;
1102 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001103 ObjPtr<mirror::String> name;
1104 if (!GetDexPathListElementName(element, &name)) {
1105 *error_msg = StringPrintf("Invalid dex path list element at index %d", i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001106 return false;
1107 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001108 if (name != nullptr) {
1109 out_dex_file_names->push_front(name.Ptr());
1110 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001111 }
1112 }
1113 }
1114 class_loader = class_loader->GetParent();
1115 }
1116 return true;
1117}
1118
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001119class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1120 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001121 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001122 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1123
1124 virtual void Visit(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001125 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001126 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked();
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001127 if (klass != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001128 CHECK(live_bitmap_->Test(klass.Ptr())) << "Image method has unmarked declaring class";
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001129 }
1130 }
1131
1132 private:
1133 gc::accounting::HeapBitmap* const live_bitmap_;
1134};
1135
Chang Xingba17dbd2017-06-28 21:27:56 +00001136class FixupInternVisitor {
1137 public:
1138 ALWAYS_INLINE ObjPtr<mirror::Object> TryInsertIntern(mirror::Object* obj) const
1139 REQUIRES_SHARED(Locks::mutator_lock_) {
1140 if (obj != nullptr && obj->IsString()) {
1141 const auto intern = Runtime::Current()->GetInternTable()->InternStrong(obj->AsString());
1142 return intern;
1143 }
1144 return obj;
1145 }
1146
1147 ALWAYS_INLINE void VisitRootIfNonNull(
1148 mirror::CompressedReference<mirror::Object>* root) const
1149 REQUIRES_SHARED(Locks::mutator_lock_) {
1150 if (!root->IsNull()) {
1151 VisitRoot(root);
1152 }
1153 }
1154
1155 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1156 REQUIRES_SHARED(Locks::mutator_lock_) {
1157 root->Assign(TryInsertIntern(root->AsMirrorPtr()));
1158 }
1159
1160 // Visit Class Fields
1161 ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
1162 MemberOffset offset,
1163 bool is_static ATTRIBUTE_UNUSED) const
1164 REQUIRES_SHARED(Locks::mutator_lock_) {
1165 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1166 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1167 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1168 // Updating images, don't do a read barrier.
1169 // Only string fields are fixed, don't do a verify.
1170 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
1171 offset);
1172 obj->SetFieldObject<false, false>(offset, TryInsertIntern(ref));
1173 }
1174 }
1175
1176 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1177 ObjPtr<mirror::Reference> ref) const
1178 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1179 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1180 }
1181
1182 void operator()(mirror::Object* obj) const
1183 REQUIRES_SHARED(Locks::mutator_lock_) {
1184 if (obj->IsDexCache()) {
1185 obj->VisitReferences<true, kVerifyNone, kWithoutReadBarrier>(*this, *this);
1186 } else {
1187 // Don't visit native roots for non-dex-cache
1188 obj->VisitReferences<false, kVerifyNone, kWithoutReadBarrier>(*this, *this);
1189 }
1190 }
1191};
1192
Andreas Gampe2af99022017-04-25 08:32:59 -07001193// new_class_set is the set of classes that were read from the class table section in the image.
1194// If there was no class table section, it is null.
1195// Note: using a class here to avoid having to make ClassLinker internals public.
1196class AppImageClassLoadersAndDexCachesHelper {
1197 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001198 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001199 ClassLinker* class_linker,
1200 gc::space::ImageSpace* space,
1201 Handle<mirror::ClassLoader> class_loader,
1202 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001203 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001204 REQUIRES(!Locks::dex_lock_)
1205 REQUIRES_SHARED(Locks::mutator_lock_);
1206};
1207
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001208void AppImageClassLoadersAndDexCachesHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001209 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001210 gc::space::ImageSpace* space,
1211 Handle<mirror::ClassLoader> class_loader,
1212 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001213 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001214 REQUIRES(!Locks::dex_lock_)
1215 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001216 Thread* const self = Thread::Current();
1217 gc::Heap* const heap = Runtime::Current()->GetHeap();
1218 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001219 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001220 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001221 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001222 const size_t num_dex_caches = dex_caches->GetLength();
1223 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001224 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001225 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001226 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001227 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001228 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1229 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001230 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001231 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001232 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001233 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001234 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001235 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001236 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001237 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001238 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001239 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001240 auto it = new_class_set->Find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001241 DCHECK(it != new_class_set->end());
1242 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001243 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001244 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001245 auto it2 = new_class_set->Find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001246 DCHECK(it2 != new_class_set->end());
1247 DCHECK_EQ(it2->Read(), super_class);
1248 }
1249 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1250 const void* code = m.GetEntryPointFromQuickCompiledCode();
Andreas Gampe2af99022017-04-25 08:32:59 -07001251 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1252 if (!class_linker->IsQuickResolutionStub(code) &&
1253 !class_linker->IsQuickGenericJniStub(code) &&
1254 !class_linker->IsQuickToInterpreterBridge(code) &&
Vladimir Marko1a1de672016-10-13 12:53:15 +01001255 !m.IsNative()) {
David Sehr709b0702016-10-13 09:12:37 -07001256 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001257 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001258 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01001259 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1260 const void* code = m.GetEntryPointFromQuickCompiledCode();
Andreas Gampe2af99022017-04-25 08:32:59 -07001261 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1262 if (!class_linker->IsQuickResolutionStub(code) &&
1263 !class_linker->IsQuickGenericJniStub(code) &&
1264 !class_linker->IsQuickToInterpreterBridge(code) &&
Vladimir Marko1a1de672016-10-13 12:53:15 +01001265 !m.IsNative()) {
David Sehr709b0702016-10-13 09:12:37 -07001266 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001267 }
1268 }
1269 }
1270 }
1271 }
1272 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001273 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001274 {
1275 // Fixup all the literal strings happens at app images which are supposed to be interned.
1276 ScopedTrace timing("Fixup String Intern in image and dex_cache");
1277 const auto& image_header = space->GetImageHeader();
1278 const auto bitmap = space->GetMarkBitmap(); // bitmap of objects
1279 const uint8_t* target_base = space->GetMemMap()->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001280 const ImageSection& objects_section = image_header.GetObjectsSection();
Chang Xingba17dbd2017-06-28 21:27:56 +00001281
1282 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1283 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1284
1285 FixupInternVisitor fixup_intern_visitor;
1286 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_intern_visitor);
1287 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001288 if (kVerifyArtMethodDeclaringClasses) {
1289 ScopedTrace timing("Verify declaring classes");
1290 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1291 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001292 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001293 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001294}
1295
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001296// Update the class loader. Should only be used on classes in the image space.
1297class UpdateClassLoaderVisitor {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001298 public:
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001299 UpdateClassLoaderVisitor(gc::space::ImageSpace* space, ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001300 : space_(space),
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001301 class_loader_(class_loader) {}
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001302
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001303 bool operator()(ObjPtr<mirror::Class> klass) const REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001304 // Do not update class loader for boot image classes where the app image
1305 // class loader is only the initiating loader but not the defining loader.
1306 if (klass->GetClassLoader() != nullptr) {
1307 klass->SetClassLoader(class_loader_);
1308 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001309 return true;
1310 }
1311
1312 gc::space::ImageSpace* const space_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001313 ObjPtr<mirror::ClassLoader> const class_loader_;
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001314};
1315
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001316static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1317 const char* location,
1318 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001319 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001320 DCHECK(error_msg != nullptr);
1321 std::unique_ptr<const DexFile> dex_file;
Richard Uhler9a37efc2016-08-05 16:32:55 -07001322 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001323 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001324 return std::unique_ptr<const DexFile>();
1325 }
1326 std::string inner_error_msg;
1327 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1328 if (dex_file == nullptr) {
1329 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1330 location,
1331 oat_file->GetLocation().c_str(),
1332 inner_error_msg.c_str());
1333 return std::unique_ptr<const DexFile>();
1334 }
1335
1336 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1337 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1338 location,
1339 dex_file->GetLocationChecksum(),
1340 oat_dex_file->GetDexFileLocationChecksum());
1341 return std::unique_ptr<const DexFile>();
1342 }
1343 return dex_file;
1344}
1345
1346bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1347 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1348 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001349 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001350 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001351 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001352 DCHECK(dex_caches_object != nullptr);
1353 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1354 dex_caches_object->AsObjectArray<mirror::DexCache>();
1355 const OatFile* oat_file = space->GetOatFile();
1356 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001357 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001358 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1359 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1360 dex_file_location.c_str(),
1361 error_msg);
1362 if (dex_file == nullptr) {
1363 return false;
1364 }
1365 dex_cache->SetDexFile(dex_file.get());
1366 out_dex_files->push_back(std::move(dex_file));
1367 }
1368 return true;
1369}
1370
Andreas Gampe0793bec2016-12-01 11:37:33 -08001371// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1372// together and caches some intermediate results.
1373class ImageSanityChecks FINAL {
1374 public:
1375 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1376 REQUIRES_SHARED(Locks::mutator_lock_) {
1377 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001378 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1379 DCHECK(obj != nullptr);
1380 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1381 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1382 if (obj->IsClass()) {
1383 auto klass = obj->AsClass();
1384 for (ArtField& field : klass->GetIFields()) {
1385 CHECK_EQ(field.GetDeclaringClass(), klass);
1386 }
1387 for (ArtField& field : klass->GetSFields()) {
1388 CHECK_EQ(field.GetDeclaringClass(), klass);
1389 }
1390 const auto pointer_size = isc.pointer_size_;
1391 for (auto& m : klass->GetMethods(pointer_size)) {
1392 isc.SanityCheckArtMethod(&m, klass);
1393 }
1394 auto* vtable = klass->GetVTable();
1395 if (vtable != nullptr) {
1396 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1397 }
1398 if (klass->ShouldHaveImt()) {
1399 ImTable* imt = klass->GetImt(pointer_size);
1400 for (size_t i = 0; i < ImTable::kSize; ++i) {
1401 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1402 }
1403 }
1404 if (klass->ShouldHaveEmbeddedVTable()) {
1405 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1406 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1407 }
1408 }
1409 mirror::IfTable* iftable = klass->GetIfTable();
1410 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1411 if (iftable->GetMethodArrayCount(i) > 0) {
1412 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1413 }
1414 }
1415 }
1416 };
1417 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001418 }
1419
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001420 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1421 ClassLinker* class_linker,
1422 mirror::MethodDexCacheType* arr,
1423 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001424 REQUIRES_SHARED(Locks::mutator_lock_) {
1425 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001426 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001427 }
1428
Andreas Gampe0793bec2016-12-01 11:37:33 -08001429 private:
1430 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1431 : spaces_(heap->GetBootImageSpaces()),
1432 pointer_size_(class_linker->GetImagePointerSize()) {
1433 space_begin_.reserve(spaces_.size());
1434 method_sections_.reserve(spaces_.size());
1435 runtime_method_sections_.reserve(spaces_.size());
1436 for (gc::space::ImageSpace* space : spaces_) {
1437 space_begin_.push_back(space->Begin());
1438 auto& header = space->GetImageHeader();
1439 method_sections_.push_back(&header.GetMethodsSection());
1440 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1441 }
1442 }
1443
1444 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1445 REQUIRES_SHARED(Locks::mutator_lock_) {
1446 if (m->IsRuntimeMethod()) {
1447 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1448 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1449 } else if (m->IsCopied()) {
1450 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1451 } else if (expected_class != nullptr) {
1452 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1453 }
1454 if (!spaces_.empty()) {
1455 bool contains = false;
1456 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1457 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1458 contains = method_sections_[i]->Contains(offset) ||
1459 runtime_method_sections_[i]->Contains(offset);
1460 }
1461 CHECK(contains) << m << " not found";
1462 }
1463 }
1464
1465 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1466 ObjPtr<mirror::Class> expected_class)
1467 REQUIRES_SHARED(Locks::mutator_lock_) {
1468 CHECK(arr != nullptr);
1469 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1470 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1471 // expected_class == null means we are a dex cache.
1472 if (expected_class != nullptr) {
1473 CHECK(method != nullptr);
1474 }
1475 if (method != nullptr) {
1476 SanityCheckArtMethod(method, expected_class);
1477 }
1478 }
1479 }
1480
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001481 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001482 REQUIRES_SHARED(Locks::mutator_lock_) {
1483 CHECK_EQ(arr != nullptr, size != 0u);
1484 if (arr != nullptr) {
1485 bool contains = false;
1486 for (auto space : spaces_) {
1487 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001488 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001489 contains = true;
1490 break;
1491 }
1492 }
1493 CHECK(contains);
1494 }
1495 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001496 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1497 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001498 // expected_class == null means we are a dex cache.
1499 if (method != nullptr) {
1500 SanityCheckArtMethod(method, nullptr);
1501 }
1502 }
1503 }
1504
1505 const std::vector<gc::space::ImageSpace*>& spaces_;
1506 const PointerSize pointer_size_;
1507
1508 // Cached sections from the spaces.
1509 std::vector<const uint8_t*> space_begin_;
1510 std::vector<const ImageSection*> method_sections_;
1511 std::vector<const ImageSection*> runtime_method_sections_;
1512};
1513
Andreas Gampebe7af222017-07-25 09:57:28 -07001514static void VerifyAppImage(const ImageHeader& header,
1515 const Handle<mirror::ClassLoader>& class_loader,
1516 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1517 ClassTable* class_table, gc::space::ImageSpace* space)
1518 REQUIRES_SHARED(Locks::mutator_lock_) {
1519 {
1520 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1521 public:
1522 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1523
1524 virtual void Visit(ArtMethod* method)
1525 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
1526 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1527 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1528 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << mirror::Class::PrettyClass(klass);
1529 }
1530 }
1531
1532 private:
1533 ClassTable* const table_;
1534 };
1535 VerifyClassInTableArtMethodVisitor visitor(class_table);
1536 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
1537 }
1538 {
1539 // Verify that all direct interfaces of classes in the class table are also resolved.
1540 std::vector<ObjPtr<mirror::Class>> classes;
1541 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1542 REQUIRES_SHARED(Locks::mutator_lock_) {
1543 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1544 classes.push_back(klass);
1545 }
1546 return true;
1547 };
1548 class_table->Visit(verify_direct_interfaces_in_table);
1549 Thread* self = Thread::Current();
1550 for (ObjPtr<mirror::Class> klass : classes) {
1551 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1552 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1553 << klass->PrettyDescriptor() << " iface #" << i;
1554 }
1555 }
1556 }
1557 // Check that all non-primitive classes in dex caches are also in the class table.
1558 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1559 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1560 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1561 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1562 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1563 if (klass != nullptr && !klass->IsPrimitive()) {
1564 CHECK(class_table->Contains(klass))
1565 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1566 }
1567 }
1568 }
1569}
1570
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001571bool ClassLinker::AddImageSpace(
1572 gc::space::ImageSpace* space,
1573 Handle<mirror::ClassLoader> class_loader,
1574 jobjectArray dex_elements,
1575 const char* dex_location,
1576 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1577 std::string* error_msg) {
1578 DCHECK(out_dex_files != nullptr);
1579 DCHECK(error_msg != nullptr);
1580 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001581 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001582 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001583 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001584 DCHECK(dex_caches_object != nullptr);
1585 Runtime* const runtime = Runtime::Current();
1586 gc::Heap* const heap = runtime->GetHeap();
1587 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001588 // Check that the image is what we are expecting.
1589 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1590 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1591 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1592 image_pointer_size_);
1593 return false;
1594 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001595 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1596 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1597 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1598 expected_image_roots,
1599 header.GetImageRoots()->GetLength());
1600 return false;
1601 }
1602 StackHandleScope<3> hs(self);
1603 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1604 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1605 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1606 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
1607 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1608 "Class loader should be the last image root.");
1609 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
1610 app_image ? header.GetImageRoot(ImageHeader::kClassLoader)->AsClassLoader() : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001611 DCHECK(class_roots != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001612 if (class_roots->GetLength() != static_cast<int32_t>(kClassRootsMax)) {
1613 *error_msg = StringPrintf("Expected %d class roots but got %d",
1614 class_roots->GetLength(),
1615 static_cast<int32_t>(kClassRootsMax));
1616 return false;
1617 }
1618 // Check against existing class roots to make sure they match the ones in the boot image.
1619 for (size_t i = 0; i < kClassRootsMax; i++) {
1620 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i))) {
1621 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1622 return false;
1623 }
1624 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001625 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001626 if (oat_file->GetOatHeader().GetDexFileCount() !=
1627 static_cast<uint32_t>(dex_caches->GetLength())) {
1628 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1629 "image";
1630 return false;
1631 }
1632
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001633 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001634 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1635 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001636 // TODO: Only store qualified paths.
1637 // If non qualified, qualify it.
1638 if (dex_file_location.find('/') == std::string::npos) {
1639 std::string dex_location_path = dex_location;
1640 const size_t pos = dex_location_path.find_last_of('/');
1641 CHECK_NE(pos, std::string::npos);
1642 dex_location_path = dex_location_path.substr(0, pos + 1); // Keep trailing '/'
1643 dex_file_location = dex_location_path + dex_file_location;
1644 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001645 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1646 dex_file_location.c_str(),
1647 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001648 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001649 return false;
1650 }
1651
1652 if (app_image) {
1653 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
1654 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00001655 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001656 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00001657 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001658 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001659 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001660 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001661 }
1662 }
1663 } else {
1664 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001665 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
1666 this,
1667 dex_cache->GetResolvedMethods(),
1668 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001669 }
1670 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00001671 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001672 }
1673 out_dex_files->push_back(std::move(dex_file));
1674 }
1675
1676 if (app_image) {
1677 ScopedObjectAccessUnchecked soa(Thread::Current());
1678 // Check that the class loader resolves the same way as the ones in the image.
1679 // Image class loader [A][B][C][image dex files]
1680 // Class loader = [???][dex_elements][image dex files]
1681 // Need to ensure that [???][dex_elements] == [A][B][C].
1682 // For each class loader, PathClassLoader, the laoder checks the parent first. Also the logic
1683 // for PathClassLoader does this by looping through the array of dex files. To ensure they
1684 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
1685 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001686 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1687 *error_msg = "Unexpected BootClassLoader in app image";
1688 return false;
1689 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001690 std::list<ObjPtr<mirror::String>> image_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001691 std::string temp_error_msg;
1692 if (!FlattenPathClassLoader(image_class_loader.Get(), &image_dex_file_names, &temp_error_msg)) {
1693 *error_msg = StringPrintf("Failed to flatten image class loader hierarchy '%s'",
1694 temp_error_msg.c_str());
1695 return false;
1696 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001697 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001698 if (!FlattenPathClassLoader(class_loader.Get(), &loader_dex_file_names, &temp_error_msg)) {
1699 *error_msg = StringPrintf("Failed to flatten class loader hierarchy '%s'",
1700 temp_error_msg.c_str());
1701 return false;
1702 }
1703 // Add the temporary dex path list elements at the end.
1704 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
1705 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
1706 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
1707 if (element != nullptr) {
1708 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001709 ObjPtr<mirror::String> name;
1710 if (GetDexPathListElementName(element, &name) && name != nullptr) {
1711 loader_dex_file_names.push_back(name);
1712 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01001713 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001714 }
1715 // Ignore the number of image dex files since we are adding those to the class loader anyways.
1716 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
1717 static_cast<size_t>(dex_caches->GetLength()));
1718 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
1719 // Check that the dex file names match.
1720 bool equal = image_count == loader_dex_file_names.size();
1721 if (equal) {
1722 auto it1 = image_dex_file_names.begin();
1723 auto it2 = loader_dex_file_names.begin();
1724 for (size_t i = 0; equal && i < image_count; ++i, ++it1, ++it2) {
1725 equal = equal && (*it1)->Equals(*it2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001726 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001727 }
1728 if (!equal) {
1729 VLOG(image) << "Image dex files " << image_dex_file_names.size();
1730 for (ObjPtr<mirror::String> name : image_dex_file_names) {
1731 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001732 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001733 VLOG(image) << "Loader dex files " << loader_dex_file_names.size();
1734 for (ObjPtr<mirror::String> name : loader_dex_file_names) {
1735 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001736 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001737 *error_msg = "Rejecting application image due to class loader mismatch";
1738 // Ignore class loader mismatch for now since these would just use possibly incorrect
1739 // oat code anyways. The structural class check should be done in the parent.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001740 }
1741 }
1742
1743 if (kSanityCheckObjects) {
1744 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1745 auto* dex_cache = dex_caches->Get(i);
1746 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
1747 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
1748 if (field != nullptr) {
1749 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
1750 }
1751 }
1752 }
1753 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001754 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001755 }
1756 }
1757
1758 // Set entry point to interpreter if in InterpretOnly mode.
1759 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001760 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001761 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001762 }
1763
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001764 if (!app_image) {
1765 // Make the string intern table and class table immutable for boot image.
1766 // PIC app oat files may mmap a read-only copy into their own .bss section,
1767 // so enforce that the data in the boot image tables remains unchanged.
1768 //
1769 // We cannot do that for app image even after the fixup as some interned
1770 // String references may actually end up pointing to moveable Strings.
1771 uint8_t* const_section_begin = space->Begin() + header.GetBootImageConstantTablesOffset();
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -07001772 CheckedCall(mprotect,
1773 "protect constant tables",
1774 const_section_begin,
1775 header.GetBootImageConstantTablesSize(),
1776 PROT_READ);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001777 }
1778
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001779 ClassTable* class_table = nullptr;
1780 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001781 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001782 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08001783 }
1784 // If we have a class table section, read it and use it for verification in
1785 // UpdateAppImageClassLoadersAndDexCaches.
1786 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001787 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08001788 const bool added_class_table = class_table_section.Size() > 0u;
1789 if (added_class_table) {
1790 const uint64_t start_time2 = NanoTime();
1791 size_t read_count = 0;
1792 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
1793 /*make copy*/false,
1794 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08001795 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001796 }
1797 if (app_image) {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001798 AppImageClassLoadersAndDexCachesHelper::Update(this,
1799 space,
1800 class_loader,
1801 dex_caches,
1802 &temp_set);
Mathieu Chartier69731002016-03-02 16:08:31 -08001803 // Update class loader and resolved strings. If added_class_table is false, the resolved
1804 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001805 UpdateClassLoaderVisitor visitor(space, class_loader.Get());
1806 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001807 visitor(root.Read());
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001808 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001809 }
1810 if (!oat_file->GetBssGcRoots().empty()) {
1811 // Insert oat file to class table for visiting .bss GC roots.
1812 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001813 }
Mathieu Chartier69731002016-03-02 16:08:31 -08001814 if (added_class_table) {
1815 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1816 class_table->AddClassSet(std::move(temp_set));
1817 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001818
Mathieu Chartier69731002016-03-02 16:08:31 -08001819 if (kIsDebugBuild && app_image) {
1820 // This verification needs to happen after the classes have been added to the class loader.
1821 // Since it ensures classes are in the class table.
Andreas Gampebe7af222017-07-25 09:57:28 -07001822 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08001823 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001824
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001825 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001826 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001827}
1828
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001829bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001830 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
1831 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001832}
1833
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001834void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001835 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
1836 // enabling tracing requires the mutator lock, there are no race conditions here.
1837 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001838 Thread* const self = Thread::Current();
1839 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001840 if (kUseReadBarrier) {
1841 // We do not track new roots for CC.
1842 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
1843 kVisitRootFlagClearRootLog |
1844 kVisitRootFlagStartLoggingNewRoots |
1845 kVisitRootFlagStopLoggingNewRoots));
1846 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001847 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001848 // Argument for how root visiting deals with ArtField and ArtMethod roots.
1849 // There is 3 GC cases to handle:
1850 // Non moving concurrent:
1851 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001852 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001853 //
1854 // Moving non-concurrent:
1855 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
1856 // To prevent missing roots, this case needs to ensure that there is no
1857 // suspend points between the point which we allocate ArtMethod arrays and place them in a
1858 // class which is in the class table.
1859 //
1860 // Moving concurrent:
1861 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
1862 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001863 //
1864 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
1865 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
1866 // these objects.
1867 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07001868 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07001869 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09001870 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001871 for (const ClassLoaderData& data : class_loaders_) {
1872 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
1873 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
1874 }
1875 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001876 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001877 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001878 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001879 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001880 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001881 // Concurrent moving GC marked new roots through the to-space invariant.
1882 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001883 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001884 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
1885 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
1886 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
1887 if (old_ref != nullptr) {
1888 DCHECK(old_ref->IsClass());
1889 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
1890 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
1891 // Concurrent moving GC marked new roots through the to-space invariant.
1892 CHECK_EQ(new_ref, old_ref);
1893 }
1894 }
1895 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001896 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001897 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001898 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00001899 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001900 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001901 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001902 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001903 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001904 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001905 }
1906 // We deliberately ignore the class roots in the image since we
1907 // handle image roots by using the MS/CMS rescanning of dirty cards.
1908}
1909
Brian Carlstroma663ea52011-08-19 23:33:41 -07001910// Keep in sync with InitCallback. Anything we visit, we need to
1911// reinit references to when reinitializing a ClassLinker from a
1912// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001913void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07001914 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001915 VisitClassRoots(visitor, flags);
Mathieu Chartier31000802015-06-14 14:14:37 -07001916 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07001917 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
1918 // unloading if we are marking roots.
1919 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001920}
1921
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001922class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
1923 public:
1924 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
1925 : visitor_(visitor),
1926 done_(false) {}
1927
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001928 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001929 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001930 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001931 if (!done_ && class_table != nullptr) {
1932 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
1933 if (!class_table->Visit(visitor)) {
1934 // If the visitor ClassTable returns false it means that we don't need to continue.
1935 done_ = true;
1936 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001937 }
1938 }
1939
1940 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001941 // Class visitor that limits the class visits from a ClassTable to the classes with
1942 // the provided defining class loader. This filter is used to avoid multiple visits
1943 // of the same class which can be recorded for multiple initiating class loaders.
1944 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
1945 public:
1946 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
1947 ClassVisitor* visitor)
1948 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
1949
1950 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
1951 if (klass->GetClassLoader() != defining_class_loader_) {
1952 return true;
1953 }
1954 return (*visitor_)(klass);
1955 }
1956
1957 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
1958 ClassVisitor* const visitor_;
1959 };
1960
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001961 ClassVisitor* const visitor_;
1962 // If done is true then we don't need to do any more visiting.
1963 bool done_;
1964};
1965
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001966void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07001967 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001968 VisitClassLoaderClassesVisitor loader_visitor(visitor);
1969 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001970 }
1971}
1972
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001973void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001974 Thread* const self = Thread::Current();
1975 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1976 // Not safe to have thread suspension when we are holding a lock.
1977 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001978 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001979 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001980 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001981 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08001982 }
1983}
1984
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001985class GetClassesInToVector : public ClassVisitor {
1986 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001987 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001988 classes_.push_back(klass);
1989 return true;
1990 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001991 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07001992};
1993
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001994class GetClassInToObjectArray : public ClassVisitor {
1995 public:
1996 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
1997 : arr_(arr), index_(0) {}
1998
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001999 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002000 ++index_;
2001 if (index_ <= arr_->GetLength()) {
2002 arr_->Set(index_ - 1, klass);
2003 return true;
2004 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002005 return false;
2006 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002007
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002008 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002009 return index_ <= arr_->GetLength();
2010 }
2011
2012 private:
2013 mirror::ObjectArray<mirror::Class>* const arr_;
2014 int32_t index_;
2015};
2016
2017void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002018 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2019 // is avoiding duplicates.
2020 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002021 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002022 GetClassesInToVector accumulator;
2023 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002024 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002025 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002026 return;
2027 }
2028 }
2029 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002030 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002031 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002032 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002033 // We size the array assuming classes won't be added to the class table during the visit.
2034 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002035 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002036 size_t class_table_size;
2037 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002038 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002039 // Add 100 in case new classes get loaded when we are filling in the object array.
2040 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002041 }
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07002042 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002043 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002044 classes.Assign(
2045 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002046 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002047 GetClassInToObjectArray accumulator(classes.Get());
2048 VisitClasses(&accumulator);
2049 if (accumulator.Succeeded()) {
2050 break;
2051 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002052 }
2053 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2054 // If the class table shrank during creation of the clases array we expect null elements. If
2055 // the class table grew then the loop repeats. If classes are created after the loop has
2056 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002057 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002058 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002059 return;
2060 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002061 }
2062 }
2063}
2064
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002065ClassLinker::~ClassLinker() {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002066 mirror::Class::ResetClass();
2067 mirror::Constructor::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07002068 mirror::Field::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002069 mirror::Method::ResetClass();
2070 mirror::Reference::ResetClass();
2071 mirror::StackTraceElement::ResetClass();
2072 mirror::String::ResetClass();
2073 mirror::Throwable::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002074 mirror::BooleanArray::ResetArrayClass();
2075 mirror::ByteArray::ResetArrayClass();
2076 mirror::CharArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002077 mirror::Constructor::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002078 mirror::DoubleArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002079 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002080 mirror::FloatArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002081 mirror::Method::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002082 mirror::IntArray::ResetArrayClass();
2083 mirror::LongArray::ResetArrayClass();
2084 mirror::ShortArray::ResetArrayClass();
Narayan Kamathafa48272016-08-03 12:46:58 +01002085 mirror::MethodType::ResetClass();
2086 mirror::MethodHandleImpl::ResetClass();
Orion Hodsonc069a302017-01-18 09:23:12 +00002087 mirror::MethodHandlesLookup::ResetClass();
2088 mirror::CallSite::ResetClass();
Narayan Kamath000e1882016-10-24 17:14:25 +01002089 mirror::EmulatedStackFrame::ResetClass();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002090 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002091 for (const ClassLoaderData& data : class_loaders_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002092 DeleteClassLoader(self, data);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002093 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002094 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002095}
2096
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002097void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data) {
2098 Runtime* const runtime = Runtime::Current();
2099 JavaVMExt* const vm = runtime->GetJavaVM();
2100 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002101 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002102 if (runtime->GetJit() != nullptr) {
2103 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2104 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002105 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002106 code_cache->RemoveMethodsIn(self, *data.allocator);
2107 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002108 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002109 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002110 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002111 }
2112 delete data.allocator;
2113 delete data.class_table;
2114}
2115
Mathieu Chartiere401d142015-04-22 13:56:20 -07002116mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) {
Andreas Gampe542451c2016-07-26 09:02:02 -07002117 return down_cast<mirror::PointerArray*>(
2118 image_pointer_size_ == PointerSize::k64
2119 ? static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length))
2120 : static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002121}
2122
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002123mirror::DexCache* ClassLinker::AllocDexCache(ObjPtr<mirror::String>* out_location,
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002124 Thread* self,
2125 const DexFile& dex_file) {
2126 StackHandleScope<1> hs(self);
2127 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002128 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002129 GetClassRoot(kJavaLangDexCache)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002130 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002131 self->AssertPendingOOMException();
2132 return nullptr;
2133 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002134 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002135 if (location == nullptr) {
2136 self->AssertPendingOOMException();
2137 return nullptr;
2138 }
2139 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002140 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002141}
2142
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002143mirror::DexCache* ClassLinker::AllocAndInitializeDexCache(Thread* self,
2144 const DexFile& dex_file,
2145 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002146 ObjPtr<mirror::String> location = nullptr;
2147 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002148 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002149 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002150 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002151 mirror::DexCache::InitializeDexCache(self,
2152 dex_cache,
2153 location,
2154 &dex_file,
2155 linear_alloc,
2156 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002157 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002158 return dex_cache.Ptr();
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002159}
2160
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002161mirror::Class* ClassLinker::AllocClass(Thread* self,
2162 ObjPtr<mirror::Class> java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08002163 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002164 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002165 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002166 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002167 ObjPtr<mirror::Object> k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002168 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2169 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002170 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002171 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002172 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002173 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002174 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002175}
2176
Ian Rogers6fac4472014-02-25 17:01:10 -08002177mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002178 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002179}
2180
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002181mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002182 Thread* self,
2183 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002184 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2185 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002186}
2187
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002188mirror::Class* ClassLinker::EnsureResolved(Thread* self,
2189 const char* descriptor,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002190 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002191 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002192 if (kIsDebugBuild) {
2193 StackHandleScope<1> hs(self);
2194 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2195 Thread::PoisonObjectPointersIfDebug();
2196 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002197
2198 // For temporary classes we must wait for them to be retired.
2199 if (init_done_ && klass->IsTemp()) {
2200 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002201 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002202 ThrowEarlierClassFailure(klass);
2203 return nullptr;
2204 }
2205 StackHandleScope<1> hs(self);
2206 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2207 ObjectLock<mirror::Class> lock(self, h_class);
2208 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002209 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002210 lock.WaitIgnoringInterrupts();
2211 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002212 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002213 ThrowEarlierClassFailure(h_class.Get());
2214 return nullptr;
2215 }
2216 CHECK(h_class->IsRetired());
2217 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002218 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002219 }
2220
Brian Carlstromaded5f72011-10-07 17:15:04 -07002221 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002222 size_t index = 0;
2223 // Maximum number of yield iterations until we start sleeping.
2224 static const size_t kNumYieldIterations = 1000;
2225 // How long each sleep is in us.
2226 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002227 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002228 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002229 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002230 {
2231 ObjectTryLock<mirror::Class> lock(self, h_class);
2232 // Can not use a monitor wait here since it may block when returning and deadlock if another
2233 // thread has locked klass.
2234 if (lock.Acquired()) {
2235 // Check for circular dependencies between classes, the lock is required for SetStatus.
2236 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2237 ThrowClassCircularityError(h_class.Get());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002238 mirror::Class::SetStatus(h_class, mirror::Class::kStatusErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002239 return nullptr;
2240 }
2241 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002242 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002243 {
2244 // Handle wrapper deals with klass moving.
2245 ScopedThreadSuspension sts(self, kSuspended);
2246 if (index < kNumYieldIterations) {
2247 sched_yield();
2248 } else {
2249 usleep(kSleepDurationUS);
2250 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002251 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002252 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002253 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002254
Vladimir Marko72ab6842017-01-20 19:32:50 +00002255 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002256 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002257 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002258 }
2259 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002260 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002261 self->AssertNoPendingException();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002262 return klass.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002263}
2264
Ian Rogers68b56852014-08-29 20:19:11 -07002265typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2266
2267// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002268ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002269 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002270 for (const DexFile* dex_file : class_path) {
David Sehr9aa352e2016-09-15 18:13:52 -07002271 const DexFile::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002272 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002273 return ClassPathEntry(dex_file, dex_class_def);
2274 }
2275 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002276 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002277}
2278
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002279bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2280 Thread* self,
2281 const char* descriptor,
2282 size_t hash,
2283 Handle<mirror::ClassLoader> class_loader,
2284 ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002285 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002286 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002287 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002288 return true;
2289 }
2290
Calin Juravlecdd49122017-07-05 20:09:53 -07002291 if (IsPathOrDexClassLoader(soa, class_loader)) {
2292 // For regular path or dex class loader the search order is:
2293 // - parent
2294 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002295
Calin Juravlecdd49122017-07-05 20:09:53 -07002296 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2297 StackHandleScope<1> hs(self);
2298 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2299 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2300 return false; // One of the parents is not supported.
2301 }
2302 if (*result != nullptr) {
2303 return true; // Found the class up the chain.
2304 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002305
Calin Juravlecdd49122017-07-05 20:09:53 -07002306 // Search the current class loader classpath.
2307 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002308 return true;
2309 }
2310
Calin Juravlecdd49122017-07-05 20:09:53 -07002311 if (IsDelegateLastClassLoader(soa, class_loader)) {
2312 // For delegate last, the search order is:
2313 // - boot class path
2314 // - class loader dex files
2315 // - parent
2316 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2317 if (*result != nullptr) {
2318 return true; // The class is part of the boot class path.
2319 }
2320
2321 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2322 if (*result != nullptr) {
2323 return true; // Found the class in the current class loader
2324 }
2325
2326 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2327 StackHandleScope<1> hs(self);
2328 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2329 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2330 }
2331
2332 // Unsupported class loader.
2333 *result = nullptr;
2334 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002335}
2336
2337// Finds the class in the boot class loader.
2338// If the class is found the method returns the resolved class. Otherwise it returns null.
2339ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2340 const char* descriptor,
2341 size_t hash) {
2342 ObjPtr<mirror::Class> result = nullptr;
2343 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2344 if (pair.second != nullptr) {
2345 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2346 if (klass != nullptr) {
2347 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002348 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002349 result = DefineClass(self,
2350 descriptor,
2351 hash,
2352 ScopedNullHandle<mirror::ClassLoader>(),
2353 *pair.first,
2354 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002355 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002356 if (result == nullptr) {
2357 CHECK(self->IsExceptionPending()) << descriptor;
2358 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002359 }
2360 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002361 return result;
2362}
Andreas Gampef865ea92015-04-13 22:14:19 -07002363
Calin Juravle415dc3d2017-06-28 11:03:12 -07002364ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2365 ScopedObjectAccessAlreadyRunnable& soa,
2366 const char* descriptor,
2367 size_t hash,
2368 Handle<mirror::ClassLoader> class_loader) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002369 CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002370 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002371
Calin Juravle415dc3d2017-06-28 11:03:12 -07002372 Thread* self = soa.Self();
Andreas Gampe08883de2016-11-08 13:20:52 -08002373 ArtField* const cookie_field =
2374 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Andreas Gampef865ea92015-04-13 22:14:19 -07002375 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002376 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002377 ObjPtr<mirror::Object> dex_path_list =
Andreas Gampe08883de2016-11-08 13:20:52 -08002378 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
2379 GetObject(class_loader.Get());
Andreas Gampef865ea92015-04-13 22:14:19 -07002380 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
2381 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002382 ObjPtr<mirror::Object> dex_elements_obj =
Andreas Gampe08883de2016-11-08 13:20:52 -08002383 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
Calin Juravle415dc3d2017-06-28 11:03:12 -07002384 GetObject(dex_path_list);
Andreas Gampef865ea92015-04-13 22:14:19 -07002385 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2386 // at the mCookie which is a DexFile vector.
2387 if (dex_elements_obj != nullptr) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002388 StackHandleScope<1> hs(self);
Andreas Gampef865ea92015-04-13 22:14:19 -07002389 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2390 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2391 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002392 ObjPtr<mirror::Object> element = dex_elements->GetWithoutChecks(i);
Andreas Gampef865ea92015-04-13 22:14:19 -07002393 if (element == nullptr) {
2394 // Should never happen, fall back to java code to throw a NPE.
2395 break;
2396 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002397 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Andreas Gampef865ea92015-04-13 22:14:19 -07002398 if (dex_file != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002399 ObjPtr<mirror::LongArray> long_array = cookie_field->GetObject(dex_file)->AsLongArray();
Andreas Gampef865ea92015-04-13 22:14:19 -07002400 if (long_array == nullptr) {
2401 // This should never happen so log a warning.
2402 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002403 break;
2404 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002405 int32_t long_array_size = long_array->GetLength();
Mathieu Chartiere58991b2015-10-13 07:59:34 -07002406 // First element is the oat file.
2407 for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) {
Andreas Gampef865ea92015-04-13 22:14:19 -07002408 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
2409 long_array->GetWithoutChecks(j)));
David Sehr9aa352e2016-09-15 18:13:52 -07002410 const DexFile::ClassDef* dex_class_def =
2411 OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002412 if (dex_class_def != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002413 ObjPtr<mirror::Class> klass = DefineClass(self,
Calin Juravle415dc3d2017-06-28 11:03:12 -07002414 descriptor,
2415 hash,
2416 class_loader,
2417 *cp_dex_file,
2418 *dex_class_def);
Andreas Gampef865ea92015-04-13 22:14:19 -07002419 if (klass == nullptr) {
2420 CHECK(self->IsExceptionPending()) << descriptor;
2421 self->ClearException();
2422 // TODO: Is it really right to break here, and not check the other dex files?
Calin Juravle415dc3d2017-06-28 11:03:12 -07002423 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002424 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002425 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002426 }
2427 }
2428 }
2429 }
2430 }
Ian Rogers32427292014-11-19 14:05:21 -08002431 self->AssertNoPendingException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002432 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002433 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002434}
2435
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002436mirror::Class* ClassLinker::FindClass(Thread* self,
2437 const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002438 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002439 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002440 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002441 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002442 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002443 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002444 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2445 // for primitive classes that aren't backed by dex files.
2446 return FindPrimitiveClass(descriptor[0]);
2447 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002448 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002449 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002450 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002451 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002452 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002453 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002454 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002455 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002456 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002457 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002458 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002459 return DefineClass(self,
2460 descriptor,
2461 hash,
2462 ScopedNullHandle<mirror::ClassLoader>(),
2463 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002464 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002465 } else {
2466 // The boot class loader is searched ahead of the application class loader, failures are
2467 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2468 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002469 ObjPtr<mirror::Throwable> pre_allocated =
2470 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002471 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002472 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002473 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002474 }
2475 ObjPtr<mirror::Class> result_ptr;
2476 bool descriptor_equals;
2477 if (descriptor[0] == '[') {
2478 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2479 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2480 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2481 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002482 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002483 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002484 bool known_hierarchy =
2485 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2486 if (result_ptr != nullptr) {
2487 // The chain was understood and we found the class. We still need to add the class to
2488 // the class table to protect from racy programs that can try and redefine the path list
2489 // which would change the Class<?> returned for subsequent evaluation of const-class.
2490 DCHECK(known_hierarchy);
2491 DCHECK(result_ptr->DescriptorEquals(descriptor));
2492 descriptor_equals = true;
2493 } else {
2494 // Either the chain wasn't understood or the class wasn't found.
2495 //
2496 // If the chain was understood but we did not find the class, let the Java-side
2497 // rediscover all this and throw the exception with the right stack trace. Note that
2498 // the Java-side could still succeed for racy programs if another thread is actively
2499 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002500
Calin Juravleccd56952016-12-15 17:57:38 +00002501 if (!self->CanCallIntoJava()) {
2502 // Oops, we can't call into java so we can't run actual class-loader code.
2503 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002504 ObjPtr<mirror::Throwable> pre_allocated =
2505 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2506 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002507 return nullptr;
2508 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002509
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002510 // Inlined DescriptorToDot(descriptor) with extra validation.
2511 //
2512 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2513 // the DescriptorEquals() check below and give a confusing error message. For example,
2514 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2515 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2516 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2517 size_t descriptor_length = strlen(descriptor);
2518 if (UNLIKELY(descriptor[0] != 'L') ||
2519 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2520 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2521 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2522 return nullptr;
2523 }
2524 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2525 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2526
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002527 ScopedLocalRef<jobject> class_loader_object(
2528 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002529 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2530 {
2531 ScopedThreadStateChange tsc(self, kNative);
2532 ScopedLocalRef<jobject> class_name_object(
2533 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2534 if (class_name_object.get() == nullptr) {
2535 DCHECK(self->IsExceptionPending()); // OOME.
2536 return nullptr;
2537 }
2538 CHECK(class_loader_object.get() != nullptr);
2539 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2540 WellKnownClasses::java_lang_ClassLoader_loadClass,
2541 class_name_object.get()));
2542 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002543 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002544 // broken loader - throw NPE to be compatible with Dalvik
2545 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2546 class_name_string.c_str()).c_str());
2547 return nullptr;
2548 }
2549 result_ptr = soa.Decode<mirror::Class>(result.get());
2550 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002551 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002552 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002553 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002554
2555 if (self->IsExceptionPending()) {
2556 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2557 // However, to comply with the RI behavior, first check if another thread succeeded.
2558 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2559 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2560 self->ClearException();
2561 return EnsureResolved(self, descriptor, result_ptr);
2562 }
2563 return nullptr;
2564 }
2565
2566 // Try to insert the class to the class table, checking for mismatch.
2567 ObjPtr<mirror::Class> old;
2568 {
2569 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2570 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2571 old = class_table->Lookup(descriptor, hash);
2572 if (old == nullptr) {
2573 old = result_ptr; // For the comparison below, after releasing the lock.
2574 if (descriptor_equals) {
2575 class_table->InsertWithHash(result_ptr.Ptr(), hash);
2576 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get());
2577 } // else throw below, after releasing the lock.
2578 }
2579 }
2580 if (UNLIKELY(old != result_ptr)) {
2581 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2582 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2583 mirror::Class* loader_class = class_loader->GetClass();
2584 const char* loader_class_name =
2585 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2586 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2587 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2588 << DescriptorToDot(descriptor) << "\").";
2589 return EnsureResolved(self, descriptor, old);
2590 }
2591 if (UNLIKELY(!descriptor_equals)) {
2592 std::string result_storage;
2593 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2594 std::string loader_storage;
2595 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2596 ThrowNoClassDefFoundError(
2597 "Initiating class loader of type %s returned class %s instead of %s.",
2598 DescriptorToDot(loader_class_name).c_str(),
2599 DescriptorToDot(result_name).c_str(),
2600 DescriptorToDot(descriptor).c_str());
2601 return nullptr;
2602 }
2603 // success, return mirror::Class*
2604 return result_ptr.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002605}
2606
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002607mirror::Class* ClassLinker::DefineClass(Thread* self,
2608 const char* descriptor,
2609 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002610 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002611 const DexFile& dex_file,
2612 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002613 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002614 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002615
Brian Carlstromaded5f72011-10-07 17:15:04 -07002616 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002617 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002618 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002619 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002620 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002621 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002622 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002623 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002624 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002625 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2626 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002627 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002628 klass.Assign(GetClassRoot(kJavaLangDexCache));
Alex Lightd6251582016-10-31 11:12:30 -07002629 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
2630 klass.Assign(GetClassRoot(kDalvikSystemClassExt));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002631 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002632 }
2633
Andreas Gampefa4333d2017-02-14 11:10:34 -08002634 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002635 // Allocate a class with the status of not ready.
2636 // Interface object should get the right size here. Regular class will
2637 // figure out the right size later and be replaced with one of the right
2638 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002639 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002640 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08002641 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002642 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07002643 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002644 }
Alex Lightb0f11922017-01-23 14:25:17 -08002645 // Get the real dex file. This will return the input if there aren't any callbacks or they do
2646 // nothing.
2647 DexFile const* new_dex_file = nullptr;
2648 DexFile::ClassDef const* new_class_def = nullptr;
2649 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
2650 // will only be called once.
2651 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
2652 klass,
2653 class_loader,
2654 dex_file,
2655 dex_class_def,
2656 &new_dex_file,
2657 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08002658 // Check to see if an exception happened during runtime callbacks. Return if so.
2659 if (self->IsExceptionPending()) {
2660 return nullptr;
2661 }
Alex Lightb0f11922017-01-23 14:25:17 -08002662 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002663 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002664 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002665 return nullptr;
2666 }
2667 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08002668 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002669
Jeff Hao848f70a2014-01-15 13:49:50 -08002670 // Mark the string class by setting its access flag.
2671 if (UNLIKELY(!init_done_)) {
2672 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2673 klass->SetStringClass();
2674 }
2675 }
2676
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002677 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002678 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08002679 // Make sure we have a valid empty iftable even if there are errors.
2680 klass->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002681
Mathieu Chartier590fee92013-09-13 13:46:47 -07002682 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002683 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002684 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002685 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2686 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002687 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002688 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002689
Mathieu Chartierc7853442015-03-27 14:35:38 -07002690 // Load the fields and other things after we are inserted in the table. This is so that we don't
2691 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
2692 // other reason is that the field roots are only visited from the class table. So we need to be
2693 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08002694 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002695 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002696 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07002697 // An exception occured during load, set status to erroneous while holding klass' lock in case
2698 // notification is necessary.
2699 if (!klass->IsErroneous()) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002700 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002701 }
2702 return nullptr;
2703 }
2704
Brian Carlstromaded5f72011-10-07 17:15:04 -07002705 // Finish loading (if necessary) by finding parents
2706 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08002707 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002708 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002709 if (!klass->IsErroneous()) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002710 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002711 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002712 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002713 }
2714 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08002715
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07002716 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08002717 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08002718 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08002719
Brian Carlstromaded5f72011-10-07 17:15:04 -07002720 // Link the class (if necessary)
2721 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002722 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002723 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002724
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002725 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002726 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002727 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002728 if (!klass->IsErroneous()) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002729 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002730 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002731 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002732 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002733 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002734 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00002735 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002736
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002737 // Instrumentation may have updated entrypoints for all methods of all
2738 // classes. However it could not update methods of this class while we
2739 // were loading it. Now the class is resolved, we can update entrypoints
2740 // as required by instrumentation.
2741 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2742 // We must be in the kRunnable state to prevent instrumentation from
2743 // suspending all threads to update entrypoints while we are doing it
2744 // for this class.
2745 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002746 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002747 }
2748
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002749 /*
2750 * We send CLASS_PREPARE events to the debugger from here. The
2751 * definition of "preparation" is creating the static fields for a
2752 * class and initializing them to the standard default values, but not
2753 * executing any code (that comes later, during "initialization").
2754 *
2755 * We did the static preparation in LinkClass.
2756 *
2757 * The class has been prepared and resolved but possibly not yet verified
2758 * at this point.
2759 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08002760 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002761
Tamas Berghammer160e6df2016-01-05 14:29:02 +00002762 // Notify native debugger of the new class and its layout.
2763 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
2764
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002765 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002766}
2767
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002768uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2769 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002770 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002771 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002772 size_t num_8 = 0;
2773 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002774 size_t num_32 = 0;
2775 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002776 if (class_data != nullptr) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002777 // We allow duplicate definitions of the same field in a class_data_item
2778 // but ignore the repeated indexes here, b/21868015.
Andreas Gampee2abbc62017-09-15 11:59:26 -07002779 uint32_t last_field_idx = dex::kDexNoIndex;
Ian Rogers0571d352011-11-03 19:51:38 -07002780 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002781 uint32_t field_idx = it.GetMemberIndex();
2782 // Ordering enforced by DexFileVerifier.
Andreas Gampee2abbc62017-09-15 11:59:26 -07002783 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
Vladimir Marko879d27b2016-03-15 20:31:50 +00002784 if (UNLIKELY(field_idx == last_field_idx)) {
2785 continue;
2786 }
2787 last_field_idx = field_idx;
2788 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002789 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002790 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002791 switch (c) {
2792 case 'L':
2793 case '[':
2794 num_ref++;
2795 break;
2796 case 'J':
2797 case 'D':
2798 num_64++;
2799 break;
2800 case 'I':
2801 case 'F':
2802 num_32++;
2803 break;
2804 case 'S':
2805 case 'C':
2806 num_16++;
2807 break;
2808 case 'B':
2809 case 'Z':
2810 num_8++;
2811 break;
2812 default:
2813 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002814 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002815 }
2816 }
2817 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002818 return mirror::Class::ComputeClassSize(false,
2819 0,
2820 num_8,
2821 num_16,
2822 num_32,
2823 num_64,
2824 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002825 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002826}
2827
TDYa12785321912012-04-01 15:24:56 -07002828// Special case to get oat code without overwriting a trampoline.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002829const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07002830 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00002831 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002832 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002833 }
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002834 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
2835 if (code != nullptr) {
2836 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08002837 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002838 if (method->IsNative()) {
2839 // No code and native? Use generic trampoline.
2840 return GetQuickGenericJniStub();
2841 }
2842 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07002843}
2844
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002845bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
2846 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
2847 return false;
2848 }
2849
Elliott Hughes956af0f2014-12-11 14:34:28 -08002850 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002851 return true;
2852 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002853
2854 Runtime* runtime = Runtime::Current();
2855 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
2856 if (instr->InterpretOnly()) {
2857 return true;
2858 }
2859
2860 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
2861 // Doing this check avoids doing compiled/interpreter transitions.
2862 return true;
2863 }
2864
2865 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
2866 // Force the use of interpreter when it is required by the debugger.
2867 return true;
2868 }
2869
Alex Light8f34aba2017-10-09 13:46:32 -07002870 if (Thread::Current()->IsAsyncExceptionPending()) {
2871 // Force use of interpreter to handle async-exceptions
2872 return true;
2873 }
2874
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002875 if (runtime->IsJavaDebuggable()) {
2876 // For simplicity, we ignore precompiled code and go to the interpreter
2877 // assuming we don't already have jitted code.
2878 // We could look at the oat file where `quick_code` is being defined,
2879 // and check whether it's been compiled debuggable, but we decided to
2880 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08002881 jit::Jit* jit = Runtime::Current()->GetJit();
2882 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
2883 }
2884
David Srbeckyf4480162016-03-16 00:06:24 +00002885 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01002886 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00002887 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002888 // since we want to JIT it (at first use) with extra stackmaps for native
2889 // debugging. We keep however all AOT code from the boot image,
2890 // since the JIT-at-first-use is blocking and would result in non-negligible
2891 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00002892 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002893 }
2894
2895 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002896}
2897
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002898void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07002899 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07002900 if (klass->NumDirectMethods() == 0) {
2901 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002902 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002903 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002904 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002905 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002906 return; // OAT file unavailable.
2907 }
Ian Rogers19846512012-02-24 11:42:47 -08002908 }
Alex Light64ad14d2014-08-19 14:23:13 -07002909
Mathieu Chartierf8322842014-05-16 10:59:25 -07002910 const DexFile& dex_file = klass->GetDexFile();
2911 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002912 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002913 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002914 // There should always be class data if there were direct methods.
David Sehr709b0702016-10-13 09:12:37 -07002915 CHECK(class_data != nullptr) << klass->PrettyDescriptor();
Ian Rogers19846512012-02-24 11:42:47 -08002916 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002917 it.SkipAllFields();
Ian Rogers97b52f82014-08-14 11:34:07 -07002918 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002919 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
2920 klass->GetDexClassDefIndex(),
2921 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002922 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002923 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002924 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002925 if (!method->IsStatic()) {
2926 // Only update static methods.
2927 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002928 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002929 const void* quick_code = nullptr;
2930 if (has_oat_class) {
2931 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002932 quick_code = oat_method.GetQuickCode();
2933 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002934 // Check whether the method is native, in which case it's generic JNI.
2935 if (quick_code == nullptr && method->IsNative()) {
2936 quick_code = GetQuickGenericJniStub();
2937 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002938 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002939 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002940 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002941 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08002942 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002943 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002944}
2945
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002946// Does anything needed to make sure that the compiler will not generate a direct invoke to this
2947// method. Should only be called on non-invokable methods.
2948inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07002949 DCHECK(method != nullptr);
2950 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002951 method->SetEntryPointFromQuickCompiledCodePtrSize(
2952 class_linker->GetQuickToInterpreterBridgeTrampoline(),
2953 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07002954}
2955
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002956static void LinkCode(ClassLinker* class_linker,
2957 ArtMethod* method,
2958 const OatFile::OatClass* oat_class,
2959 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002960 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002961 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002962 // The following code only applies to a non-compiler runtime.
2963 return;
2964 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002965 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002966 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002967 if (oat_class != nullptr) {
2968 // Every kind of method should at least get an invoke stub from the oat_method.
2969 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002970 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002971 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002972 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002973
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00002974 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002975 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002976 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07002977
Alex Light9139e002015-10-09 15:59:48 -07002978 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002979 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002980 return;
2981 }
Ian Rogers19846512012-02-24 11:42:47 -08002982
2983 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002984 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002985 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2986 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002987 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002988 } else if (quick_code == nullptr && method->IsNative()) {
2989 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00002990 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002991 // Set entry point from compiled code if there's no code or in interpreter only mode.
2992 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002993 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002994
Ian Rogers62d6c772013-02-27 08:32:07 -08002995 if (method->IsNative()) {
2996 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002997 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002998
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002999 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003000 // We have a native method here without code. Then it should have either the generic JNI
3001 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3002 // TODO: this doesn't handle all the cases where trampolines may be installed.
3003 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003004 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3005 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003006 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003007 }
3008}
3009
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003010void ClassLinker::SetupClass(const DexFile& dex_file,
3011 const DexFile::ClassDef& dex_class_def,
3012 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003013 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003014 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003015 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003016 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003017 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003018 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003019
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003020 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07003021 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003022 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003023 klass->SetAccessFlags(access_flags);
3024 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003025 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003026 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003027
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003028 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003029 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003030}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003031
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003032void ClassLinker::LoadClass(Thread* self,
3033 const DexFile& dex_file,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003034 const DexFile::ClassDef& dex_class_def,
3035 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07003036 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003037 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07003038 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07003039 }
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003040 LoadClassMembers(self, dex_file, class_data, klass);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003041}
3042
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003043LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3044 LinearAlloc* allocator,
3045 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003046 if (length == 0) {
3047 return nullptr;
3048 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003049 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3050 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3051 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003052 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003053 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003054 CHECK(ret != nullptr);
3055 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3056 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003057}
3058
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003059LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3060 LinearAlloc* allocator,
3061 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003062 if (length == 0) {
3063 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003064 }
Vladimir Marko14632852015-08-17 12:07:23 +01003065 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3066 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003067 const size_t storage_size =
3068 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003069 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003070 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003071 CHECK(ret != nullptr);
3072 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003073 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003074 }
3075 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003076}
3077
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003078LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003079 if (class_loader == nullptr) {
3080 return Runtime::Current()->GetLinearAlloc();
3081 }
3082 LinearAlloc* allocator = class_loader->GetAllocator();
3083 DCHECK(allocator != nullptr);
3084 return allocator;
3085}
3086
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003087LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003088 if (class_loader == nullptr) {
3089 return Runtime::Current()->GetLinearAlloc();
3090 }
3091 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3092 LinearAlloc* allocator = class_loader->GetAllocator();
3093 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003094 RegisterClassLoader(class_loader);
3095 allocator = class_loader->GetAllocator();
3096 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003097 }
3098 return allocator;
3099}
3100
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003101void ClassLinker::LoadClassMembers(Thread* self,
3102 const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07003103 const uint8_t* class_data,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003104 Handle<mirror::Class> klass) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003105 {
3106 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3107 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003108 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003109 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003110 // We allow duplicate definitions of the same field in a class_data_item
3111 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003112 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003113 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003114 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3115 allocator,
3116 it.NumStaticFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003117 size_t num_sfields = 0;
3118 uint32_t last_field_idx = 0u;
3119 for (; it.HasNextStaticField(); it.Next()) {
3120 uint32_t field_idx = it.GetMemberIndex();
3121 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3122 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
3123 DCHECK_LT(num_sfields, it.NumStaticFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003124 LoadField(it, klass, &sfields->At(num_sfields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003125 ++num_sfields;
3126 last_field_idx = field_idx;
3127 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003128 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003129
Mathieu Chartiere401d142015-04-22 13:56:20 -07003130 // Load instance fields.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003131 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3132 allocator,
3133 it.NumInstanceFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003134 size_t num_ifields = 0u;
3135 last_field_idx = 0u;
3136 for (; it.HasNextInstanceField(); it.Next()) {
3137 uint32_t field_idx = it.GetMemberIndex();
3138 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3139 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
3140 DCHECK_LT(num_ifields, it.NumInstanceFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003141 LoadField(it, klass, &ifields->At(num_ifields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003142 ++num_ifields;
3143 last_field_idx = field_idx;
3144 }
3145 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003146
Vladimir Marko23682bf2015-06-24 14:28:03 +01003147 if (UNLIKELY(num_sfields != it.NumStaticFields()) ||
3148 UNLIKELY(num_ifields != it.NumInstanceFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003149 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Vladimir Marko23682bf2015-06-24 14:28:03 +01003150 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields()
3151 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003152 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3153 if (sfields != nullptr) {
3154 sfields->SetSize(num_sfields);
3155 }
3156 if (ifields != nullptr) {
3157 ifields->SetSize(num_ifields);
3158 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003159 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003160 // Set the field arrays.
3161 klass->SetSFieldsPtr(sfields);
3162 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003163 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003164 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
3165 // Load methods.
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003166 bool has_oat_class = false;
3167 const OatFile::OatClass oat_class =
3168 (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler())
3169 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3170 : OatFile::OatClass::Invalid();
3171 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
Alex Lighte64300b2015-12-15 15:02:47 -08003172 klass->SetMethodsPtr(
3173 AllocArtMethodArray(self, allocator, it.NumDirectMethods() + it.NumVirtualMethods()),
3174 it.NumDirectMethods(),
3175 it.NumVirtualMethods());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003176 size_t class_def_method_index = 0;
Andreas Gampee2abbc62017-09-15 11:59:26 -07003177 uint32_t last_dex_method_index = dex::kDexNoIndex;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003178 size_t last_class_def_method_index = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08003179 // TODO These should really use the iterators.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003180 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
3181 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003182 LoadMethod(dex_file, it, klass, method);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003183 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003184 uint32_t it_method_index = it.GetMemberIndex();
3185 if (last_dex_method_index == it_method_index) {
3186 // duplicate case
3187 method->SetMethodIndex(last_class_def_method_index);
3188 } else {
3189 method->SetMethodIndex(class_def_method_index);
3190 last_dex_method_index = it_method_index;
3191 last_class_def_method_index = class_def_method_index;
3192 }
3193 class_def_method_index++;
3194 }
3195 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
3196 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003197 LoadMethod(dex_file, it, klass, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003198 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003199 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003200 class_def_method_index++;
3201 }
3202 DCHECK(!it.HasNext());
Ian Rogers0571d352011-11-03 19:51:38 -07003203 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003204 // Ensure that the card is marked so that remembered sets pick up native roots.
3205 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003206 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003207}
3208
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003209void ClassLinker::LoadField(const ClassDataItemIterator& it,
3210 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003211 ArtField* dst) {
3212 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003213 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003214 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07003215 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003216}
3217
Mathieu Chartier268764d2016-09-13 12:09:38 -07003218void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003219 const ClassDataItemIterator& it,
3220 Handle<mirror::Class> klass,
3221 ArtMethod* dst) {
Ian Rogers19846512012-02-24 11:42:47 -08003222 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08003223 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003224 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003225
Mathieu Chartier268764d2016-09-13 12:09:38 -07003226 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003227 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003228 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07003229 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003230
Andreas Gampe51829322014-08-25 15:05:04 -07003231 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07003232
Ian Rogersdfb325e2013-10-30 01:00:44 -07003233 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003234 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003235 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3236 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003237 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003238 klass->SetFinalizable();
3239 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003240 std::string temp;
3241 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003242 // The Enum class declares a "final" finalize() method to prevent subclasses from
3243 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3244 // subclasses, so we exclude it here.
3245 // We also want to avoid setting the flag on Object, where we know that finalize() is
3246 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003247 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3248 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003249 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003250 }
3251 }
3252 }
3253 } else if (method_name[0] == '<') {
3254 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003255 bool is_init = (strcmp("<init>", method_name) == 0);
3256 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003257 if (UNLIKELY(!is_init && !is_clinit)) {
3258 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3259 } else {
3260 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3261 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003262 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003263 access_flags |= kAccConstructor;
3264 }
3265 }
3266 }
3267 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003268}
3269
Ian Rogers7b078e82014-09-10 14:44:24 -07003270void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003271 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003272 self,
3273 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003274 Runtime::Current()->GetLinearAlloc());
3275 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003276 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003277}
3278
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003279void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003280 ObjPtr<mirror::DexCache> dex_cache) {
3281 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003282 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003283 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
3284 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003285}
3286
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003287void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003288 ObjPtr<mirror::DexCache> dex_cache,
3289 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003290 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003291 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003292 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003293 // For app images, the dex cache location may be a suffix of the dex file location since the
3294 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003295 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3296 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003297 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3298 std::string dex_file_location = dex_file.GetLocation();
3299 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003300 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003301 // Take suffix.
3302 const std::string dex_file_suffix = dex_file_location.substr(
3303 dex_file_location.length() - dex_cache_length,
3304 dex_cache_length);
3305 // Example dex_cache location is SettingsProvider.apk and
3306 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003307 CHECK_EQ(dex_cache_location, dex_file_suffix);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003308 const OatFile* oat_file =
3309 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
3310 // Clean up pass to remove null dex caches. Also check if we need to initialize OatFile .bss.
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003311 // Null dex caches can occur due to class unloading and we are lazily removing null entries.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003312 bool initialize_oat_file_bss = (oat_file != nullptr);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003313 JavaVMExt* const vm = self->GetJniEnv()->vm;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003314 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3315 DexCacheData data = *it;
3316 if (self->IsJWeakCleared(data.weak_root)) {
3317 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003318 it = dex_caches_.erase(it);
3319 } else {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003320 if (initialize_oat_file_bss &&
3321 it->dex_file->GetOatDexFile() != nullptr &&
3322 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
3323 initialize_oat_file_bss = false; // Already initialized.
3324 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003325 ++it;
3326 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003327 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003328 if (initialize_oat_file_bss) {
3329 // TODO: Pre-initialize from boot/app image?
3330 ArtMethod* resolution_method = Runtime::Current()->GetResolutionMethod();
3331 for (ArtMethod*& entry : oat_file->GetBssMethods()) {
3332 entry = resolution_method;
3333 }
3334 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003335 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003336 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003337 DexCacheData data;
3338 data.weak_root = dex_cache_jweak;
3339 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003340 data.class_table = ClassTableForClassLoader(class_loader);
3341 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003342 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3343 // path dex caches without an image.
3344 data.class_table->InsertStrongRoot(dex_cache);
3345 if (class_loader != nullptr) {
3346 // Since we added a strong root to the class table, do the write barrier as required for
3347 // remembered sets and generational GCs.
3348 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3349 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003350 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003351}
3352
Vladimir Markocd556b02017-02-03 11:47:34 +00003353ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3354 return data.IsValid()
3355 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3356 : nullptr;
3357}
3358
3359ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3360 Thread* self,
3361 ObjPtr<mirror::DexCache> dex_cache,
3362 const DexCacheData& data,
3363 ObjPtr<mirror::ClassLoader> class_loader) {
3364 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3365 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3366 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3367 "Attempt to register dex file %s with multiple class loaders",
3368 data.dex_file->GetLocation().c_str());
3369 return nullptr;
3370 }
3371 return dex_cache;
3372}
3373
Alex Light07f06212017-06-01 14:01:43 -07003374void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3375 ObjPtr<mirror::ClassLoader> class_loader) {
3376 Thread* self = Thread::Current();
3377 StackHandleScope<2> hs(self);
3378 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3379 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3380 const DexFile* dex_file = dex_cache->GetDexFile();
3381 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3382 if (kIsDebugBuild) {
3383 DexCacheData old_data;
3384 {
3385 ReaderMutexLock mu(self, *Locks::dex_lock_);
3386 old_data = FindDexCacheDataLocked(*dex_file);
3387 }
3388 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3389 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3390 << "been registered on dex file " << dex_file->GetLocation();
3391 }
3392 ClassTable* table;
3393 {
3394 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3395 table = InsertClassTableForClassLoader(h_class_loader.Get());
3396 }
3397 WriterMutexLock mu(self, *Locks::dex_lock_);
3398 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3399 table->InsertStrongRoot(h_dex_cache.Get());
3400 if (h_class_loader.Get() != nullptr) {
3401 // Since we added a strong root to the class table, do the write barrier as required for
3402 // remembered sets and generational GCs.
3403 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3404 }
3405}
3406
Vladimir Markocd556b02017-02-03 11:47:34 +00003407ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3408 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003409 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003410 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003411 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003412 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003413 old_data = FindDexCacheDataLocked(dex_file);
3414 }
3415 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3416 if (old_dex_cache != nullptr) {
3417 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003418 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003419 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3420 DCHECK(linear_alloc != nullptr);
3421 ClassTable* table;
3422 {
3423 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3424 table = InsertClassTableForClassLoader(class_loader);
3425 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003426 // Don't alloc while holding the lock, since allocation may need to
3427 // suspend all threads and another thread may need the dex_lock_ to
3428 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003429 StackHandleScope<3> hs(self);
3430 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003431 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003432 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3433 self,
3434 dex_file)));
3435 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003436 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003437 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003438 old_data = FindDexCacheDataLocked(dex_file);
3439 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003440 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003441 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3442 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3443 // that the arrays are null.
3444 mirror::DexCache::InitializeDexCache(self,
3445 h_dex_cache.Get(),
3446 h_location.Get(),
3447 &dex_file,
3448 linear_alloc,
3449 image_pointer_size_);
3450 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003451 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003452 }
3453 if (old_dex_cache != nullptr) {
3454 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3455 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003456 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003457 self->ClearException();
3458 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3459 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3460 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003461 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003462 self->AssertPendingOOMException();
3463 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003464 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003465 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003466 if (h_class_loader.Get() != nullptr) {
3467 // Since we added a strong root to the class table, do the write barrier as required for
3468 // remembered sets and generational GCs.
3469 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3470 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003471 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003472}
3473
Vladimir Markocd556b02017-02-03 11:47:34 +00003474bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003475 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003476 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003477}
3478
Vladimir Markocd556b02017-02-03 11:47:34 +00003479ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3480 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003481 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3482 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003483 if (dex_cache != nullptr) {
3484 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003485 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003486 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003487 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003488 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003489 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003490 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003491 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003492 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3493 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003494 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003495}
3496
Vladimir Markocd556b02017-02-03 11:47:34 +00003497ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3498 const DexFile* dex_file = dex_cache->GetDexFile();
3499 DCHECK(dex_file != nullptr);
3500 ReaderMutexLock mu(self, *Locks::dex_lock_);
3501 // Search assuming unique-ness of dex file.
3502 for (const DexCacheData& data : dex_caches_) {
3503 // Avoid decoding (and read barriers) other unrelated dex caches.
3504 if (data.dex_file == dex_file) {
3505 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3506 if (registered_dex_cache != nullptr) {
3507 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3508 return data.class_table;
3509 }
3510 }
3511 }
3512 return nullptr;
3513}
3514
3515ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3516 // Search assuming unique-ness of dex file.
3517 for (const DexCacheData& data : dex_caches_) {
3518 // Avoid decoding (and read barriers) other unrelated dex caches.
3519 if (data.dex_file == &dex_file) {
3520 return data;
3521 }
3522 }
3523 return DexCacheData();
3524}
3525
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003526mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003527 ObjPtr<mirror::Class> klass =
3528 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003529 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003530 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003531 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003532 }
3533 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003534}
3535
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003536mirror::Class* ClassLinker::InitializePrimitiveClass(ObjPtr<mirror::Class> primitive_class,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003537 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003538 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003539 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003540 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003541 StackHandleScope<1> hs(self);
3542 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003543 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003544 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3545 h_class->SetPrimitiveType(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003546 h_class->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003547 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003548 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003549 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3550 h_class.Get(),
3551 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003552 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003553 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003554}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003555
Brian Carlstrombe977852011-07-19 14:54:54 -07003556// Create an array class (i.e. the class object for the array, not the
3557// array itself). "descriptor" looks like "[C" or "[[[[B" or
3558// "[Ljava/lang/String;".
3559//
3560// If "descriptor" refers to an array of primitives, look up the
3561// primitive type's internally-generated class object.
3562//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003563// "class_loader" is the class loader of the class that's referring to
3564// us. It's used to ensure that we're looking for the element type in
3565// the right context. It does NOT become the class loader for the
3566// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003567//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003568// Returns null with an exception raised on failure.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003569mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003570 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003571 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003572 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003573 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003574 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3575 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003576 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003577 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003578 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003579 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3580 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003581 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003582 DCHECK(self->IsExceptionPending());
3583 return nullptr;
3584 } else {
3585 self->ClearException();
3586 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003587 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003588 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3589 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3590 return nullptr;
3591 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003592 // See if the component type is already loaded. Array classes are
3593 // always associated with the class loader of their underlying
3594 // element type -- an array of Strings goes with the loader for
3595 // java/lang/String -- so we need to look for it there. (The
3596 // caller should have checked for the existence of the class
3597 // before calling here, but they did so with *their* class loader,
3598 // not the component type's loader.)
3599 //
3600 // If we find it, the caller adds "loader" to the class' initiating
3601 // loader list, which should prevent us from going through this again.
3602 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003603 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003604 // are the same, because our caller (FindClass) just did the
3605 // lookup. (Even if we get this wrong we still have correct behavior,
3606 // because we effectively do this lookup again when we add the new
3607 // class to the hash table --- necessary because of possible races with
3608 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003609 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003610 ObjPtr<mirror::Class> new_class =
3611 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003612 if (new_class != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003613 return new_class.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003614 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003615 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003616
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003617 // Fill out the fields in the Class.
3618 //
3619 // It is possible to execute some methods against arrays, because
3620 // all arrays are subclasses of java_lang_Object_, so we need to set
3621 // up a vtable. We can just point at the one in java_lang_Object_.
3622 //
3623 // Array classes are simple enough that we don't need to do a full
3624 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003625 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003626 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003627 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003628 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003629 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003630 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003631 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003632 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003633 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003634 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003635 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003636 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003637 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07003638 } else if (strcmp(descriptor, "[J") == 0) {
3639 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003640 }
3641 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003642 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003643 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003644 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003645 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003646 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003647 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003648 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003649 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003650 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003651 DCHECK(new_class->GetComponentType() != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003652 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003653 new_class->SetSuperClass(java_lang_Object);
3654 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003655 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003656 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07003657 if (component_type->IsPrimitive()) {
3658 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
3659 } else {
3660 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
3661 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003662 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00003663 new_class->PopulateEmbeddedVTable(image_pointer_size_);
3664 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
3665 new_class->SetImt(object_imt, image_pointer_size_);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003666 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003667 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003668 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003669
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003670 // All arrays have java/lang/Cloneable and java/io/Serializable as
3671 // interfaces. We need to set that up here, so that stuff like
3672 // "instanceof" works right.
3673 //
3674 // Note: The GC could run during the call to FindSystemClass,
3675 // so we need to make sure the class object is GC-valid while we're in
3676 // there. Do this by clearing the interface list so the GC will just
3677 // think that the entries are null.
3678
3679
3680 // Use the single, global copies of "interfaces" and "iftable"
3681 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003682 {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003683 ObjPtr<mirror::IfTable> array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003684 CHECK(array_iftable != nullptr);
3685 new_class->SetIfTable(array_iftable);
3686 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003687
Elliott Hughes00626c22013-06-14 15:04:14 -07003688 // Inherit access flags from the component type.
3689 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3690 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3691 access_flags &= kAccJavaFlagsMask;
3692 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003693 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003694 access_flags |= kAccAbstract | kAccFinal;
3695 access_flags &= ~kAccInterface;
3696
3697 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003698
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003699 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003700 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003701 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
3702 // duplicate events in case of races. Array classes don't really follow dedicated
3703 // load and prepare, anyways.
3704 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
3705 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
3706
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003707 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003708 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003709 }
3710 // Another thread must have loaded the class after we
3711 // started but before we finished. Abandon what we've
3712 // done.
3713 //
3714 // (Yes, this happens.)
3715
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003716 return existing.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003717}
3718
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003719mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003720 switch (type) {
3721 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003722 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003723 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003724 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003725 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003726 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003727 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003728 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003729 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003730 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003731 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003732 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003733 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003734 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003735 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003736 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003737 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003738 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003739 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003740 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003741 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003742 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003743 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003744 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003745}
3746
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003747mirror::Class* ClassLinker::InsertClass(const char* descriptor, ObjPtr<mirror::Class> klass, size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003748 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003749 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003750 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003751 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003752 source += " from ";
3753 source += dex_cache->GetLocation()->ToModifiedUtf8();
3754 }
3755 LOG(INFO) << "Loaded class " << descriptor << source;
3756 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003757 {
3758 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003759 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07003760 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003761 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003762 if (existing != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003763 return existing.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07003764 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003765 VerifyObject(klass);
3766 class_table->InsertWithHash(klass, hash);
3767 if (class_loader != nullptr) {
3768 // This is necessary because we need to have the card dirtied for remembered sets.
3769 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3770 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00003771 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07003772 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003773 }
3774 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003775 if (kIsDebugBuild) {
3776 // Test that copied methods correctly can find their holder.
3777 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
3778 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
3779 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08003780 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003781 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003782}
3783
Vladimir Marko1998cd02017-01-13 13:02:58 +00003784void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003785 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3786 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
3787 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
3788 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00003789 }
3790}
3791
Alex Lighte64300b2015-12-15 15:02:47 -08003792// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003793void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08003794 LengthPrefixedArray<ArtMethod>* new_methods) {
3795 klass->SetMethodsPtrUnchecked(new_methods,
3796 klass->NumDirectMethods(),
3797 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003798 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003799 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003800}
3801
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003802mirror::Class* ClassLinker::LookupClass(Thread* self,
Andreas Gampe2ff3b972017-06-05 18:14:53 -07003803 const char* descriptor,
3804 ObjPtr<mirror::ClassLoader> class_loader) {
3805 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
3806}
3807
3808mirror::Class* ClassLinker::LookupClass(Thread* self,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003809 const char* descriptor,
3810 size_t hash,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003811 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01003812 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3813 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3814 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003815 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01003816 if (result != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003817 return result.Ptr();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003818 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003819 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01003820 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003821}
3822
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003823class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
3824 public:
3825 explicit MoveClassTableToPreZygoteVisitor() {}
3826
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003827 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003828 REQUIRES(Locks::classlinker_classes_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003829 REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003830 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07003831 if (class_table != nullptr) {
3832 class_table->FreezeSnapshot();
3833 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003834 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003835};
3836
3837void ClassLinker::MoveClassTableToPreZygote() {
3838 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07003839 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003840 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003841 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003842}
3843
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003844// Look up classes by hash and descriptor and put all matching ones in the result array.
3845class LookupClassesVisitor : public ClassLoaderVisitor {
3846 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003847 LookupClassesVisitor(const char* descriptor,
3848 size_t hash,
3849 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003850 : descriptor_(descriptor),
3851 hash_(hash),
3852 result_(result) {}
3853
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003854 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003855 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003856 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003857 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003858 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
3859 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003860 result_->push_back(klass);
3861 }
3862 }
3863
3864 private:
3865 const char* const descriptor_;
3866 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003867 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003868};
3869
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003870void ClassLinker::LookupClasses(const char* descriptor,
3871 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003872 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003873 Thread* const self = Thread::Current();
3874 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003875 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07003876 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003877 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003878 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003879 result.push_back(klass);
3880 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003881 LookupClassesVisitor visitor(descriptor, hash, &result);
3882 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003883}
3884
Alex Lightf1f10492015-10-07 16:08:36 -07003885bool ClassLinker::AttemptSupertypeVerification(Thread* self,
3886 Handle<mirror::Class> klass,
3887 Handle<mirror::Class> supertype) {
3888 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003889 DCHECK(klass != nullptr);
3890 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07003891
Alex Lightf1f10492015-10-07 16:08:36 -07003892 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
3893 VerifyClass(self, supertype);
3894 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00003895
3896 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
3897 // The supertype is either verified, or we soft failed at AOT time.
3898 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07003899 return true;
3900 }
3901 // If we got this far then we have a hard failure.
3902 std::string error_msg =
3903 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07003904 klass->PrettyDescriptor().c_str(),
3905 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07003906 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003907 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07003908 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003909 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003910 // Set during VerifyClass call (if at all).
3911 self->ClearException();
3912 }
3913 // Change into a verify error.
3914 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08003915 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003916 self->GetException()->SetCause(cause.Get());
3917 }
3918 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
3919 if (Runtime::Current()->IsAotCompiler()) {
3920 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3921 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07003922 // Need to grab the lock to change status.
3923 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko72ab6842017-01-20 19:32:50 +00003924 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07003925 return false;
3926}
3927
Andreas Gampecc1b5352016-12-01 16:58:38 -08003928// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
3929// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
3930// before.
3931static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
3932 REQUIRES_SHARED(Locks::mutator_lock_) {
3933 if (!klass->WasVerificationAttempted()) {
3934 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
3935 klass->SetVerificationAttempted();
3936 }
3937}
3938
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07003939verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01003940 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07003941 {
3942 // TODO: assert that the monitor on the Class is held
3943 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003944
Andreas Gampe884f3b82016-03-30 19:52:58 -07003945 // Is somebody verifying this now?
3946 mirror::Class::Status old_status = klass->GetStatus();
3947 while (old_status == mirror::Class::kStatusVerifying ||
3948 old_status == mirror::Class::kStatusVerifyingAtRuntime) {
3949 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07003950 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
3951 // case we may see the same status again. b/62912904. This is why the check is
3952 // greater or equal.
3953 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07003954 << "Class '" << klass->PrettyClass()
3955 << "' performed an illegal verification state transition from " << old_status
3956 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003957 old_status = klass->GetStatus();
3958 }
jeffhao98eacac2011-09-14 16:11:53 -07003959
Andreas Gampe884f3b82016-03-30 19:52:58 -07003960 // The class might already be erroneous, for example at compile time if we attempted to verify
3961 // this class as a parent to another.
3962 if (klass->IsErroneous()) {
3963 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07003964 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07003965 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003966
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00003967 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07003968 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003969 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07003970 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07003971 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00003972
3973 // For AOT, don't attempt to re-verify if we have already found we should
3974 // verify at runtime.
3975 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07003976 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07003977 }
jeffhao98eacac2011-09-14 16:11:53 -07003978
Andreas Gampe884f3b82016-03-30 19:52:58 -07003979 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
3980 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
3981 } else {
3982 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07003983 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003984 CHECK(!Runtime::Current()->IsAotCompiler());
3985 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
3986 }
3987
3988 // Skip verification if disabled.
3989 if (!Runtime::Current()->IsVerificationEnabled()) {
3990 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003991 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07003992 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07003993 }
Jeff Hao4a200f52014-04-01 14:58:49 -07003994 }
3995
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07003996 VLOG(class_linker) << "Beginning verification for class: "
3997 << klass->PrettyDescriptor()
3998 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
3999
Ian Rogers9ffb0392012-09-10 11:56:50 -07004000 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004001 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004002 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4003 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004004 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004005 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004006 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004007 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004008
Alex Lightf1f10492015-10-07 16:08:36 -07004009 // Verify all default super-interfaces.
4010 //
4011 // (1) Don't bother if the superclass has already had a soft verification failure.
4012 //
4013 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4014 // recursive initialization by themselves. This is because when an interface is initialized
4015 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4016 // but choose not to for an optimization. If the interfaces is being verified due to a class
4017 // initialization (which would need all the default interfaces to be verified) the class code
4018 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004019 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004020 && !klass->IsInterface()) { // See (2)
4021 int32_t iftable_count = klass->GetIfTableCount();
4022 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4023 // Loop through all interfaces this class has defined. It doesn't matter the order.
4024 for (int32_t i = 0; i < iftable_count; i++) {
4025 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004026 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004027 // We only care if we have default interfaces and can skip if we are already verified...
4028 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4029 continue;
4030 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4031 // We had a hard failure while verifying this interface. Just return immediately.
4032 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004033 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004034 } else if (UNLIKELY(!iface->IsVerified())) {
4035 // We softly failed to verify the iface. Stop checking and clean up.
4036 // Put the iface into the supertype handle so we know what caused us to fail.
4037 supertype.Assign(iface.Get());
4038 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004039 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004040 }
4041 }
4042
Alex Lightf1f10492015-10-07 16:08:36 -07004043 // At this point if verification failed, then supertype is the "first" supertype that failed
4044 // verification (without a specific order). If verification succeeded, then supertype is either
4045 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004046 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004047 supertype.Get() == klass->GetSuperClass() ||
4048 !supertype->IsVerified());
4049
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004050 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004051 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004052 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004053 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004054
4055 VLOG(class_linker) << "Class preverified status for class "
4056 << klass->PrettyDescriptor()
4057 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4058 << ": "
4059 << preverified;
4060
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004061 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4062 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004063 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4064 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004065
Ian Rogers62d6c772013-02-27 08:32:07 -08004066 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004067 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004068 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004069 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004070 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004071
4072 // Verification is done, grab the lock again.
4073 ObjectLock<mirror::Class> lock(self, klass);
4074
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004075 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4076 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004077 VLOG(class_linker) << "Soft verification failure in class "
4078 << klass->PrettyDescriptor()
4079 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4080 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004081 }
Ian Rogers1f539342012-10-03 21:09:42 -07004082 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004083 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004084 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004085 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004086 // Even though there were no verifier failures we need to respect whether the super-class and
4087 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004088 if (supertype == nullptr || supertype->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004089 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004090 } else {
Alex Lightf1f10492015-10-07 16:08:36 -07004091 CHECK_EQ(supertype->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004092 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004093 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004094 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004095 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004096 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004097 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004098 // Soft failures at compile time should be retried at runtime. Soft
4099 // failures at runtime will be handled by slow paths in the generated
4100 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004101 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004102 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004103 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004104 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004105 // As this is a fake verified status, make sure the methods are _not_ marked
4106 // kAccSkipAccessChecks later.
4107 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004108 }
4109 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004110 } else {
David Sehr709b0702016-10-13 09:12:37 -07004111 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004112 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4113 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004114 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004115 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko72ab6842017-01-20 19:32:50 +00004116 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004117 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004118 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004119 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004120 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004121 // method.
4122 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004123 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004124 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004125
4126 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4127 // Never skip access checks if the verification soft fail is forced.
4128 // Mark the class as having a verification attempt to avoid re-running the verifier.
4129 klass->SetVerificationAttempted();
4130 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004131 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004132 }
Andreas Gampe48498592014-09-10 19:48:05 -07004133 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004134 // Done verifying. Notify the compiler about the verification status, in case the class
4135 // was verified implicitly (eg super class of a compiled class).
4136 if (Runtime::Current()->IsAotCompiler()) {
4137 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4138 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4139 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004140 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004141}
4142
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004143verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4144 Handle<mirror::Class> klass,
4145 verifier::HardFailLogMode log_level,
4146 std::string* error_msg) {
4147 Runtime* const runtime = Runtime::Current();
4148 return verifier::MethodVerifier::VerifyClass(self,
4149 klass.Get(),
4150 runtime->GetCompilerCallbacks(),
4151 runtime->IsAotCompiler(),
4152 log_level,
4153 error_msg);
4154}
4155
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004156bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004157 ObjPtr<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004158 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004159 // If we're compiling, we can only verify the class using the oat file if
4160 // we are not compiling the image or if the class we're verifying is not part of
4161 // the app. In other words, we will only check for preverification of bootclasspath
4162 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004163 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004164 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07004165 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004166 return false;
4167 }
4168 // We are compiling an app (not the image).
4169
4170 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004171 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004172 return false;
4173 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004174 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004175
Richard Uhler07b3c232015-03-31 15:57:54 -07004176 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004177 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004178 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004179 return false;
4180 }
4181
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004182 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004183 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Jeff Hao0cb17282017-07-12 14:51:49 -07004184 if (oat_file_class_status >= mirror::Class::kStatusVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004185 return true;
4186 }
4187 // If we only verified a subset of the classes at compile time, we can end up with classes that
4188 // were resolved by the verifier.
4189 if (oat_file_class_status == mirror::Class::kStatusResolved) {
4190 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004191 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004192 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004193 // Compile time verification failed with a soft error. Compile time verification can fail
4194 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004195 // class ... {
4196 // Foo x;
4197 // .... () {
4198 // if (...) {
4199 // v1 gets assigned a type of resolved class Foo
4200 // } else {
4201 // v1 gets assigned a type of unresolved class Bar
4202 // }
4203 // iput x = v1
4204 // } }
4205 // when we merge v1 following the if-the-else it results in Conflict
4206 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4207 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4208 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4209 // at compile time).
4210 return false;
4211 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004212 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004213 // Compile time verification failed with a hard error. This is caused by invalid instructions
4214 // in the class. These errors are unrecoverable.
4215 return false;
4216 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004217 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004218 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4219 // not loading the class.
4220 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4221 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004222 return false;
4223 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004224 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004225 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004226 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004227 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004228 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004229}
4230
Alex Light5a559862016-01-29 12:24:48 -08004231void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004232 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004233 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004234 }
4235}
4236
Alex Light5a559862016-01-29 12:24:48 -08004237void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004238 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
Alex Light5a559862016-01-29 12:24:48 -08004239 const DexFile::CodeItem* code_item =
4240 method->GetDexFile()->GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004241 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004242 return; // native or abstract method
4243 }
4244 if (code_item->tries_size_ == 0) {
4245 return; // nothing to process
4246 }
Ian Rogers13735952014-10-08 12:43:28 -07004247 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004248 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004249 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4250 CatchHandlerIterator iterator(handlers_ptr);
4251 for (; iterator.HasNext(); iterator.Next()) {
4252 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4253 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004254 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004255 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004256 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004257 DCHECK(Thread::Current()->IsExceptionPending());
4258 Thread::Current()->ClearException();
4259 }
4260 }
4261 }
4262 handlers_ptr = iterator.EndDataPointer();
4263 }
4264}
4265
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004266mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4267 jstring name,
4268 jobjectArray interfaces,
4269 jobject loader,
4270 jobjectArray methods,
4271 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004272 Thread* self = soa.Self();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004273 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004274 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004275 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004276 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004277 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004278 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004279 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004280 DCHECK(temp_klass->GetClass() != nullptr);
4281 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004282 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4283 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004284 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4285 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4286 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4287 temp_klass->SetName(soa.Decode<mirror::String>(name));
4288 temp_klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004289 // Object has an empty iftable, copy it for that reason.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004290 temp_klass->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
4291 mirror::Class::SetStatus(temp_klass, mirror::Class::kStatusIdx, self);
4292 std::string descriptor(GetDescriptorForProxy(temp_klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004293 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004294
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004295 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004296 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004297
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004298 // Insert the class before loading the fields as the field roots
4299 // (ArtField::declaring_class_) are only visited from the class
4300 // table. There can't be any suspend points between inserting the
4301 // class and setting the field arrays below.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004302 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004303 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004304
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004305 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004306 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004307 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004308 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004309
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004310 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4311 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004312 ArtField& interfaces_sfield = sfields->At(0);
4313 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004314 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004315 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004316
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004317 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004318 ArtField& throws_sfield = sfields->At(1);
4319 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004320 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004321 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004322
Ian Rogers466bb252011-10-14 03:29:56 -07004323 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004324 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004325
Alex Lighte64300b2015-12-15 15:02:47 -08004326 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004327 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004328 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
David Sehr709b0702016-10-13 09:12:37 -07004329 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004330 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004331
4332 // Create the methods array.
4333 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4334 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004335 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4336 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004337 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004338 self->AssertPendingOOMException();
4339 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004340 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004341 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004342
4343 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004344 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004345
4346 // Create virtual method using specified prototypes.
4347 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004348 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004349 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004350 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004351 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004352 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4353 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004354 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004355
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004356 // The super class is java.lang.reflect.Proxy
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004357 temp_klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004358 // Now effectively in the loaded state.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004359 mirror::Class::SetStatus(temp_klass, mirror::Class::kStatusLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004360 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004361
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004362 // At this point the class is loaded. Publish a ClassLoad event.
4363 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4364 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4365
4366 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004367 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004368 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004369 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004370 // Link the fields and virtual methods, creating vtable and iftables.
4371 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004372 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004373 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004374 if (!LinkClass(self, descriptor.c_str(), temp_klass, h_interfaces, &klass)) {
4375 mirror::Class::SetStatus(temp_klass, mirror::Class::kStatusErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004376 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004377 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004378 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004379 CHECK(temp_klass->IsRetired());
4380 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004381
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004382 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004383 interfaces_sfield.SetObject<false>(
4384 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004385 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004386 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4387 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004388 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004389 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004390
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004391 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4392
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004393 {
4394 // Lock on klass is released. Lock new class object.
4395 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004396 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004397 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004398
4399 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004400 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004401 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004402 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4403
Ian Rogersc2b44472011-12-14 21:17:17 -08004404 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004405 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4406 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004407 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004408 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004409
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004410 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004411 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004412 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004413 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004414 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004415
4416 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004417 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004418 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004419
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004420 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004421 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004422 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004423 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004424 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004425 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004426}
4427
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004428std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004429 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004430 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004431 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004432 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4433}
4434
Mathieu Chartiere401d142015-04-22 13:56:20 -07004435void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4436 // Create constructor for Proxy that must initialize the method.
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004437 CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 23u);
4438
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004439 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4440 // on which front-end compiler was used to build the libcore DEX files.
Vladimir Markoba118822017-06-12 15:41:56 +01004441 ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->FindConstructor(
4442 "(Ljava/lang/reflect/InvocationHandler;)V", image_pointer_size_);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004443 DCHECK(proxy_constructor != nullptr)
4444 << "Could not find <init> method in java.lang.reflect.Proxy";
4445
Jeff Haodb8a6642014-08-14 17:18:52 -07004446 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4447 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004448 DCHECK(out != nullptr);
4449 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004450 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004451 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004452 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004453 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4454 kAccPublic |
4455 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004456 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004457
4458 // Set the original constructor method.
4459 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004460}
4461
Mathieu Chartiere401d142015-04-22 13:56:20 -07004462void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004463 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004464 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4465 CHECK_STREQ(np->GetName(), "<init>");
4466 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004467 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004468}
4469
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004470void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004471 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004472 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004473 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004474 DCHECK(out != nullptr);
4475 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004476
Alex Lighte9dd04f2016-03-16 16:09:45 -07004477 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004478 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004479 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4480 // preference to the invocation handler.
4481 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4482 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004483 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4484 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004485 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4486
4487 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4488 // method they copy might (if it's a default method).
4489 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004490
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004491 // Set the original interface method.
4492 out->SetDataPtrSize(prototype, image_pointer_size_);
4493
Ian Rogers466bb252011-10-14 03:29:56 -07004494 // At runtime the method looks like a reference and argument saving method, clone the code
4495 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004496 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004497}
Jesse Wilson95caa792011-10-12 18:14:17 -04004498
Mathieu Chartiere401d142015-04-22 13:56:20 -07004499void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004500 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004501 CHECK(!prototype->IsFinal());
4502 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004503 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004504
4505 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4506 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08004507 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01004508 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004509}
4510
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004511bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004512 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004513 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004514 return true;
4515 }
4516 if (!can_init_statics) {
4517 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004518 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004519 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004520 return false;
4521 }
4522 // Check if there are encoded static values needing initialization.
4523 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004524 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004525 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004526 if (dex_class_def->static_values_off_ != 0) {
4527 return false;
4528 }
4529 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004530 // If we are a class we need to initialize all interfaces with default methods when we are
4531 // initialized. Check all of them.
4532 if (!klass->IsInterface()) {
4533 size_t num_interfaces = klass->GetIfTableCount();
4534 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004535 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07004536 if (iface->HasDefaultMethods() &&
4537 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
4538 return false;
4539 }
4540 }
4541 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004542 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004543 if (klass->IsInterface() || !klass->HasSuperClass()) {
4544 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004545 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004546 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07004547 if (!can_init_parents && !super_class->IsInitialized()) {
4548 return false;
4549 }
4550 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004551}
4552
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004553bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
4554 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004555 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4556
4557 // Are we already initialized and therefore done?
4558 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4559 // an initialized class will never change its state.
4560 if (klass->IsInitialized()) {
4561 return true;
4562 }
4563
4564 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004565 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004566 return false;
4567 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004568
Ian Rogers7b078e82014-09-10 14:44:24 -07004569 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004570 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004571 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004572 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004573
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004574 // Re-check under the lock in case another thread initialized ahead of us.
4575 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004576 return true;
4577 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004578
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004579 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004580 if (klass->IsErroneous()) {
Andreas Gampecb086952015-11-02 16:20:00 -08004581 ThrowEarlierClassFailure(klass.Get(), true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07004582 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004583 return false;
4584 }
4585
Vladimir Marko72ab6842017-01-20 19:32:50 +00004586 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
4587 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004588
4589 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004590 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004591 if (!klass->IsVerified()) {
4592 // We failed to verify, expect either the klass to be erroneous or verification failed at
4593 // compile time.
4594 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07004595 // The class is erroneous. This may be a verifier error, or another thread attempted
4596 // verification and/or initialization and failed. We can distinguish those cases by
4597 // whether an exception is already pending.
4598 if (self->IsExceptionPending()) {
4599 // Check that it's a VerifyError.
4600 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07004601 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07004602 } else {
4603 // Check that another thread attempted initialization.
4604 DCHECK_NE(0, klass->GetClinitThreadId());
4605 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
4606 // Need to rethrow the previous failure now.
4607 ThrowEarlierClassFailure(klass.Get(), true);
4608 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07004609 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004610 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004611 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004612 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004613 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004614 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004615 } else {
4616 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004617 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07004618
4619 // A separate thread could have moved us all the way to initialized. A "simple" example
4620 // involves a subclass of the current class being initialized at the same time (which
4621 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00004622 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07004623 if (klass->IsInitialized()) {
4624 return true;
4625 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004626 }
4627
Brian Carlstromd1422f82011-09-28 11:37:09 -07004628 // If the class is kStatusInitializing, either this thread is
4629 // initializing higher up the stack or another thread has beat us
4630 // to initializing and we need to wait. Either way, this
4631 // invocation of InitializeClass will not be responsible for
4632 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004633 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004634 // Could have got an exception during verification.
4635 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004636 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004637 return false;
4638 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004639 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004640 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004641 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004642 return true;
4643 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004644 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004645 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004646 }
4647
Jeff Haoe2e40342017-07-19 10:45:18 -07004648 // Try to get the oat class's status for this class if the oat file is present. The compiler
4649 // tries to validate superclass descriptors, and writes the result into the oat file.
4650 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
4651 // is different at runtime than it was at compile time, the oat file is rejected. So if the
4652 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07004653 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07004654 const Runtime* runtime = Runtime::Current();
4655 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
4656 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
4657 : OatFile::OatClass::Invalid();
Jeff Hao0cb17282017-07-12 14:51:49 -07004658 if (oat_class.GetStatus() < mirror::Class::kStatusSuperclassValidated &&
4659 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00004660 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004661 return false;
4662 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004663 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004664
David Sehr709b0702016-10-13 09:12:37 -07004665 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07004666 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004667
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004668 // From here out other threads may observe that we're initializing and so changes of state
4669 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004670 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004671 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004672
4673 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004674 }
4675
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004676 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004677 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004678 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004679 if (!super_class->IsInitialized()) {
4680 CHECK(!super_class->IsInterface());
4681 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004682 StackHandleScope<1> hs(self);
4683 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004684 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004685 if (!super_initialized) {
4686 // The super class was verified ahead of entering initializing, we should only be here if
4687 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07004688 // For the case of aot compiler, the super class might also be initializing but we don't
4689 // want to process circular dependencies in pre-compile.
4690 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004691 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07004692 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004693 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004694 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004695 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004696 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004697 // Initialization failed because the super-class is erroneous.
Vladimir Marko72ab6842017-01-20 19:32:50 +00004698 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004699 return false;
4700 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004701 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004702 }
4703
Alex Lighteb7c1442015-08-31 13:17:42 -07004704 if (!klass->IsInterface()) {
4705 // Initialize interfaces with default methods for the JLS.
4706 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004707 // Only setup the (expensive) handle scope if we actually need to.
4708 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07004709 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07004710 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
4711 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004712 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004713 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004714 CHECK(handle_scope_iface->IsInterface());
4715 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
4716 // We have already done this for this interface. Skip it.
4717 continue;
4718 }
4719 // We cannot just call initialize class directly because we need to ensure that ALL
4720 // interfaces with default methods are initialized. Non-default interface initialization
4721 // will not affect other non-default super-interfaces.
4722 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
4723 handle_scope_iface,
4724 can_init_statics,
4725 can_init_parents);
4726 if (!iface_initialized) {
4727 ObjectLock<mirror::Class> lock(self, klass);
4728 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko72ab6842017-01-20 19:32:50 +00004729 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07004730 return false;
4731 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004732 }
4733 }
4734 }
4735
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004736 const size_t num_static_fields = klass->NumStaticFields();
4737 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004738 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004739 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004740 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004741 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004742 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004743 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004744
4745 // Eagerly fill in static fields so that the we don't have to do as many expensive
4746 // Class::FindStaticField in ResolveField.
4747 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004748 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004749 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004750 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004751 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004752 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004753 } else {
4754 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004755 }
4756 }
4757
David Sehr9323e6e2016-09-13 08:58:35 -07004758 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_file,
4759 &dex_cache,
4760 &class_loader,
4761 this,
4762 *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004763 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004764 ClassDataItemIterator field_it(dex_file, class_data);
4765 if (value_it.HasNext()) {
4766 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004767 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004768 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004769 ArtField* field = ResolveField(
4770 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004771 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004772 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004773 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004774 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004775 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07004776 if (self->IsExceptionPending()) {
4777 break;
4778 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004779 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004780 }
4781 }
4782 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004783
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004784
Mathieu Chartierda595be2016-08-10 13:57:39 -07004785 if (!self->IsExceptionPending()) {
4786 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4787 if (clinit != nullptr) {
4788 CHECK(can_init_statics);
4789 JValue result;
4790 clinit->Invoke(self, nullptr, 0, &result, "V");
4791 }
4792 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004793 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004794 uint64_t t1 = NanoTime();
4795
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004796 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004797 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004798 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004799
4800 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004801 WrapExceptionInInitializer(klass);
Vladimir Marko72ab6842017-01-20 19:32:50 +00004802 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004803 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004804 } else if (Runtime::Current()->IsTransactionAborted()) {
4805 // The exception thrown when the transaction aborted has been caught and cleared
4806 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07004807 VLOG(compiler) << "Return from class initializer of "
4808 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01004809 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02004810 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko72ab6842017-01-20 19:32:50 +00004811 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004812 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004813 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004814 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4815 RuntimeStats* thread_stats = self->GetStats();
4816 ++global_stats->class_init_count;
4817 ++thread_stats->class_init_count;
4818 global_stats->class_init_time_ns += (t1 - t0);
4819 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004820 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004821 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004822 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004823 std::string temp;
4824 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004825 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004826 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004827 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004828 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004829 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004830 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004831 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004832}
4833
Alex Lighteb7c1442015-08-31 13:17:42 -07004834// We recursively run down the tree of interfaces. We need to do this in the order they are declared
4835// and perform the initialization only on those interfaces that contain default methods.
4836bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
4837 Handle<mirror::Class> iface,
4838 bool can_init_statics,
4839 bool can_init_parents) {
4840 CHECK(iface->IsInterface());
4841 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004842 // Only create the (expensive) handle scope if we need it.
4843 if (UNLIKELY(num_direct_ifaces > 0)) {
4844 StackHandleScope<1> hs(self);
4845 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
4846 // First we initialize all of iface's super-interfaces recursively.
4847 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004848 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004849 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004850 if (!super_iface->HasBeenRecursivelyInitialized()) {
4851 // Recursive step
4852 handle_super_iface.Assign(super_iface);
4853 if (!InitializeDefaultInterfaceRecursive(self,
4854 handle_super_iface,
4855 can_init_statics,
4856 can_init_parents)) {
4857 return false;
4858 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004859 }
4860 }
4861 }
4862
4863 bool result = true;
4864 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
4865 // initialize if we don't have default methods.
4866 if (iface->HasDefaultMethods()) {
4867 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
4868 }
4869
4870 // Mark that this interface has undergone recursive default interface initialization so we know we
4871 // can skip it on any later class initializations. We do this even if we are not a default
4872 // interface since we can still avoid the traversal. This is purely a performance optimization.
4873 if (result) {
4874 // TODO This should be done in a better way
4875 ObjectLock<mirror::Class> lock(self, iface);
4876 iface->SetRecursivelyInitialized();
4877 }
4878 return result;
4879}
4880
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004881bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
4882 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004883 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004884 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004885 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004886 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004887 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004888 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004889
4890 // When we wake up, repeat the test for init-in-progress. If
4891 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004892 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004893 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004894 WrapExceptionInInitializer(klass);
Vladimir Marko72ab6842017-01-20 19:32:50 +00004895 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004896 return false;
4897 }
4898 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004899 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004900 continue;
4901 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004902 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
4903 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004904 // Compile time initialization failed.
4905 return false;
4906 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004907 if (klass->IsErroneous()) {
4908 // The caller wants an exception, but it was thrown in a
4909 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004910 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07004911 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004912 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004913 return false;
4914 }
4915 if (klass->IsInitialized()) {
4916 return true;
4917 }
David Sehr709b0702016-10-13 09:12:37 -07004918 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004919 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004920 }
Ian Rogers07140832014-09-30 15:43:59 -07004921 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004922}
4923
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004924static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
4925 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004926 ArtMethod* method,
4927 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004928 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004929 DCHECK(Thread::Current()->IsExceptionPending());
4930 DCHECK(!m->IsProxyMethod());
4931 const DexFile* dex_file = m->GetDexFile();
4932 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
4933 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08004934 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07004935 std::string return_type = dex_file->PrettyType(return_type_idx);
4936 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004937 ThrowWrappedLinkageError(klass.Get(),
4938 "While checking class %s method %s signature against %s %s: "
4939 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07004940 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
4941 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004942 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07004943 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004944 return_type.c_str(), class_loader.c_str());
4945}
4946
4947static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
4948 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004949 ArtMethod* method,
4950 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004951 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08004952 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004953 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004954 DCHECK(Thread::Current()->IsExceptionPending());
4955 DCHECK(!m->IsProxyMethod());
4956 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07004957 std::string arg_type = dex_file->PrettyType(arg_type_idx);
4958 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004959 ThrowWrappedLinkageError(klass.Get(),
4960 "While checking class %s method %s signature against %s %s: "
4961 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07004962 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
4963 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004964 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07004965 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004966 index, arg_type.c_str(), class_loader.c_str());
4967}
4968
4969static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
4970 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004971 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004972 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004973 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004974 ThrowLinkageError(klass.Get(),
4975 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07004976 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
4977 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004978 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07004979 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004980 error_msg.c_str());
4981}
4982
Ian Rogersb5fb2072014-12-02 17:22:02 -08004983static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004984 Handle<mirror::Class> klass,
4985 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004986 ArtMethod* method1,
4987 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004988 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004989 {
4990 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01004991 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004992 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004993 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004994 return false;
4995 }
Vladimir Markob45528c2017-07-27 14:14:28 +01004996 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004997 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004998 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004999 return false;
5000 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005001 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005002 ThrowSignatureMismatch(klass, super_klass, method1,
5003 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005004 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005005 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005006 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005007 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005008 return false;
5009 }
5010 }
5011 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
5012 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
5013 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005014 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005015 ThrowSignatureMismatch(klass, super_klass, method1,
5016 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005017 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005018 return false;
5019 }
5020 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005021 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005022 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005023 ThrowSignatureMismatch(klass, super_klass, method1,
5024 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005025 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005026 return false;
5027 }
5028 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005029 }
5030 uint32_t num_types = types1->Size();
5031 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005032 ThrowSignatureMismatch(klass, super_klass, method1,
5033 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005034 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005035 return false;
5036 }
5037 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005038 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005039 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005040 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005041 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005042 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005043 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005044 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005045 return false;
5046 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005047 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005048 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005049 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005050 if (UNLIKELY(other_param_type == nullptr)) {
5051 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005052 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005053 return false;
5054 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005055 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005056 ThrowSignatureMismatch(klass, super_klass, method1,
5057 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5058 i,
David Sehr709b0702016-10-13 09:12:37 -07005059 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005060 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005061 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005062 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005063 return false;
5064 }
5065 }
5066 return true;
5067}
5068
5069
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005070bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005071 if (klass->IsInterface()) {
5072 return true;
5073 }
Ian Rogers151f2212014-05-06 11:27:27 -07005074 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005075 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005076 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005077 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005078 if (klass->HasSuperClass() &&
5079 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005080 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005081 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005082 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5083 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5084 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005085 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5086 klass,
5087 super_klass,
5088 m,
5089 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005090 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005091 return false;
5092 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005093 }
5094 }
5095 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005096 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005097 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5098 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5099 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005100 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005101 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5102 j, image_pointer_size_);
5103 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5104 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005105 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5106 klass,
5107 super_klass,
5108 m,
5109 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005110 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005111 return false;
5112 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005113 }
5114 }
5115 }
5116 }
5117 return true;
5118}
5119
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005120bool ClassLinker::EnsureInitialized(Thread* self,
5121 Handle<mirror::Class> c,
5122 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005123 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005124 DCHECK(c != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005125 if (c->IsInitialized()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08005126 EnsureSkipAccessChecksMethods(c, image_pointer_size_);
Mathieu Chartier8502f722016-06-08 15:09:08 -07005127 self->AssertNoPendingException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005128 return true;
5129 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005130 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005131 if (!success) {
5132 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005133 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005134 }
5135 } else {
5136 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005137 }
5138 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005139}
5140
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005141void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5142 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005143 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005144 for (ArtField& field : new_class->GetIFields()) {
5145 if (field.GetDeclaringClass() == temp_class) {
5146 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005147 }
5148 }
5149
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005150 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005151 for (ArtField& field : new_class->GetSFields()) {
5152 if (field.GetDeclaringClass() == temp_class) {
5153 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005154 }
5155 }
5156
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005157 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005158 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005159 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005160 if (method.GetDeclaringClass() == temp_class) {
5161 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005162 }
5163 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005164
5165 // Make sure the remembered set and mod-union tables know that we updated some of the native
5166 // roots.
5167 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005168}
5169
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005170void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005171 CHECK(class_loader->GetAllocator() == nullptr);
5172 CHECK(class_loader->GetClassTable() == nullptr);
5173 Thread* const self = Thread::Current();
5174 ClassLoaderData data;
5175 data.weak_root = self->GetJniEnv()->vm->AddWeakGlobalRef(self, class_loader);
5176 // Create and set the class table.
5177 data.class_table = new ClassTable;
5178 class_loader->SetClassTable(data.class_table);
5179 // Create and set the linear allocator.
5180 data.allocator = Runtime::Current()->CreateLinearAlloc();
5181 class_loader->SetAllocator(data.allocator);
5182 // Add to the list so that we know to free the data later.
5183 class_loaders_.push_back(data);
5184}
5185
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005186ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005187 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005188 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005189 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005190 ClassTable* class_table = class_loader->GetClassTable();
5191 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005192 RegisterClassLoader(class_loader);
5193 class_table = class_loader->GetClassTable();
5194 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005195 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005196 return class_table;
5197}
5198
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005199ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005200 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005201}
5202
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005203static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005204 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005205 while (klass->HasSuperClass()) {
5206 klass = klass->GetSuperClass();
5207 if (klass->ShouldHaveImt()) {
5208 return klass->GetImt(pointer_size);
5209 }
5210 }
5211 return nullptr;
5212}
5213
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005214bool ClassLinker::LinkClass(Thread* self,
5215 const char* descriptor,
5216 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005217 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005218 MutableHandle<mirror::Class>* h_new_class_out) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005219 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005220
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005221 if (!LinkSuperClass(klass)) {
5222 return false;
5223 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005224 ArtMethod* imt_data[ImTable::kSize];
5225 // If there are any new conflicts compared to super class.
5226 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005227 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005228 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005229 return false;
5230 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005231 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005232 return false;
5233 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005234 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005235 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005236 return false;
5237 }
5238 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005239 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005240
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005241 ImTable* imt = nullptr;
5242 if (klass->ShouldHaveImt()) {
5243 // If there are any new conflicts compared to the super class we can not make a copy. There
5244 // can be cases where both will have a conflict method at the same slot without having the same
5245 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5246 // will possibly create a table that is incorrect for either of the classes.
5247 // Same IMT with new_conflict does not happen very often.
5248 if (!new_conflict) {
5249 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5250 if (super_imt != nullptr) {
5251 bool imt_equals = true;
5252 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5253 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5254 }
5255 if (imt_equals) {
5256 imt = super_imt;
5257 }
5258 }
5259 }
5260 if (imt == nullptr) {
5261 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5262 imt = reinterpret_cast<ImTable*>(
5263 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5264 if (imt == nullptr) {
5265 return false;
5266 }
5267 imt->Populate(imt_data, image_pointer_size_);
5268 }
5269 }
5270
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005271 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5272 // We don't need to retire this class as it has no embedded tables or it was created the
5273 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005274 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005275
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005276 if (klass->ShouldHaveEmbeddedVTable()) {
5277 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005278 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005279 if (klass->ShouldHaveImt()) {
5280 klass->SetImt(imt, image_pointer_size_);
5281 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005282
5283 // Update CHA info based on whether we override methods.
5284 // Have to do this before setting the class as resolved which allows
5285 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005286 if (cha_ != nullptr) {
5287 cha_->UpdateAfterLoadingOf(klass);
5288 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005289
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005290 // This will notify waiters on klass that saw the not yet resolved
5291 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07005292 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005293 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005294 } else {
5295 CHECK(!klass->IsResolved());
5296 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005297 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005298 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005299 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5300 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5301 // may not see any references to the target space and clean the card for a class if another
5302 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005303 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005304 klass->SetSFieldsPtrUnchecked(nullptr);
5305 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005306 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005307 self->AssertPendingOOMException();
Vladimir Marko72ab6842017-01-20 19:32:50 +00005308 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005309 return false;
5310 }
5311
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005312 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5313 ObjectLock<mirror::Class> lock(self, h_new_class);
5314 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005315
5316 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005317 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005318 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005319 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005320 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005321 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005322 if (class_loader != nullptr) {
5323 // We updated the class in the class table, perform the write barrier so that the GC knows
5324 // about the change.
5325 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
5326 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005327 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005328 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005329 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5330 }
5331 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005332
Mingyao Yang063fc772016-08-02 11:02:54 -07005333 // Update CHA info based on whether we override methods.
5334 // Have to do this before setting the class as resolved which allows
5335 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005336 if (cha_ != nullptr) {
5337 cha_->UpdateAfterLoadingOf(h_new_class);
5338 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005339
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005340 // This will notify waiters on temp class that saw the not yet resolved class in the
5341 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07005342 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005343
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005344 CHECK_EQ(h_new_class->GetStatus(), mirror::Class::kStatusResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005345 // This will notify waiters on new_class that saw the not yet resolved
5346 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005347 mirror::Class::SetStatus(h_new_class, mirror::Class::kStatusResolved, self);
5348 // Return the new class.
5349 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005350 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005351 return true;
5352}
5353
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005354bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005355 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005356 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005357 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5358 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005359 // Check that a class does not inherit from itself directly.
5360 //
5361 // TODO: This is a cheap check to detect the straightforward case
5362 // of a class extending itself (b/28685551), but we should do a
5363 // proper cycle detection on loaded classes, to detect all cases
5364 // of class circularity errors (b/28830038).
5365 if (super_class_idx == class_def.class_idx_) {
5366 ThrowClassCircularityError(klass.Get(),
5367 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005368 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005369 return false;
5370 }
5371
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005372 ObjPtr<mirror::Class> super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005373 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005374 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005375 return false;
5376 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005377 // Verify
5378 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005379 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005380 super_class->PrettyDescriptor().c_str(),
5381 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005382 return false;
5383 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005384 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005385 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005386 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005387 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005388 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005389 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005390 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005391 ObjPtr<mirror::Class> interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005392 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005393 DCHECK(Thread::Current()->IsExceptionPending());
5394 return false;
5395 }
5396 // Verify
5397 if (!klass->CanAccess(interface)) {
5398 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005399 ThrowIllegalAccessError(klass.Get(),
5400 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005401 interface->PrettyDescriptor().c_str(),
5402 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005403 return false;
5404 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005405 }
5406 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005407 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07005408 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005409 return true;
5410}
5411
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005412bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005413 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005414 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005415 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005416 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005417 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005418 return false;
5419 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005420 return true;
5421 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005422 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005423 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005424 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005425 return false;
5426 }
5427 // Verify
Vladimir Markob43b2d82017-07-18 17:46:38 +01005428 if (super->IsFinal()) {
5429 ThrowVerifyError(klass.Get(),
5430 "Superclass %s of %s is declared final",
5431 super->PrettyDescriptor().c_str(),
5432 klass->PrettyDescriptor().c_str());
5433 return false;
5434 }
5435 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005436 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005437 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005438 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005439 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005440 return false;
5441 }
5442 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005443 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005444 super->PrettyDescriptor().c_str(),
5445 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005446 return false;
5447 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005448
Brian Carlstromf3632832014-05-20 15:36:53 -07005449 // Inherit kAccClassIsFinalizable from the superclass in case this
5450 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005451 if (super->IsFinalizable()) {
5452 klass->SetFinalizable();
5453 }
5454
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005455 // Inherit class loader flag form super class.
5456 if (super->IsClassLoaderClass()) {
5457 klass->SetClassLoaderClass();
5458 }
5459
Elliott Hughes2da50362011-10-10 16:57:08 -07005460 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005461 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005462 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005463 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005464 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005465 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005466 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07005467 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005468 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005469 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005470 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005471 return false;
5472 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005473
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005474 if (kIsDebugBuild) {
5475 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005476 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005477 CHECK(super->IsResolved());
5478 super = super->GetSuperClass();
5479 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005480 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005481 return true;
5482}
5483
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005484// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005485bool ClassLinker::LinkMethods(Thread* self,
5486 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005487 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005488 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005489 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005490 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005491 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5492 // need to have default methods be in the virtuals array of each class but we don't set that up
5493 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07005494 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07005495 // Link virtual methods then interface methods.
5496 // We set up the interface lookup table first because we need it to determine if we need to update
5497 // any vtable entries with new default method implementations.
5498 return SetupInterfaceLookupTable(self, klass, interfaces)
5499 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005500 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005501}
5502
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005503// Comparator for name and signature of a method, used in finding overriding methods. Implementation
5504// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
5505// caches in the implementation below.
5506class MethodNameAndSignatureComparator FINAL : public ValueObject {
5507 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005508 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005509 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005510 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
5511 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07005512 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005513 }
5514
5515 const char* GetName() {
5516 if (name_ == nullptr) {
5517 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
5518 }
5519 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005520 }
5521
Mathieu Chartiere401d142015-04-22 13:56:20 -07005522 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005523 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07005524 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005525 const DexFile* other_dex_file = other->GetDexFile();
5526 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
5527 if (dex_file_ == other_dex_file) {
5528 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
5529 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005530 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005531 uint32_t other_name_len;
5532 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
5533 &other_name_len);
5534 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
5535 return false;
5536 }
5537 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
5538 }
5539
5540 private:
5541 // Dex file for the method to compare against.
5542 const DexFile* const dex_file_;
5543 // MethodId for the method to compare against.
5544 const DexFile::MethodId* const mid_;
5545 // Lazily computed name from the dex file's strings.
5546 const char* name_;
5547 // Lazily computed name length.
5548 uint32_t name_len_;
5549};
5550
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005551class LinkVirtualHashTable {
5552 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005553 LinkVirtualHashTable(Handle<mirror::Class> klass,
5554 size_t hash_size,
5555 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07005556 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005557 : klass_(klass),
5558 hash_size_(hash_size),
5559 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07005560 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005561 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
5562 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005563
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005564 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005565 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
5566 virtual_method_index, image_pointer_size_);
5567 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005568 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005569 uint32_t index = hash % hash_size_;
5570 // Linear probe until we have an empty slot.
5571 while (hash_table_[index] != invalid_index_) {
5572 if (++index == hash_size_) {
5573 index = 0;
5574 }
5575 }
5576 hash_table_[index] = virtual_method_index;
5577 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005578
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005579 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005580 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005581 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005582 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005583 size_t index = hash % hash_size_;
5584 while (true) {
5585 const uint32_t value = hash_table_[index];
5586 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
5587 // the block and can safely assume not found.
5588 if (value == invalid_index_) {
5589 break;
5590 }
5591 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005592 ArtMethod* virtual_method =
5593 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
5594 if (comparator->HasSameNameAndSignature(
5595 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005596 hash_table_[index] = removed_index_;
5597 return value;
5598 }
5599 }
5600 if (++index == hash_size_) {
5601 index = 0;
5602 }
5603 }
5604 return GetNotFoundIndex();
5605 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005606
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005607 static uint32_t GetNotFoundIndex() {
5608 return invalid_index_;
5609 }
5610
5611 private:
5612 static const uint32_t invalid_index_;
5613 static const uint32_t removed_index_;
5614
5615 Handle<mirror::Class> klass_;
5616 const size_t hash_size_;
5617 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07005618 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005619};
5620
5621const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
5622const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
5623
Stephen Hines1ddd9132017-02-08 01:51:18 -08005624bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07005625 Thread* self,
5626 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07005627 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005628 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07005629 if (klass->IsInterface()) {
5630 // No vtable.
5631 if (!IsUint<16>(num_virtual_methods)) {
5632 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
5633 return false;
5634 }
5635 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07005636 // Assign each method an IMT index and set the default flag.
5637 for (size_t i = 0; i < num_virtual_methods; ++i) {
5638 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5639 m->SetMethodIndex(i);
5640 if (!m->IsAbstract()) {
5641 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
5642 has_defaults = true;
5643 }
5644 }
5645 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
5646 // during initialization. This is a performance optimization. We could simply traverse the
5647 // virtual_methods_ array again during initialization.
5648 if (has_defaults) {
5649 klass->SetHasDefaultMethods();
5650 }
5651 return true;
5652 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005653 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
5654 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005655 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07005656 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07005657 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005658 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005659 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005660 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005661 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005662 return false;
5663 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005664 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005665 vtable->SetElementPtrSize(
5666 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005667 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005668 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5669 // might give us new default methods). If no new interfaces then we can skip the rest since
5670 // the class cannot override any of the super-class's methods. This is required for
5671 // correctness since without it we might not update overridden default method vtable entries
5672 // correctly.
5673 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005674 klass->SetVTable(vtable.Get());
5675 return true;
5676 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005677 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07005678 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005679 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07005680 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07005681 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5682 // might give us new default methods). See comment above.
5683 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005684 klass->SetVTable(super_vtable);
5685 return true;
5686 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005687 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
5688 super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005689 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005690 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005691 return false;
5692 }
Ian Rogersa436fde2013-08-27 23:34:06 -07005693 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005694 // How the algorithm works:
5695 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
5696 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
5697 // method which has not been matched to a vtable method, and j if the virtual method at the
5698 // index overrode the super virtual method at index j.
5699 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
5700 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
5701 // the need for the initial vtable which we later shrink back down).
5702 // 3. Add non overridden methods to the end of the vtable.
5703 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07005704 // + 1 so that even if we only have new default methods we will still be able to use this hash
5705 // table (i.e. it will never have 0 size).
5706 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005707 uint32_t* hash_table_ptr;
5708 std::unique_ptr<uint32_t[]> hash_heap_storage;
5709 if (hash_table_size <= kMaxStackHash) {
5710 hash_table_ptr = reinterpret_cast<uint32_t*>(
5711 alloca(hash_table_size * sizeof(*hash_table_ptr)));
5712 } else {
5713 hash_heap_storage.reset(new uint32_t[hash_table_size]);
5714 hash_table_ptr = hash_heap_storage.get();
5715 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005716 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005717 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005718 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005719 DCHECK(klass->GetVirtualMethodDuringLinking(
5720 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005721 hash_table.Add(i);
5722 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005723 // 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 -07005724 // the hash table.
5725 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005726 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005727 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005728 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
5729 super_method->GetAccessFlags())) {
5730 // Continue on to the next method since this one is package private and canot be overridden.
5731 // Before Android 4.1, the package-private method super_method might have been incorrectly
5732 // overridden.
5733 continue;
5734 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005735 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005736 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07005737 // We remove the method so that subsequent lookups will be faster by making the hash-map
5738 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005739 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5740 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005741 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
5742 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005743 if (super_method->IsFinal()) {
5744 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5745 virtual_method->PrettyMethod().c_str(),
5746 super_method->GetDeclaringClassDescriptor());
5747 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005748 }
Alex Lightc7a420c2016-10-18 14:33:18 -07005749 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
5750 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07005751 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005752 // We didn't directly override this method but we might through default methods...
5753 // Check for default method update.
5754 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07005755 switch (FindDefaultMethodImplementation(self,
5756 super_method,
5757 klass,
5758 /*out*/&default_method)) {
5759 case DefaultMethodSearchResult::kDefaultConflict: {
5760 // A conflict was found looking for default methods. Note this (assuming it wasn't
5761 // pre-existing) in the translations map.
5762 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
5763 // Don't generate another conflict method to reduce memory use as an optimization.
5764 default_translations->insert(
5765 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
5766 }
5767 break;
5768 }
5769 case DefaultMethodSearchResult::kAbstractFound: {
5770 // No conflict but method is abstract.
5771 // We note that this vtable entry must be made abstract.
5772 if (UNLIKELY(!super_method->IsAbstract())) {
5773 default_translations->insert(
5774 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
5775 }
5776 break;
5777 }
5778 case DefaultMethodSearchResult::kDefaultFound: {
5779 if (UNLIKELY(super_method->IsDefaultConflicting() ||
5780 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
5781 // Found a default method implementation that is new.
5782 // TODO Refactor this add default methods to virtuals here and not in
5783 // LinkInterfaceMethods maybe.
5784 // The problem is default methods might override previously present
5785 // default-method or miranda-method vtable entries from the superclass.
5786 // Unfortunately we need these to be entries in this class's virtuals. We do not
5787 // give these entries there until LinkInterfaceMethods so we pass this map around
5788 // to let it know which vtable entries need to be updated.
5789 // Make a note that vtable entry j must be updated, store what it needs to be updated
5790 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
5791 // then.
5792 default_translations->insert(
5793 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07005794 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
5795 << " overridden by default "
5796 << default_method->PrettyMethod()
5797 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07005798 }
5799 break;
5800 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005801 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005802 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005803 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005804 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07005805 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005806 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005807 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005808 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5809 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07005810 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005811 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005812 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005813 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005814 local_method->SetMethodIndex(actual_count);
5815 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005816 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005817 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005818 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005819 return false;
5820 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005821 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005822 CHECK_LE(actual_count, max_count);
5823 if (actual_count < max_count) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005824 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005825 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005826 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005827 return false;
5828 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005829 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005830 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005831 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005832 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005833 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005834 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5835 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005836 return false;
5837 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005838 auto* vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005839 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005840 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005841 return false;
5842 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005843 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005844 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5845 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005846 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005847 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005848 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005849 }
5850 return true;
5851}
5852
Alex Light9139e002015-10-09 15:59:48 -07005853// Determine if the given iface has any subinterface in the given list that declares the method
5854// specified by 'target'.
5855//
5856// Arguments
5857// - self: The thread we are running on
5858// - target: A comparator that will match any method that overrides the method we are checking for
5859// - iftable: The iftable we are searching for an overriding method on.
5860// - ifstart: The index of the interface we are checking to see if anything overrides
5861// - iface: The interface we are checking to see if anything overrides.
5862// - image_pointer_size:
5863// The image pointer size.
5864//
5865// Returns
5866// - True: There is some method that matches the target comparator defined in an interface that
5867// is a subtype of iface.
5868// - False: There is no method that matches the target comparator in any interface that is a subtype
5869// of iface.
5870static bool ContainsOverridingMethodOf(Thread* self,
5871 MethodNameAndSignatureComparator& target,
5872 Handle<mirror::IfTable> iftable,
5873 size_t ifstart,
5874 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07005875 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005876 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07005877 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005878 DCHECK(iface != nullptr);
5879 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07005880 DCHECK_GE(ifstart, 0u);
5881 DCHECK_LT(ifstart, iftable->Count());
5882 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
5883 DCHECK(iface->IsInterface());
5884
5885 size_t iftable_count = iftable->Count();
5886 StackHandleScope<1> hs(self);
5887 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
5888 for (size_t k = ifstart + 1; k < iftable_count; k++) {
5889 // Skip ifstart since our current interface obviously cannot override itself.
5890 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08005891 // Iterate through every method on this interface. The order does not matter.
5892 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07005893 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08005894 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07005895 // Check if the i'th interface is a subtype of this one.
5896 if (iface->IsAssignableFrom(current_iface.Get())) {
5897 return true;
5898 }
5899 break;
5900 }
5901 }
5902 }
5903 return false;
5904}
5905
Alex Lighteb7c1442015-08-31 13:17:42 -07005906// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07005907// out_default_method and returns kDefaultFound on success. If no default method was found return
5908// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
5909// default_method conflict) it will return kDefaultConflict.
5910ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
5911 Thread* self,
5912 ArtMethod* target_method,
5913 Handle<mirror::Class> klass,
5914 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07005915 DCHECK(self != nullptr);
5916 DCHECK(target_method != nullptr);
5917 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07005918
5919 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07005920
5921 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
5922 // table. This lets us walk the table backwards when searching for default methods. The first one
5923 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
5924 // track of it and then continue checking all other interfaces, since we need to throw an error if
5925 // we encounter conflicting default method implementations (one is not a subtype of the other).
5926 //
5927 // The order of unrelated interfaces does not matter and is not defined.
5928 size_t iftable_count = klass->GetIfTableCount();
5929 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07005930 // No interfaces. We have already reset out to null so just return kAbstractFound.
5931 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07005932 }
5933
Alex Light9139e002015-10-09 15:59:48 -07005934 StackHandleScope<3> hs(self);
5935 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07005936 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07005937 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07005938 MethodNameAndSignatureComparator target_name_comparator(
5939 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
5940 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07005941 for (size_t k = iftable_count; k != 0; ) {
5942 --k;
5943
Alex Lighteb7c1442015-08-31 13:17:42 -07005944 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07005945
5946 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08005947 // Iterate through every declared method on this interface. The order does not matter.
5948 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
5949 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07005950 // Skip abstract methods and methods with different names.
5951 if (current_method->IsAbstract() ||
5952 !target_name_comparator.HasSameNameAndSignature(
5953 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
5954 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07005955 } else if (!current_method->IsPublic()) {
5956 // The verifier should have caught the non-public method for dex version 37. Just warn and
5957 // skip it since this is from before default-methods so we don't really need to care that it
5958 // has code.
David Sehr709b0702016-10-13 09:12:37 -07005959 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
5960 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07005961 << "This will be a fatal error in subsequent versions of android. "
5962 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07005963 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08005964 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07005965 // We have multiple default impls of the same method. This is a potential default conflict.
5966 // We need to check if this possibly conflicting method is either a superclass of the chosen
5967 // default implementation or is overridden by a non-default interface method. In either case
5968 // there is no conflict.
5969 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
5970 !ContainsOverridingMethodOf(self,
5971 target_name_comparator,
5972 iftable,
5973 k,
5974 iface,
5975 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00005976 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07005977 << current_method->PrettyMethod() << " and "
5978 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
5979 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07005980 *out_default_method = nullptr;
5981 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07005982 } else {
5983 break; // Continue checking at the next interface.
5984 }
5985 } else {
Alex Light9139e002015-10-09 15:59:48 -07005986 // chosen_iface == null
5987 if (!ContainsOverridingMethodOf(self,
5988 target_name_comparator,
5989 iftable,
5990 k,
5991 iface,
5992 image_pointer_size_)) {
5993 // Don't set this as the chosen interface if something else is overriding it (because that
5994 // other interface would be potentially chosen instead if it was default). If the other
5995 // interface was abstract then we wouldn't select this interface as chosen anyway since
5996 // the abstract method masks it.
5997 *out_default_method = current_method;
5998 chosen_iface.Assign(iface.Get());
5999 // We should now finish traversing the graph to find if we have default methods that
6000 // conflict.
6001 } else {
David Sehr709b0702016-10-13 09:12:37 -07006002 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6003 << "' was "
6004 << "skipped because it was overridden by an abstract method in a "
6005 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006006 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006007 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006008 break;
6009 }
6010 }
Alex Light9139e002015-10-09 15:59:48 -07006011 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006012 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6013 << "' selected "
6014 << "as the implementation for '" << target_method->PrettyMethod()
6015 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006016 return DefaultMethodSearchResult::kDefaultFound;
6017 } else {
6018 return DefaultMethodSearchResult::kAbstractFound;
6019 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006020}
6021
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006022ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006023 ArtMethod* conflict_method,
6024 ArtMethod* interface_method,
6025 ArtMethod* method,
6026 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006027 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006028 Runtime* const runtime = Runtime::Current();
6029 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6030 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6031
6032 // Create a new entry if the existing one is the shared conflict method.
6033 ArtMethod* new_conflict_method = new_entry
6034 ? runtime->CreateImtConflictMethod(linear_alloc)
6035 : conflict_method;
6036
6037 // Allocate a new table. Note that we will leak this table at the next conflict,
6038 // but that's a tradeoff compared to making the table fixed size.
6039 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006040 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6041 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006042 if (data == nullptr) {
6043 LOG(ERROR) << "Failed to allocate conflict table";
6044 return conflict_method;
6045 }
6046 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6047 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006048 method,
6049 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006050
6051 // Do a fence to ensure threads see the data in the table before it is assigned
6052 // to the conflict method.
6053 // Note that there is a race in the presence of multiple threads and we may leak
6054 // memory from the LinearAlloc, but that's a tradeoff compared to using
6055 // atomic operations.
6056 QuasiAtomic::ThreadFenceRelease();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006057 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006058 return new_conflict_method;
6059}
6060
Vladimir Marko921094a2017-01-12 18:37:06 +00006061bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6062 Handle<mirror::Class> klass,
6063 Handle<mirror::IfTable> iftable) {
6064 DCHECK(!klass->IsInterface());
6065 const bool has_superclass = klass->HasSuperClass();
6066 const bool extend_super_iftable = has_superclass;
6067 const size_t ifcount = klass->GetIfTableCount();
6068 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6069 for (size_t i = 0; i < ifcount; ++i) {
6070 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6071 if (num_methods > 0) {
6072 const bool is_super = i < super_ifcount;
6073 // This is an interface implemented by a super-class. Therefore we can just copy the method
6074 // array from the superclass.
6075 const bool super_interface = is_super && extend_super_iftable;
6076 ObjPtr<mirror::PointerArray> method_array;
6077 if (super_interface) {
6078 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6079 DCHECK(if_table != nullptr);
6080 DCHECK(if_table->GetMethodArray(i) != nullptr);
6081 // If we are working on a super interface, try extending the existing method array.
6082 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
6083 } else {
6084 method_array = AllocPointerArray(self, num_methods);
6085 }
6086 if (UNLIKELY(method_array == nullptr)) {
6087 self->AssertPendingOOMException();
6088 return false;
6089 }
6090 iftable->SetMethodArray(i, method_array);
6091 }
6092 }
6093 return true;
6094}
6095
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006096void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6097 ArtMethod* imt_conflict_method,
6098 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006099 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006100 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006101 // Place method in imt if entry is empty, place conflict otherwise.
6102 if (*imt_ref == unimplemented_method) {
6103 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006104 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006105 // If we are not a conflict and we have the same signature and name as the imt
6106 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006107 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6108 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006109 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006110 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006111 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006112 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006113 *imt_ref = current_method;
6114 } else {
Alex Light9139e002015-10-09 15:59:48 -07006115 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006116 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006117 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006118 } else {
6119 // Place the default conflict method. Note that there may be an existing conflict
6120 // method in the IMT, but it could be one tailored to the super class, with a
6121 // specific ImtConflictTable.
6122 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006123 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006124 }
6125}
6126
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006127void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006128 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6129 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006130 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006131 Runtime* const runtime = Runtime::Current();
6132 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6133 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006134 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006135 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006136 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006137 FillIMTFromIfTable(klass->GetIfTable(),
6138 unimplemented_method,
6139 conflict_method,
6140 klass,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006141 /*create_conflict_tables*/true,
6142 /*ignore_copied_methods*/false,
6143 &new_conflict,
6144 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006145 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006146 if (!klass->ShouldHaveImt()) {
6147 return;
6148 }
6149 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6150 // we can just use the same pointer.
6151 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006152 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006153 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6154 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6155 bool same = true;
6156 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6157 ArtMethod* method = imt_data[i];
6158 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6159 if (method != super_method) {
6160 bool is_conflict_table = method->IsRuntimeMethod() &&
6161 method != unimplemented_method &&
6162 method != conflict_method;
6163 // Verify conflict contents.
6164 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6165 super_method != unimplemented_method &&
6166 super_method != conflict_method;
6167 if (!is_conflict_table || !super_conflict_table) {
6168 same = false;
6169 } else {
6170 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6171 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6172 same = same && table1->Equals(table2, image_pointer_size_);
6173 }
6174 }
6175 }
6176 if (same) {
6177 imt = super_imt;
6178 }
6179 }
6180 if (imt == nullptr) {
6181 imt = klass->GetImt(image_pointer_size_);
6182 DCHECK(imt != nullptr);
6183 imt->Populate(imt_data, image_pointer_size_);
6184 } else {
6185 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006186 }
6187}
6188
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006189ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6190 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006191 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006192 void* data = linear_alloc->Alloc(Thread::Current(),
6193 ImtConflictTable::ComputeSize(count,
6194 image_pointer_size));
6195 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6196}
6197
6198ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6199 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6200}
6201
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006202void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006203 ArtMethod* unimplemented_method,
6204 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006205 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006206 bool create_conflict_tables,
6207 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006208 /*out*/bool* new_conflict,
6209 /*out*/ArtMethod** imt) {
6210 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006211 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006212 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006213 const size_t num_virtuals = interface->NumVirtualMethods();
6214 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6215 // Virtual methods can be larger than the if table methods if there are default methods.
6216 DCHECK_GE(num_virtuals, method_array_count);
6217 if (kIsDebugBuild) {
6218 if (klass->IsInterface()) {
6219 DCHECK_EQ(method_array_count, 0u);
6220 } else {
6221 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6222 }
6223 }
6224 if (method_array_count == 0) {
6225 continue;
6226 }
6227 auto* method_array = if_table->GetMethodArray(i);
6228 for (size_t j = 0; j < method_array_count; ++j) {
6229 ArtMethod* implementation_method =
6230 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6231 if (ignore_copied_methods && implementation_method->IsCopied()) {
6232 continue;
6233 }
6234 DCHECK(implementation_method != nullptr);
6235 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6236 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6237 // or interface methods in the IMT here they will not create extra conflicts since we compare
6238 // names and signatures in SetIMTRef.
6239 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006240 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006241
6242 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6243 // the same implementation method, keep track of this to avoid creating a conflict table in
6244 // this case.
6245
6246 // Conflict table size for each IMT slot.
6247 ++conflict_counts[imt_index];
6248
6249 SetIMTRef(unimplemented_method,
6250 imt_conflict_method,
6251 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006252 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006253 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006254 }
6255 }
6256
6257 if (create_conflict_tables) {
6258 // Create the conflict tables.
6259 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006260 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006261 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006262 if (imt[i] == imt_conflict_method) {
6263 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6264 if (new_table != nullptr) {
6265 ArtMethod* new_conflict_method =
6266 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6267 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6268 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006269 } else {
6270 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006271 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006272 }
6273 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006274 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006275 }
6276 }
6277
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006278 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006279 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006280 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6281 // Virtual methods can be larger than the if table methods if there are default methods.
6282 if (method_array_count == 0) {
6283 continue;
6284 }
6285 auto* method_array = if_table->GetMethodArray(i);
6286 for (size_t j = 0; j < method_array_count; ++j) {
6287 ArtMethod* implementation_method =
6288 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6289 if (ignore_copied_methods && implementation_method->IsCopied()) {
6290 continue;
6291 }
6292 DCHECK(implementation_method != nullptr);
6293 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006294 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006295 if (!imt[imt_index]->IsRuntimeMethod() ||
6296 imt[imt_index] == unimplemented_method ||
6297 imt[imt_index] == imt_conflict_method) {
6298 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006299 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006300 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6301 const size_t num_entries = table->NumEntries(image_pointer_size_);
6302 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6303 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006304 }
6305 }
6306 }
6307}
6308
Alex Lighteb7c1442015-08-31 13:17:42 -07006309// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6310// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006311static bool NotSubinterfaceOfAny(
6312 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6313 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006314 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006315 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006316 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006317 for (ObjPtr<mirror::Class> c : classes) {
6318 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006319 return false;
6320 }
6321 }
6322 return true;
6323}
6324
6325// Fills in and flattens the interface inheritance hierarchy.
6326//
6327// By the end of this function all interfaces in the transitive closure of to_process are added to
6328// the iftable and every interface precedes all of its sub-interfaces in this list.
6329//
6330// all I, J: Interface | I <: J implies J precedes I
6331//
6332// (note A <: B means that A is a subtype of B)
6333//
6334// This returns the total number of items in the iftable. The iftable might be resized down after
6335// this call.
6336//
6337// We order this backwards so that we do not need to reorder superclass interfaces when new
6338// interfaces are added in subclass's interface tables.
6339//
6340// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6341// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6342// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6343// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006344static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006345 size_t super_ifcount,
6346 std::vector<mirror::Class*> to_process)
6347 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006348 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006349 // This is the set of all class's already in the iftable. Used to make checking if a class has
6350 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006351 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006352 // The first super_ifcount elements are from the superclass. We note that they are already added.
6353 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006354 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006355 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6356 classes_in_iftable.insert(iface);
6357 }
6358 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006359 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006360 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6361 // At this point in the loop current-iface-list has the invariant that:
6362 // for every pair of interfaces I,J within it:
6363 // if index_of(I) < index_of(J) then I is not a subtype of J
6364
6365 // If we have already seen this element then all of its super-interfaces must already be in the
6366 // current-iface-list so we can skip adding it.
6367 if (!ContainsElement(classes_in_iftable, interface)) {
6368 // We haven't seen this interface so add all of its super-interfaces onto the
6369 // current-iface-list, skipping those already on it.
6370 int32_t ifcount = interface->GetIfTableCount();
6371 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006372 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006373 if (!ContainsElement(classes_in_iftable, super_interface)) {
6374 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6375 classes_in_iftable.insert(super_interface);
6376 iftable->SetInterface(filled_ifcount, super_interface);
6377 filled_ifcount++;
6378 }
6379 }
6380 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6381 // Place this interface onto the current-iface-list after all of its super-interfaces.
6382 classes_in_iftable.insert(interface);
6383 iftable->SetInterface(filled_ifcount, interface);
6384 filled_ifcount++;
6385 } else if (kIsDebugBuild) {
6386 // Check all super-interfaces are already in the list.
6387 int32_t ifcount = interface->GetIfTableCount();
6388 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006389 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006390 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006391 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6392 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006393 }
6394 }
6395 }
6396 if (kIsDebugBuild) {
6397 // Check that the iftable is ordered correctly.
6398 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006399 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006400 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006401 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006402 // !(if_a <: if_b)
6403 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006404 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6405 << ") extends "
6406 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006407 << "interface list.";
6408 }
6409 }
6410 }
6411 return filled_ifcount;
6412}
6413
6414bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6415 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6416 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006417 const bool has_superclass = klass->HasSuperClass();
6418 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006419 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006420 const size_t num_interfaces =
6421 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006422 if (num_interfaces == 0) {
6423 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006424 if (LIKELY(has_superclass)) {
6425 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6426 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006427 // Class implements no interfaces.
6428 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006429 return true;
6430 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006431 // Class implements same interfaces as parent, are any of these not marker interfaces?
6432 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006433 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006434 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006435 if (super_iftable->GetMethodArrayCount(i) > 0) {
6436 has_non_marker_interface = true;
6437 break;
6438 }
6439 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006440 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006441 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006442 klass->SetIfTable(super_iftable);
6443 return true;
6444 }
6445 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006446 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006447 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006448 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006449 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006450 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006451 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006452 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006453 if (UNLIKELY(!interface->IsInterface())) {
6454 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006455 ThrowIncompatibleClassChangeError(klass.Get(),
6456 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006457 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006458 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6459 return false;
6460 }
6461 ifcount += interface->GetIfTableCount();
6462 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006463 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006464 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006465 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006466 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006467 return false;
6468 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006469 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006470 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006471 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006472 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006473 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006474 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006475 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006476 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006477
6478 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6479 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6480 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006481 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006482
6483 size_t new_ifcount;
6484 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006485 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Alex Lighteb7c1442015-08-31 13:17:42 -07006486 std::vector<mirror::Class*> to_add;
6487 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006488 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006489 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006490 to_add.push_back(interface.Ptr());
Ian Rogersb52b01a2012-01-12 17:01:38 -08006491 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006492
6493 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006494 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006495
Ian Rogers7b078e82014-09-10 14:44:24 -07006496 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006497
Ian Rogersb52b01a2012-01-12 17:01:38 -08006498 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07006499 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006500 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006501 iftable.Assign(down_cast<mirror::IfTable*>(
Alex Lighteb7c1442015-08-31 13:17:42 -07006502 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006503 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006504 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006505 return false;
6506 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006507 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08006508 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006509 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006510 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006511 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07006512 return true;
6513}
6514
Alex Light1f3925d2016-09-07 12:04:20 -07006515// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
6516// of methods must be unique.
6517static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
6518 return nullptr;
6519}
6520
6521template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07006522static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07006523 const ScopedArenaVector<ArtMethod*>& list,
6524 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006525 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006526 for (ArtMethod* method : list) {
6527 if (cmp.HasSameNameAndSignature(method)) {
6528 return method;
6529 }
6530 }
Alex Light1f3925d2016-09-07 12:04:20 -07006531 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07006532}
6533
Alex Light1f3925d2016-09-07 12:04:20 -07006534// Check that all vtable entries are present in this class's virtuals or are the same as a
6535// superclasses vtable entry.
6536static void CheckClassOwnsVTableEntries(Thread* self,
6537 Handle<mirror::Class> klass,
6538 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006539 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07006540 StackHandleScope<2> hs(self);
6541 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006542 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07006543 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006544 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006545 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6546 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6547 CHECK(m != nullptr);
6548
Alex Lighta41a30782017-03-29 11:33:19 -07006549 if (m->GetMethodIndexDuringLinking() != i) {
6550 LOG(WARNING) << m->PrettyMethod()
6551 << " has an unexpected method index for its spot in the vtable for class"
6552 << klass->PrettyClass();
6553 }
Alex Lighte64300b2015-12-15 15:02:47 -08006554 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6555 auto is_same_method = [m] (const ArtMethod& meth) {
6556 return &meth == m;
6557 };
Alex Light3f980532017-03-17 15:10:32 -07006558 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6559 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
6560 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
6561 << klass->PrettyClass() << " or any of its superclasses!";
6562 }
Alex Lighte64300b2015-12-15 15:02:47 -08006563 }
6564}
6565
Alex Light1f3925d2016-09-07 12:04:20 -07006566// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
6567// method is overridden in a subclass.
6568static void CheckVTableHasNoDuplicates(Thread* self,
6569 Handle<mirror::Class> klass,
6570 PointerSize pointer_size)
6571 REQUIRES_SHARED(Locks::mutator_lock_) {
6572 StackHandleScope<1> hs(self);
6573 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6574 int32_t num_entries = vtable->GetLength();
6575 for (int32_t i = 0; i < num_entries; i++) {
6576 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6577 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe).
6578 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6579 vtable_entry->GetAccessFlags())) {
6580 continue;
6581 }
6582 MethodNameAndSignatureComparator name_comparator(
6583 vtable_entry->GetInterfaceMethodIfProxy(pointer_size));
Alex Lightc7a420c2016-10-18 14:33:18 -07006584 for (int32_t j = i + 1; j < num_entries; j++) {
Alex Light1f3925d2016-09-07 12:04:20 -07006585 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Alex Lightc7a420c2016-10-18 14:33:18 -07006586 if (!klass->CanAccessMember(other_entry->GetDeclaringClass(),
6587 other_entry->GetAccessFlags())) {
6588 continue;
6589 }
Alex Light3f980532017-03-17 15:10:32 -07006590 if (vtable_entry == other_entry ||
6591 name_comparator.HasSameNameAndSignature(
6592 other_entry->GetInterfaceMethodIfProxy(pointer_size))) {
6593 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
6594 << klass->PrettyClass() << " in method " << vtable_entry->PrettyMethod()
6595 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(vtable_entry) << ") and "
6596 << other_entry->PrettyMethod() << " (0x" << std::hex
6597 << reinterpret_cast<uintptr_t>(other_entry) << ")";
6598 }
Alex Light1f3925d2016-09-07 12:04:20 -07006599 }
6600 }
6601}
6602
6603static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
6604 REQUIRES_SHARED(Locks::mutator_lock_) {
6605 CheckClassOwnsVTableEntries(self, klass, pointer_size);
6606 CheckVTableHasNoDuplicates(self, klass, pointer_size);
6607}
6608
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006609void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
6610 ArtMethod* unimplemented_method,
6611 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006612 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006613 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07006614 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006615 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006616 if (super_class->ShouldHaveImt()) {
6617 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6618 for (size_t i = 0; i < ImTable::kSize; ++i) {
6619 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07006620 }
6621 } else {
6622 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006623 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08006624 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006625 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006626 FillIMTFromIfTable(if_table,
6627 unimplemented_method,
6628 imt_conflict_method,
6629 klass.Get(),
6630 /*create_conflict_table*/false,
6631 /*ignore_copied_methods*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006632 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006633 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07006634 }
6635 }
6636}
6637
Vladimir Marko921094a2017-01-12 18:37:06 +00006638class ClassLinker::LinkInterfaceMethodsHelper {
6639 public:
6640 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
6641 Handle<mirror::Class> klass,
6642 Thread* self,
6643 Runtime* runtime)
6644 : class_linker_(class_linker),
6645 klass_(klass),
6646 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
6647 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
6648 self_(self),
6649 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
6650 allocator_(&stack_),
6651 default_conflict_methods_(allocator_.Adapter()),
6652 overriding_default_conflict_methods_(allocator_.Adapter()),
6653 miranda_methods_(allocator_.Adapter()),
6654 default_methods_(allocator_.Adapter()),
6655 overriding_default_methods_(allocator_.Adapter()),
6656 move_table_(allocator_.Adapter()) {
6657 }
6658
6659 ArtMethod* FindMethod(ArtMethod* interface_method,
6660 MethodNameAndSignatureComparator& interface_name_comparator,
6661 ArtMethod* vtable_impl)
6662 REQUIRES_SHARED(Locks::mutator_lock_);
6663
6664 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
6665 MethodNameAndSignatureComparator& interface_name_comparator)
6666 REQUIRES_SHARED(Locks::mutator_lock_);
6667
6668 bool HasNewVirtuals() const {
6669 return !(miranda_methods_.empty() &&
6670 default_methods_.empty() &&
6671 overriding_default_methods_.empty() &&
6672 overriding_default_conflict_methods_.empty() &&
6673 default_conflict_methods_.empty());
6674 }
6675
6676 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
6677
6678 ObjPtr<mirror::PointerArray> UpdateVtable(
6679 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
6680 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
6681
6682 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
6683
6684 void UpdateIMT(ArtMethod** out_imt);
6685
6686 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
6687 if (kIsDebugBuild) {
6688 PointerSize pointer_size = class_linker_->GetImagePointerSize();
6689 // Check that there are no stale methods are in the dex cache array.
6690 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
6691 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01006692 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
6693 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00006694 CHECK(move_table_.find(m) == move_table_.end() ||
6695 // The original versions of copied methods will still be present so allow those too.
6696 // Note that if the first check passes this might fail to GetDeclaringClass().
6697 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
6698 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
6699 [m] (ArtMethod& meth) {
6700 return &meth == m;
6701 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
6702 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
6703 }
6704 }
6705 }
6706
6707 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
6708 LengthPrefixedArray<ArtMethod>* methods) {
6709 if (kIsDebugBuild) {
6710 CHECK(methods != nullptr);
6711 // Put some random garbage in old methods to help find stale pointers.
6712 if (methods != old_methods && old_methods != nullptr) {
6713 // Need to make sure the GC is not running since it could be scanning the methods we are
6714 // about to overwrite.
6715 ScopedThreadStateChange tsc(self_, kSuspended);
6716 gc::ScopedGCCriticalSection gcs(self_,
6717 gc::kGcCauseClassLinker,
6718 gc::kCollectorTypeClassLinker);
6719 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
6720 method_size_,
6721 method_alignment_);
6722 memset(old_methods, 0xFEu, old_size);
6723 }
6724 }
6725 }
6726
6727 private:
6728 size_t NumberOfNewVirtuals() const {
6729 return miranda_methods_.size() +
6730 default_methods_.size() +
6731 overriding_default_conflict_methods_.size() +
6732 overriding_default_methods_.size() +
6733 default_conflict_methods_.size();
6734 }
6735
6736 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
6737 return !klass_->IsInterface();
6738 }
6739
6740 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
6741 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
6742 << "Interfaces should only have default-conflict methods appended to them.";
6743 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
6744 << miranda_methods_.size()
6745 << " default_methods=" << default_methods_.size()
6746 << " overriding_default_methods=" << overriding_default_methods_.size()
6747 << " default_conflict_methods=" << default_conflict_methods_.size()
6748 << " overriding_default_conflict_methods="
6749 << overriding_default_conflict_methods_.size();
6750 }
6751
6752 ClassLinker* class_linker_;
6753 Handle<mirror::Class> klass_;
6754 size_t method_alignment_;
6755 size_t method_size_;
6756 Thread* const self_;
6757
6758 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
6759 // the virtual methods array.
6760 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
6761 // during cross compilation.
6762 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
6763 ArenaStack stack_;
6764 ScopedArenaAllocator allocator_;
6765
6766 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
6767 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
6768 ScopedArenaVector<ArtMethod*> miranda_methods_;
6769 ScopedArenaVector<ArtMethod*> default_methods_;
6770 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
6771
6772 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
6773};
6774
6775ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
6776 ArtMethod* interface_method,
6777 MethodNameAndSignatureComparator& interface_name_comparator,
6778 ArtMethod* vtable_impl) {
6779 ArtMethod* current_method = nullptr;
6780 switch (class_linker_->FindDefaultMethodImplementation(self_,
6781 interface_method,
6782 klass_,
6783 /*out*/&current_method)) {
6784 case DefaultMethodSearchResult::kDefaultConflict: {
6785 // Default method conflict.
6786 DCHECK(current_method == nullptr);
6787 ArtMethod* default_conflict_method = nullptr;
6788 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
6789 // We can reuse the method from the superclass, don't bother adding it to virtuals.
6790 default_conflict_method = vtable_impl;
6791 } else {
6792 // See if we already have a conflict method for this method.
6793 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
6794 interface_name_comparator,
6795 default_conflict_methods_,
6796 overriding_default_conflict_methods_);
6797 if (LIKELY(preexisting_conflict != nullptr)) {
6798 // We already have another conflict we can reuse.
6799 default_conflict_method = preexisting_conflict;
6800 } else {
6801 // Note that we do this even if we are an interface since we need to create this and
6802 // cannot reuse another classes.
6803 // Create a new conflict method for this to use.
6804 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6805 new(default_conflict_method) ArtMethod(interface_method,
6806 class_linker_->GetImagePointerSize());
6807 if (vtable_impl == nullptr) {
6808 // Save the conflict method. We need to add it to the vtable.
6809 default_conflict_methods_.push_back(default_conflict_method);
6810 } else {
6811 // Save the conflict method but it is already in the vtable.
6812 overriding_default_conflict_methods_.push_back(default_conflict_method);
6813 }
6814 }
6815 }
6816 current_method = default_conflict_method;
6817 break;
6818 } // case kDefaultConflict
6819 case DefaultMethodSearchResult::kDefaultFound: {
6820 DCHECK(current_method != nullptr);
6821 // Found a default method.
6822 if (vtable_impl != nullptr &&
6823 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
6824 // We found a default method but it was the same one we already have from our
6825 // superclass. Don't bother adding it to our vtable again.
6826 current_method = vtable_impl;
6827 } else if (LIKELY(FillTables())) {
6828 // Interfaces don't need to copy default methods since they don't have vtables.
6829 // Only record this default method if it is new to save space.
6830 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
6831 // would make lookup for interface super much faster. (We would only need to scan
6832 // the iftable to find if there is a NSME or AME.)
6833 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
6834 default_methods_,
6835 overriding_default_methods_);
6836 if (old == nullptr) {
6837 // We found a default method implementation and there were no conflicts.
6838 if (vtable_impl == nullptr) {
6839 // Save the default method. We need to add it to the vtable.
6840 default_methods_.push_back(current_method);
6841 } else {
6842 // Save the default method but it is already in the vtable.
6843 overriding_default_methods_.push_back(current_method);
6844 }
6845 } else {
6846 CHECK(old == current_method) << "Multiple default implementations selected!";
6847 }
6848 }
6849 break;
6850 } // case kDefaultFound
6851 case DefaultMethodSearchResult::kAbstractFound: {
6852 DCHECK(current_method == nullptr);
6853 // Abstract method masks all defaults.
6854 if (vtable_impl != nullptr &&
6855 vtable_impl->IsAbstract() &&
6856 !vtable_impl->IsDefaultConflicting()) {
6857 // We need to make this an abstract method but the version in the vtable already is so
6858 // don't do anything.
6859 current_method = vtable_impl;
6860 }
6861 break;
6862 } // case kAbstractFound
6863 }
6864 return current_method;
6865}
6866
6867ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
6868 ArtMethod* interface_method,
6869 MethodNameAndSignatureComparator& interface_name_comparator) {
6870 // Find out if there is already a miranda method we can use.
6871 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
6872 miranda_methods_);
6873 if (miranda_method == nullptr) {
6874 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
6875 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6876 CHECK(miranda_method != nullptr);
6877 // Point the interface table at a phantom slot.
6878 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
6879 miranda_methods_.push_back(miranda_method);
6880 }
6881 return miranda_method;
6882}
6883
6884void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
6885 LogNewVirtuals();
6886
6887 const size_t old_method_count = klass_->NumMethods();
6888 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
6889 DCHECK_NE(old_method_count, new_method_count);
6890
6891 // Attempt to realloc to save RAM if possible.
6892 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
6893 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
6894 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
6895 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
6896 // CopyFrom has internal read barriers.
6897 //
6898 // TODO We should maybe move some of this into mirror::Class or at least into another method.
6899 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
6900 method_size_,
6901 method_alignment_);
6902 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
6903 method_size_,
6904 method_alignment_);
6905 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
6906 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01006907 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00006908 self_, old_methods, old_methods_ptr_size, new_size));
6909 CHECK(methods != nullptr); // Native allocation failure aborts.
6910
6911 PointerSize pointer_size = class_linker_->GetImagePointerSize();
6912 if (methods != old_methods) {
6913 // Maps from heap allocated miranda method to linear alloc miranda method.
6914 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
6915 // Copy over the old methods.
6916 for (auto& m : klass_->GetMethods(pointer_size)) {
6917 move_table_.emplace(&m, &*out);
6918 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
6919 // barriers when it copies.
6920 out->CopyFrom(&m, pointer_size);
6921 ++out;
6922 }
6923 }
6924 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
6925 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
6926 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00006927 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
6928 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00006929 ArtMethod& new_method = *out;
6930 new_method.CopyFrom(mir_method, pointer_size);
6931 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
6932 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
6933 << "Miranda method should be abstract!";
6934 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00006935 // Update the entry in the method array, as the array will be used for future lookups,
6936 // where thread suspension is allowed.
6937 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
6938 // would not see them.
6939 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00006940 ++out;
6941 }
6942 // We need to copy the default methods into our own method table since the runtime requires that
6943 // every method on a class's vtable be in that respective class's virtual method table.
6944 // NOTE This means that two classes might have the same implementation of a method from the same
6945 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
6946 // default method found on a class with one found on the declaring interface directly and must
6947 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00006948 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
6949 &overriding_default_methods_}) {
6950 for (size_t i = 0; i < methods_vec->size(); ++i) {
6951 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00006952 ArtMethod& new_method = *out;
6953 new_method.CopyFrom(def_method, pointer_size);
6954 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
6955 // verified yet it shouldn't have methods that are skipping access checks.
6956 // TODO This is rather arbitrary. We should maybe support classes where only some of its
6957 // methods are skip_access_checks.
6958 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
6959 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
6960 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
6961 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00006962 // Update the entry in the method array, as the array will be used for future lookups,
6963 // where thread suspension is allowed.
6964 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
6965 // would not see them.
6966 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00006967 ++out;
6968 }
6969 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00006970 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
6971 &overriding_default_conflict_methods_}) {
6972 for (size_t i = 0; i < methods_vec->size(); ++i) {
6973 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00006974 ArtMethod& new_method = *out;
6975 new_method.CopyFrom(conf_method, pointer_size);
6976 // This is a type of default method (there are default method impls, just a conflict) so
6977 // mark this as a default, non-abstract method, since thats what it is. Also clear the
6978 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
6979 // methods that are skipping access checks.
6980 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
6981 constexpr uint32_t kMaskFlags = ~(kAccAbstract | kAccSkipAccessChecks);
6982 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
6983 DCHECK(new_method.IsDefaultConflicting());
6984 // The actual method might or might not be marked abstract since we just copied it from a
6985 // (possibly default) interface method. We need to set it entry point to be the bridge so
6986 // that the compiler will not invoke the implementation of whatever method we copied from.
6987 EnsureThrowsInvocationError(class_linker_, &new_method);
6988 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00006989 // Update the entry in the method array, as the array will be used for future lookups,
6990 // where thread suspension is allowed.
6991 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
6992 // would not see them.
6993 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00006994 ++out;
6995 }
6996 }
6997 methods->SetSize(new_method_count);
6998 class_linker_->UpdateClassMethods(klass_.Get(), methods);
6999}
7000
7001ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7002 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7003 ObjPtr<mirror::PointerArray> old_vtable) {
7004 // Update the vtable to the new method structures. We can skip this for interfaces since they
7005 // do not have vtables.
7006 const size_t old_vtable_count = old_vtable->GetLength();
7007 const size_t new_vtable_count = old_vtable_count +
7008 miranda_methods_.size() +
7009 default_methods_.size() +
7010 default_conflict_methods_.size();
7011
7012 ObjPtr<mirror::PointerArray> vtable =
7013 down_cast<mirror::PointerArray*>(old_vtable->CopyOf(self_, new_vtable_count));
7014 if (UNLIKELY(vtable == nullptr)) {
7015 self_->AssertPendingOOMException();
7016 return nullptr;
7017 }
7018
7019 size_t vtable_pos = old_vtable_count;
7020 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7021 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7022 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7023 default_conflict_methods_,
7024 miranda_methods_}) {
7025 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007026 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007027 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7028 // fields are references into the dex file the method was defined in. Since the ArtMethod
7029 // does not store that information it uses declaring_class_->dex_cache_.
7030 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7031 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7032 ++vtable_pos;
7033 }
7034 }
7035 DCHECK_EQ(vtable_pos, new_vtable_count);
7036
7037 // Update old vtable methods. We use the default_translations map to figure out what each
7038 // vtable entry should be updated to, if they need to be at all.
7039 for (size_t i = 0; i < old_vtable_count; ++i) {
7040 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7041 // Try and find what we need to change this method to.
7042 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007043 if (translation_it != default_translations.end()) {
7044 if (translation_it->second.IsInConflict()) {
7045 // Find which conflict method we are to use for this method.
7046 MethodNameAndSignatureComparator old_method_comparator(
7047 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7048 // We only need to look through overriding_default_conflict_methods since this is an
7049 // overridden method we are fixing up here.
7050 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7051 old_method_comparator, overriding_default_conflict_methods_);
7052 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7053 translated_method = new_conflict_method;
7054 } else if (translation_it->second.IsAbstract()) {
7055 // Find which miranda method we are to use for this method.
7056 MethodNameAndSignatureComparator old_method_comparator(
7057 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7058 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7059 miranda_methods_);
7060 DCHECK(miranda_method != nullptr);
7061 translated_method = miranda_method;
7062 } else {
7063 // Normal default method (changed from an older default or abstract interface method).
7064 DCHECK(translation_it->second.IsTranslation());
7065 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007066 auto it = move_table_.find(translated_method);
7067 DCHECK(it != move_table_.end());
7068 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007069 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007070 } else {
7071 auto it = move_table_.find(translated_method);
7072 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007073 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007074
7075 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007076 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007077 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007078 if (kIsDebugBuild) {
7079 auto* methods = klass_->GetMethodsPtr();
7080 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007081 reinterpret_cast<uintptr_t>(translated_method));
7082 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007083 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7084 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007085 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007086 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007087 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007088 }
7089 }
7090 klass_->SetVTable(vtable.Ptr());
7091 return vtable;
7092}
7093
7094void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7095 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7096 const size_t ifcount = klass_->GetIfTableCount();
7097 // Go fix up all the stale iftable pointers.
7098 for (size_t i = 0; i < ifcount; ++i) {
7099 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7100 auto* method_array = iftable->GetMethodArray(i);
7101 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7102 DCHECK(m != nullptr) << klass_->PrettyClass();
7103 auto it = move_table_.find(m);
7104 if (it != move_table_.end()) {
7105 auto* new_m = it->second;
7106 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7107 method_array->SetElementPtrSize(j, new_m, pointer_size);
7108 }
7109 }
7110 }
7111}
7112
7113void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7114 // Fix up IMT next.
7115 for (size_t i = 0; i < ImTable::kSize; ++i) {
7116 auto it = move_table_.find(out_imt[i]);
7117 if (it != move_table_.end()) {
7118 out_imt[i] = it->second;
7119 }
7120 }
7121}
7122
Alex Light705ad492015-09-21 11:36:30 -07007123// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007124bool ClassLinker::LinkInterfaceMethods(
7125 Thread* self,
7126 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007127 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007128 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007129 ArtMethod** out_imt) {
7130 StackHandleScope<3> hs(self);
7131 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007132
7133 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007134 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007135 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007136 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007137 const size_t ifcount = klass->GetIfTableCount();
7138
Vladimir Marko921094a2017-01-12 18:37:06 +00007139 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007140
7141 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7142 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007143 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007144 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007145 const bool extend_super_iftable = has_superclass;
7146 if (has_superclass && fill_tables) {
7147 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007148 unimplemented_method,
7149 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007150 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007151 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007152 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007153 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7154 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007155 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007156 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7157 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007158 }
7159 }
7160
Vladimir Marko921094a2017-01-12 18:37:06 +00007161 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7162
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007163 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007164 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007165 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7166 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7167 // they will already be null. This has the additional benefit that the declarer of a miranda
7168 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007169 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007170 --i;
Alex Light9139e002015-10-09 15:59:48 -07007171 DCHECK_LT(i, ifcount);
7172
Alex Light705ad492015-09-21 11:36:30 -07007173 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007174 if (num_methods > 0) {
7175 StackHandleScope<2> hs2(self);
7176 const bool is_super = i < super_ifcount;
7177 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007178 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7179 // conflict methods. Just set this as nullptr in those cases.
7180 Handle<mirror::PointerArray> method_array(fill_tables
7181 ? hs2.NewHandle(iftable->GetMethodArray(i))
7182 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007183
Alex Lighte64300b2015-12-15 15:02:47 -08007184 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007185 ScopedNullHandle<mirror::PointerArray> null_handle;
7186 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007187 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007188
Alex Light9139e002015-10-09 15:59:48 -07007189 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7190 // and confusing. Default methods should always look through all the superclasses
7191 // because they are the last choice of an implementation. We get around this by looking
7192 // at the super-classes iftable methods (copied into method_array previously) when we are
7193 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007194 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007195 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007196 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007197 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007198 using_virtuals = true;
7199 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7200 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007201 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007202 // For a new interface, however, we need the whole vtable in case a new
7203 // interface method is implemented in the whole superclass.
7204 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007205 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007206 input_vtable_array = vtable;
7207 input_array_length = input_vtable_array->GetLength();
7208 }
Alex Lighte64300b2015-12-15 15:02:47 -08007209
Alex Lighteb7c1442015-08-31 13:17:42 -07007210 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007211 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007212 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007213 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007214 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Andreas Gampe75a7db62016-09-26 12:04:26 -07007215 uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Alex Lighteb7c1442015-08-31 13:17:42 -07007216 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007217 // For each method listed in the interface's method list, find the
7218 // matching method in our class's method list. We want to favor the
7219 // subclass over the superclass, which just requires walking
7220 // back from the end of the vtable. (This only matters if the
7221 // superclass defines a private method and this class redefines
7222 // it -- otherwise it would use the same vtable slot. In .dex files
7223 // those don't end up in the virtual method table, so it shouldn't
7224 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007225 //
7226 // To find defaults we need to do the same but also go over interfaces.
7227 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007228 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007229 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007230 ArtMethod* vtable_method = using_virtuals ?
7231 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007232 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7233 ArtMethod* vtable_method_for_name_comparison =
7234 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007235 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007236 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007237 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007238 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7239 // allocations.
7240 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007241 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007242 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007243 vtable_method->PrettyMethod().c_str(),
7244 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007245 return false;
Alex Light9139e002015-10-09 15:59:48 -07007246 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007247 // We might have a newer, better, default method for this, so we just skip it. If we
7248 // are still using this we will select it again when scanning for default methods. To
7249 // obviate the need to copy the method again we will make a note that we already found
7250 // a default here.
7251 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007252 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007253 break;
7254 } else {
7255 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007256 if (LIKELY(fill_tables)) {
7257 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7258 // Place method in imt if entry is empty, place conflict otherwise.
7259 SetIMTRef(unimplemented_method,
7260 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007261 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007262 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007263 /*out*/imt_ptr);
7264 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007265 break;
7266 }
7267 }
Alex Light9139e002015-10-09 15:59:48 -07007268 }
7269 // Continue on to the next method if we are done.
7270 if (LIKELY(found_impl)) {
7271 continue;
7272 } else if (LIKELY(super_interface)) {
7273 // Don't look for a default implementation when the super-method is implemented directly
7274 // by the class.
7275 //
7276 // See if we can use the superclasses method and skip searching everything else.
7277 // Note: !found_impl && super_interface
7278 CHECK(extend_super_iftable);
7279 // If this is a super_interface method it is possible we shouldn't override it because a
7280 // superclass could have implemented it directly. We get the method the superclass used
7281 // to implement this to know if we can override it with a default method. Doing this is
7282 // safe since we know that the super_iftable is filled in so we can simply pull it from
7283 // there. We don't bother if this is not a super-classes interface since in that case we
7284 // have scanned the entire vtable anyway and would have found it.
7285 // TODO This is rather dirty but it is faster than searching through the entire vtable
7286 // every time.
7287 ArtMethod* supers_method =
7288 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7289 DCHECK(supers_method != nullptr);
7290 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007291 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007292 // The method is not overridable by a default method (i.e. it is directly implemented
7293 // in some class). Therefore move onto the next interface method.
7294 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007295 } else {
7296 // If the super-classes method is override-able by a default method we need to keep
7297 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7298 // 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 -07007299 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7300 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7301 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007302 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007303 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7304 << " and not 'nullptr' or "
7305 << supers_method->PrettyMethod()
7306 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007307 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007308 }
7309 }
7310 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007311 ArtMethod* current_method = helper.FindMethod(interface_method,
7312 interface_name_comparator,
7313 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007314 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007315 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007316 // We could not find an implementation for this method and since it is a brand new
7317 // interface we searched the entire vtable (and all default methods) for an
7318 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007319 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7320 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007321 }
7322
7323 if (current_method != nullptr) {
7324 // We found a default method implementation. Record it in the iftable and IMT.
7325 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7326 SetIMTRef(unimplemented_method,
7327 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007328 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007329 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007330 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007331 }
7332 }
Alex Light705ad492015-09-21 11:36:30 -07007333 } // For each method in interface end.
7334 } // if (num_methods > 0)
7335 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007336 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007337 if (helper.HasNewVirtuals()) {
7338 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7339 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7340 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7341
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007342 // 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 -07007343 // suspension assert.
7344 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007345
Alex Light705ad492015-09-21 11:36:30 -07007346 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007347 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007348 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007349 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07007350 return false;
7351 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007352 helper.UpdateIfTable(iftable);
7353 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007354 }
Alex Light705ad492015-09-21 11:36:30 -07007355
Vladimir Marko921094a2017-01-12 18:37:06 +00007356 helper.CheckNoStaleMethodsInDexCache();
7357 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007358 } else {
7359 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007360 }
Alex Light705ad492015-09-21 11:36:30 -07007361 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007362 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007363 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007364 return true;
7365}
7366
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007367bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007368 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007369 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007370}
7371
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007372bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007373 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007374 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007375}
7376
Brian Carlstromdbc05252011-09-09 01:59:59 -07007377struct LinkFieldsComparator {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007378 explicit LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07007379 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007380 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007381 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007382 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07007383 // 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 -07007384 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7385 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08007386 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00007387 if (type1 == Primitive::kPrimNot) {
7388 // Reference always goes first.
7389 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08007390 }
Vladimir Markod5777482014-11-12 17:02:02 +00007391 if (type2 == Primitive::kPrimNot) {
7392 // Reference always goes first.
7393 return false;
7394 }
7395 size_t size1 = Primitive::ComponentSize(type1);
7396 size_t size2 = Primitive::ComponentSize(type2);
7397 if (size1 != size2) {
7398 // Larger primitive types go first.
7399 return size1 > size2;
7400 }
7401 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7402 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007403 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007404 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7405 // by name and for equal names by type id index.
7406 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7407 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07007408 }
7409};
7410
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007411bool ClassLinker::LinkFields(Thread* self,
7412 Handle<mirror::Class> klass,
7413 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007414 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07007415 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07007416 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007417 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7418 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007419
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007420 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07007421 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007422 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007423 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007424 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007425 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007426 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07007427 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007428 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007429 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007430 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007431 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007432
David Sehr709b0702016-10-13 09:12:37 -07007433 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007434
Brian Carlstromdbc05252011-09-09 01:59:59 -07007435 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07007436 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08007437 //
7438 // The overall sort order order is:
7439 // 1) All object reference fields, sorted alphabetically.
7440 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7441 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7442 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7443 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7444 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7445 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7446 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7447 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7448 //
7449 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7450 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007451 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07007452 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07007453 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07007454 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007455 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007456 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07007457 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7458 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07007459
Fred Shih381e4ca2014-08-25 17:24:27 -07007460 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07007461 size_t current_field = 0;
7462 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07007463 FieldGaps gaps;
7464
Brian Carlstromdbc05252011-09-09 01:59:59 -07007465 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007466 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007467 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07007468 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007469 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07007470 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007471 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007472 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7473 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07007474 MemberOffset old_offset = field_offset;
7475 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7476 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7477 }
Roland Levillain14d90572015-07-16 10:52:26 +01007478 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007479 grouped_and_sorted_fields.pop_front();
7480 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007481 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00007482 field_offset = MemberOffset(field_offset.Uint32Value() +
7483 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007484 }
Fred Shih381e4ca2014-08-25 17:24:27 -07007485 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7486 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00007487 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7488 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7489 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7490 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07007491 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
7492 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07007493 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007494
Elliott Hughesadb460d2011-10-05 17:02:34 -07007495 // 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 -07007496 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07007497 // We know there are no non-reference fields in the Reference classes, and we know
7498 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07007499 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007500 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07007501 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07007502 --num_reference_fields;
7503 }
7504
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007505 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007506 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007507 if (is_static) {
7508 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007509 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007510 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007511 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007512 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007513 if (num_reference_fields == 0 || super_class == nullptr) {
7514 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007515 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007516 if (super_class == nullptr ||
7517 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
7518 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007519 }
7520 }
7521 if (kIsDebugBuild) {
7522 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
7523 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007524 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007525 while (cur_super != nullptr) {
7526 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
7527 cur_super = cur_super->GetSuperClass();
7528 }
7529 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07007530 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007531 } else {
7532 // Check that there is at least num_reference_fields other than Object.class.
7533 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07007534 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007535 }
7536 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07007537 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007538 std::string temp;
7539 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
7540 size_t previous_size = klass->GetObjectSize();
7541 if (previous_size != 0) {
7542 // Make sure that we didn't originally have an incorrect size.
7543 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07007544 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007545 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007546 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007547 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007548
7549 if (kIsDebugBuild) {
7550 // Make sure that the fields array is ordered by name but all reference
7551 // offsets are at the beginning as far as alignment allows.
7552 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07007553 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00007554 : klass->GetFirstReferenceInstanceFieldOffset();
7555 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
7556 num_reference_fields *
7557 sizeof(mirror::HeapReference<mirror::Object>));
7558 MemberOffset current_ref_offset = start_ref_offset;
7559 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007560 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007561 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07007562 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
7563 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007564 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007565 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007566 // NOTE: The field names can be the same. This is not possible in the Java language
7567 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007568 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00007569 }
7570 Primitive::Type type = field->GetTypeAsPrimitiveType();
7571 bool is_primitive = type != Primitive::kPrimNot;
7572 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
7573 strcmp("referent", field->GetName()) == 0) {
7574 is_primitive = true; // We lied above, so we have to expect a lie here.
7575 }
7576 MemberOffset offset = field->GetOffsetDuringLinking();
7577 if (is_primitive) {
7578 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
7579 // Shuffled before references.
7580 size_t type_size = Primitive::ComponentSize(type);
7581 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
7582 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
7583 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
7584 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
7585 }
7586 } else {
7587 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
7588 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
7589 sizeof(mirror::HeapReference<mirror::Object>));
7590 }
7591 }
7592 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
7593 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007594 return true;
7595}
7596
Vladimir Marko76649e82014-11-10 18:32:59 +00007597// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007598void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007599 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007600 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007601 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007602 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007603 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007604 // Compute reference offsets unless our superclass overflowed.
7605 if (reference_offsets != mirror::Class::kClassWalkSuper) {
7606 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007607 if (num_reference_fields != 0u) {
7608 // All of the fields that contain object references are guaranteed be grouped in memory
7609 // starting at an appropriately aligned address after super class object data.
7610 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
7611 sizeof(mirror::HeapReference<mirror::Object>));
7612 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007613 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00007614 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007615 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007616 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00007617 reference_offsets |= (0xffffffffu << start_bit) &
7618 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007619 }
7620 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07007621 }
7622 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07007623 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007624}
7625
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007626mirror::String* ClassLinker::ResolveString(const DexFile& dex_file,
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007627 dex::StringIndex string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007628 Handle<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007629 DCHECK(dex_cache != nullptr);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007630 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007631 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007632 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007633 return resolved.Ptr();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007634 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07007635 uint32_t utf16_length;
7636 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007637 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007638 if (string != nullptr) {
7639 dex_cache->SetResolvedString(string_idx, string);
7640 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007641 return string.Ptr();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007642}
7643
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007644mirror::String* ClassLinker::LookupString(const DexFile& dex_file,
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007645 dex::StringIndex string_idx,
Vladimir Markof25cc732017-03-16 16:18:15 +00007646 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007647 DCHECK(dex_cache != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007648 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007649 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007650 return resolved.Ptr();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007651 }
7652 uint32_t utf16_length;
7653 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007654 ObjPtr<mirror::String> string =
7655 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007656 if (string != nullptr) {
7657 dex_cache->SetResolvedString(string_idx, string);
7658 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007659 return string.Ptr();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007660}
7661
Mathieu Chartierb8901302016-09-30 10:27:43 -07007662ObjPtr<mirror::Class> ClassLinker::LookupResolvedType(const DexFile& dex_file,
Andreas Gampea5b09a62016-11-17 15:21:22 -08007663 dex::TypeIndex type_idx,
Mathieu Chartierb8901302016-09-30 10:27:43 -07007664 ObjPtr<mirror::DexCache> dex_cache,
7665 ObjPtr<mirror::ClassLoader> class_loader) {
7666 ObjPtr<mirror::Class> type = dex_cache->GetResolvedType(type_idx);
7667 if (type == nullptr) {
7668 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
7669 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
7670 if (descriptor[1] == '\0') {
7671 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
7672 // for primitive classes that aren't backed by dex files.
7673 type = FindPrimitiveClass(descriptor[0]);
7674 } else {
7675 Thread* const self = Thread::Current();
7676 DCHECK(self != nullptr);
7677 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
7678 // Find the class in the loaded classes table.
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07007679 type = LookupClass(self, descriptor, hash, class_loader.Ptr());
Mathieu Chartierb8901302016-09-30 10:27:43 -07007680 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007681 if (type != nullptr) {
7682 if (type->IsResolved()) {
7683 dex_cache->SetResolvedType(type_idx, type);
7684 } else {
7685 type = nullptr;
7686 }
7687 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07007688 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007689 DCHECK(type == nullptr || type->IsResolved());
7690 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07007691}
7692
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007693mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
Andreas Gampea5b09a62016-11-17 15:21:22 -08007694 dex::TypeIndex type_idx,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007695 ObjPtr<mirror::Class> referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007696 StackHandleScope<2> hs(Thread::Current());
7697 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
7698 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07007699 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
7700}
7701
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007702mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
Andreas Gampea5b09a62016-11-17 15:21:22 -08007703 dex::TypeIndex type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007704 Handle<mirror::DexCache> dex_cache,
7705 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007706 DCHECK(dex_cache != nullptr);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007707 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007708 ObjPtr<mirror::Class> resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007709 if (resolved == nullptr) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007710 // TODO: Avoid this lookup as it duplicates work done in FindClass(). It is here
7711 // as a workaround for FastNative JNI to avoid AssertNoPendingException() when
7712 // trying to resolve annotations while an exception may be pending. Bug: 34659969
7713 resolved = LookupResolvedType(dex_file, type_idx, dex_cache.Get(), class_loader.Get());
7714 }
7715 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08007716 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07007717 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08007718 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007719 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05007720 // TODO: we used to throw here if resolved's class loader was not the
7721 // boot class loader. This was to permit different classes with the
7722 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007723 dex_cache->SetResolvedType(type_idx, resolved);
7724 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08007725 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08007726 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08007727 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007728 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00007729 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08007730 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007731 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08007732 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08007733 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00007734 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08007735 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007736 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007737 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00007738 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007739 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007740 return resolved.Ptr();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007741}
7742
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007743template <ClassLinker::ResolveMode kResolveMode>
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007744ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file,
7745 uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07007746 Handle<mirror::DexCache> dex_cache,
7747 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007748 ArtMethod* referrer,
7749 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007750 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01007751 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07007752 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01007753 PointerSize pointer_size = image_pointer_size_;
7754 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007755 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007756 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
7757 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01007758 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
7759 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07007760 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007761 return resolved;
7762 }
7763 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01007764 ObjPtr<mirror::Class> klass = nullptr;
7765 if (valid_dex_cache_method) {
7766 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
7767 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
7768 klass = LookupResolvedType(dex_file, method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Mathieu Chartierf5981312017-09-06 14:17:34 -07007769 CHECK(klass != nullptr) << resolved->PrettyMethod() << " " << resolved << " "
7770 << resolved->GetAccessFlags();
Vladimir Markoba118822017-06-12 15:41:56 +01007771 } else {
7772 // The method was not in the DexCache, resolve the declaring class.
7773 klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
7774 if (klass == nullptr) {
7775 DCHECK(Thread::Current()->IsExceptionPending());
7776 return nullptr;
7777 }
7778 }
7779
7780 // Check if the invoke type matches the class type.
7781 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
7782 CheckInvokeClassMismatch</* kThrow */ true>(
7783 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07007784 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007785 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007786 }
Vladimir Markoba118822017-06-12 15:41:56 +01007787
7788 if (!valid_dex_cache_method) {
7789 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
7790 // functions can optimize the search if the dex_cache is the same as the DexCache
7791 // of the class, with fall-back to name and signature search otherwise.
7792 if (klass->IsInterface()) {
7793 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, pointer_size);
7794 } else {
7795 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, pointer_size);
7796 }
7797 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
7798 if (resolved != nullptr) {
7799 // Be a good citizen and update the dex cache to speed subsequent calls.
7800 dex_cache->SetResolvedMethod(method_idx, resolved, pointer_size);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08007801 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007802 }
Vladimir Markoba118822017-06-12 15:41:56 +01007803
7804 // Note: We can check for IllegalAccessError only if we have a referrer.
7805 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
7806 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
7807 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
7808 if (!referring_class->CheckResolvedMethodAccess(methods_class,
7809 resolved,
7810 dex_cache.Get(),
7811 method_idx,
7812 type)) {
7813 DCHECK(Thread::Current()->IsExceptionPending());
7814 return nullptr;
7815 }
7816 }
7817
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007818 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01007819 if (LIKELY(resolved != nullptr) &&
7820 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
7821 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07007822 return resolved;
7823 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01007824 // If we had a method, or if we can find one with another lookup type,
7825 // it's an incompatible-class-change error.
7826 if (resolved == nullptr) {
7827 if (klass->IsInterface()) {
7828 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, pointer_size);
7829 } else {
7830 // If there was an interface method with the same signature,
7831 // we would have found it also in the "copied" methods.
7832 DCHECK(klass->FindInterfaceMethod(dex_cache.Get(), method_idx, pointer_size) == nullptr);
7833 }
7834 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007835 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007836 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007837 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01007838 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007839 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
7840 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01007841 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07007842 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08007843 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007844 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07007845 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007846}
7847
Jeff Hao13e748b2015-08-25 20:44:19 +00007848ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(const DexFile& dex_file,
7849 uint32_t method_idx,
7850 Handle<mirror::DexCache> dex_cache,
7851 Handle<mirror::ClassLoader> class_loader) {
7852 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007853 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007854 if (resolved != nullptr) {
7855 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00007856 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
7857 return resolved;
7858 }
7859 // Fail, get the declaring class.
7860 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01007861 ObjPtr<mirror::Class> klass =
7862 ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00007863 if (klass == nullptr) {
7864 Thread::Current()->AssertPendingException();
7865 return nullptr;
7866 }
7867 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01007868 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7869 } else {
7870 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00007871 }
7872
7873 return resolved;
7874}
7875
Vladimir Markof44d36c2017-03-14 14:18:46 +00007876ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
7877 ObjPtr<mirror::DexCache> dex_cache,
7878 ObjPtr<mirror::ClassLoader> class_loader,
7879 bool is_static) {
7880 const DexFile& dex_file = *dex_cache->GetDexFile();
7881 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
7882 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
7883 if (klass == nullptr) {
7884 klass = LookupResolvedType(dex_file, field_id.class_idx_, dex_cache, class_loader);
7885 }
7886 if (klass == nullptr) {
7887 // The class has not been resolved yet, so the field is also unresolved.
7888 return nullptr;
7889 }
7890 DCHECK(klass->IsResolved());
7891 Thread* self = is_static ? Thread::Current() : nullptr;
7892
7893 // First try to find a field declared directly by `klass` by the field index.
7894 ArtField* resolved_field = is_static
7895 ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
7896 : klass->FindInstanceField(dex_cache, field_idx);
7897
7898 if (resolved_field == nullptr) {
7899 // If not found in `klass` by field index, search the class hierarchy using the name and type.
7900 const char* name = dex_file.GetFieldName(field_id);
7901 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
7902 resolved_field = is_static
7903 ? mirror::Class::FindStaticField(self, klass, name, type)
7904 : klass->FindInstanceField(name, type);
7905 }
7906
7907 if (resolved_field != nullptr) {
7908 dex_cache->SetResolvedField(field_idx, resolved_field, image_pointer_size_);
7909 }
7910 return resolved_field;
7911}
7912
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007913ArtField* ClassLinker::ResolveField(const DexFile& dex_file,
7914 uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07007915 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007916 Handle<mirror::ClassLoader> class_loader,
7917 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007918 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007919 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007920 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07007921 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007922 return resolved;
7923 }
7924 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07007925 Thread* const self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00007926 ObjPtr<mirror::Class> klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
7927 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08007928 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07007929 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007930 }
7931
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07007932 if (is_static) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00007933 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07007934 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007935 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07007936 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08007937
Andreas Gampe58a5af82014-07-31 16:23:49 -07007938 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08007939 const char* name = dex_file.GetFieldName(field_id);
7940 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
7941 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07007942 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08007943 } else {
7944 resolved = klass->FindInstanceField(name, type);
7945 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07007946 if (resolved == nullptr) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00007947 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007948 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08007949 }
Ian Rogersb067ac22011-12-13 18:05:09 -08007950 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07007951 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08007952 return resolved;
7953}
7954
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007955ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
7956 uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07007957 Handle<mirror::DexCache> dex_cache,
7958 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007959 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007960 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007961 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07007962 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08007963 return resolved;
7964 }
7965 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07007966 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00007967 ObjPtr<mirror::Class> klass(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader));
7968 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08007969 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007970 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08007971 }
7972
Vladimir Markof44d36c2017-03-14 14:18:46 +00007973 StringPiece name(dex_file.GetFieldName(field_id));
7974 StringPiece type(dex_file.GetFieldTypeDescriptor(field_id));
Mathieu Chartierf8322842014-05-16 10:59:25 -07007975 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007976 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007977 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08007978 } else {
Vladimir Marko19a4d372016-12-08 14:41:46 +00007979 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007980 }
7981 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07007982}
7983
Narayan Kamath25352fc2016-08-03 12:46:58 +01007984mirror::MethodType* ClassLinker::ResolveMethodType(const DexFile& dex_file,
7985 uint32_t proto_idx,
7986 Handle<mirror::DexCache> dex_cache,
7987 Handle<mirror::ClassLoader> class_loader) {
7988 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08007989 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01007990
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007991 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01007992 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007993 return resolved.Ptr();
Narayan Kamath25352fc2016-08-03 12:46:58 +01007994 }
7995
7996 Thread* const self = Thread::Current();
7997 StackHandleScope<4> hs(self);
7998
7999 // First resolve the return type.
8000 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
8001 Handle<mirror::Class> return_type(hs.NewHandle(
8002 ResolveType(dex_file, proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008003 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008004 DCHECK(self->IsExceptionPending());
8005 return nullptr;
8006 }
8007
8008 // Then resolve the argument types.
8009 //
8010 // TODO: Is there a better way to figure out the number of method arguments
8011 // other than by looking at the shorty ?
8012 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8013
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008014 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008015 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008016 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8017 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008018 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008019 DCHECK(self->IsExceptionPending());
8020 return nullptr;
8021 }
8022
8023 DexFileParameterIterator it(dex_file, proto_id);
8024 int32_t i = 0;
8025 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8026 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008027 const dex::TypeIndex type_idx = it.GetTypeIdx();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008028 param_class.Assign(ResolveType(dex_file, type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008029 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008030 DCHECK(self->IsExceptionPending());
8031 return nullptr;
8032 }
8033
8034 method_params->Set(i++, param_class.Get());
8035 }
8036
8037 DCHECK(!it.HasNext());
8038
8039 Handle<mirror::MethodType> type = hs.NewHandle(
8040 mirror::MethodType::Create(self, return_type, method_params));
8041 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8042
8043 return type.Get();
8044}
8045
Orion Hodson2e599942017-09-22 16:17:41 +01008046mirror::MethodType* ClassLinker::ResolveMethodType(uint32_t proto_idx, ArtMethod* referrer) {
8047 Thread* const self = Thread::Current();
8048 StackHandleScope<2> hs(self);
8049 const DexFile* dex_file = referrer->GetDexFile();
8050 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8051 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8052 return ResolveMethodType(*dex_file, proto_idx, dex_cache, class_loader);
8053}
8054
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008055mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8056 Thread* self,
8057 const DexFile::MethodHandleItem& method_handle,
8058 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008059 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008060 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8061 mirror::MethodHandle::Kind kind;
8062 bool is_static;
8063 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008064 switch (handle_type) {
8065 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008066 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008067 is_static = true;
8068 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008069 break;
8070 }
8071 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008072 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008073 is_static = true;
8074 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008075 break;
8076 }
8077 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008078 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008079 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008080 num_params = 2;
8081 break;
8082 }
8083 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008084 kind = mirror::MethodHandle::Kind::kInstanceGet;
8085 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008086 num_params = 1;
8087 break;
8088 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008089 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008090 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008091 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008092 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008093 case DexFile::MethodHandleType::kInvokeInterface:
8094 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008095 }
8096
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008097 ArtField* target_field =
8098 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8099 if (LIKELY(target_field != nullptr)) {
8100 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8101 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8102 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8103 ThrowIllegalAccessErrorField(referring_class, target_field);
8104 return nullptr;
8105 }
8106 } else {
8107 DCHECK(Thread::Current()->IsExceptionPending());
8108 return nullptr;
8109 }
8110
8111 StackHandleScope<4> hs(self);
Orion Hodsonc069a302017-01-18 09:23:12 +00008112 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8113 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8114 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8115 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008116 if (UNLIKELY(method_params.Get() == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008117 DCHECK(self->IsExceptionPending());
8118 return nullptr;
8119 }
8120
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008121 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008122 Handle<mirror::Class> return_type;
8123 switch (handle_type) {
8124 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008125 method_params->Set(0, target_field->GetType<true>());
Orion Hodsonc069a302017-01-18 09:23:12 +00008126 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8127 break;
8128 }
8129 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008130 return_type = hs.NewHandle(target_field->GetType<true>());
Orion Hodsonc069a302017-01-18 09:23:12 +00008131 break;
8132 }
8133 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008134 method_params->Set(0, target_field->GetDeclaringClass());
8135 method_params->Set(1, target_field->GetType<true>());
Orion Hodsonc069a302017-01-18 09:23:12 +00008136 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8137 break;
8138 }
8139 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008140 method_params->Set(0, target_field->GetDeclaringClass());
8141 return_type = hs.NewHandle(target_field->GetType<true>());
Orion Hodsonc069a302017-01-18 09:23:12 +00008142 break;
8143 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008144 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008145 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008146 case DexFile::MethodHandleType::kInvokeConstructor:
8147 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008148 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008149 UNREACHABLE();
8150 }
8151
8152 for (int32_t i = 0; i < num_params; ++i) {
8153 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8154 DCHECK(self->IsExceptionPending());
8155 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008156 }
8157 }
8158
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008159 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008160 DCHECK(self->IsExceptionPending());
8161 return nullptr;
8162 }
8163
8164 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008165 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8166 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008167 DCHECK(self->IsExceptionPending());
8168 return nullptr;
8169 }
Orion Hodson631827d2017-04-10 14:53:47 +01008170
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008171 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8172 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8173}
8174
8175mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8176 Thread* self,
8177 const DexFile* const dex_file,
8178 const DexFile::MethodHandleItem& method_handle,
8179 ArtMethod* referrer) {
8180 DexFile::MethodHandleType handle_type =
8181 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8182 mirror::MethodHandle::Kind kind;
8183 uint32_t receiver_count = 0;
8184 ArtMethod* target_method = nullptr;
8185 switch (handle_type) {
8186 case DexFile::MethodHandleType::kStaticPut:
8187 case DexFile::MethodHandleType::kStaticGet:
8188 case DexFile::MethodHandleType::kInstancePut:
8189 case DexFile::MethodHandleType::kInstanceGet:
8190 UNREACHABLE();
8191 case DexFile::MethodHandleType::kInvokeStatic: {
8192 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8193 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008194 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8195 method_handle.field_or_method_idx_,
8196 referrer,
8197 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008198 break;
8199 }
8200 case DexFile::MethodHandleType::kInvokeInstance: {
8201 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8202 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008203 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8204 method_handle.field_or_method_idx_,
8205 referrer,
8206 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008207 break;
8208 }
8209 case DexFile::MethodHandleType::kInvokeConstructor: {
8210 // Constructors are currently implemented as a transform. They
8211 // are special cased later in this method.
8212 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8213 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008214 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8215 method_handle.field_or_method_idx_,
8216 referrer,
8217 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008218 break;
8219 }
8220 case DexFile::MethodHandleType::kInvokeDirect: {
8221 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8222 receiver_count = 1;
8223 StackHandleScope<2> hs(self);
8224 // A constant method handle with type kInvokeDirect can refer to
8225 // a method that is private or to a method in a super class. To
8226 // disambiguate the two options, we resolve the method ignoring
8227 // the invocation type to determine if the method is private. We
8228 // then resolve again specifying the intended invocation type to
8229 // force the appropriate checks.
8230 target_method = ResolveMethodWithoutInvokeType(*dex_file,
8231 method_handle.field_or_method_idx_,
8232 hs.NewHandle(referrer->GetDexCache()),
8233 hs.NewHandle(referrer->GetClassLoader()));
8234 if (UNLIKELY(target_method == nullptr)) {
8235 break;
8236 }
8237
8238 if (target_method->IsPrivate()) {
8239 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01008240 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8241 method_handle.field_or_method_idx_,
8242 referrer,
8243 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008244 } else {
8245 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01008246 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8247 method_handle.field_or_method_idx_,
8248 referrer,
8249 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008250 if (UNLIKELY(target_method == nullptr)) {
8251 break;
8252 }
8253 // Find the method specified in the parent in referring class
8254 // so invoke-super invokes the method in the parent of the
8255 // referrer.
8256 target_method =
8257 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
8258 kRuntimePointerSize);
8259 }
8260 break;
8261 }
8262 case DexFile::MethodHandleType::kInvokeInterface: {
8263 kind = mirror::MethodHandle::Kind::kInvokeInterface;
8264 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008265 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8266 method_handle.field_or_method_idx_,
8267 referrer,
8268 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008269 break;
8270 }
Orion Hodson631827d2017-04-10 14:53:47 +01008271 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008272
8273 if (UNLIKELY(target_method == nullptr)) {
8274 DCHECK(Thread::Current()->IsExceptionPending());
8275 return nullptr;
8276 }
8277
8278 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
8279 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8280 uint32_t access_flags = target_method->GetAccessFlags();
8281 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
8282 ThrowIllegalAccessErrorMethod(referring_class, target_method);
8283 return nullptr;
8284 }
8285
8286 // Calculate the number of parameters from the method shorty. We add the
8287 // receiver count (0 or 1) and deduct one for the return value.
8288 uint32_t shorty_length;
8289 target_method->GetShorty(&shorty_length);
8290 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
8291
8292 StackHandleScope<7> hs(self);
8293 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8294 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8295 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8296 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
8297 if (method_params.Get() == nullptr) {
8298 DCHECK(self->IsExceptionPending());
8299 return nullptr;
8300 }
8301
8302 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8303 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8304 int32_t index = 0;
8305
8306 if (receiver_count != 0) {
8307 // Insert receiver
8308 method_params->Set(index++, target_method->GetDeclaringClass());
8309 }
8310
8311 DexFileParameterIterator it(*dex_file, target_method->GetPrototype());
8312 while (it.HasNext()) {
8313 const dex::TypeIndex type_idx = it.GetTypeIdx();
8314 mirror::Class* klass = ResolveType(*dex_file, type_idx, dex_cache, class_loader);
8315 if (nullptr == klass) {
8316 DCHECK(self->IsExceptionPending());
8317 return nullptr;
8318 }
8319 method_params->Set(index++, klass);
8320 it.Next();
8321 }
8322
Vladimir Markob45528c2017-07-27 14:14:28 +01008323 Handle<mirror::Class> return_type = hs.NewHandle(target_method->ResolveReturnType());
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008324 if (UNLIKELY(return_type.IsNull())) {
8325 DCHECK(self->IsExceptionPending());
8326 return nullptr;
8327 }
8328
8329 Handle<mirror::MethodType>
8330 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8331 if (UNLIKELY(method_type.IsNull())) {
8332 DCHECK(self->IsExceptionPending());
8333 return nullptr;
8334 }
8335
8336 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
8337 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
8338 Handle<mirror::MethodHandlesLookup> lookup =
8339 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
8340 return lookup->FindConstructor(self, constructor_class, method_type);
8341 }
8342
8343 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
8344 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8345}
8346
8347mirror::MethodHandle* ClassLinker::ResolveMethodHandle(uint32_t method_handle_idx,
8348 ArtMethod* referrer)
8349 REQUIRES_SHARED(Locks::mutator_lock_) {
8350 Thread* const self = Thread::Current();
8351 const DexFile* const dex_file = referrer->GetDexFile();
8352 const DexFile::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
8353 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
8354 case DexFile::MethodHandleType::kStaticPut:
8355 case DexFile::MethodHandleType::kStaticGet:
8356 case DexFile::MethodHandleType::kInstancePut:
8357 case DexFile::MethodHandleType::kInstanceGet:
8358 return ResolveMethodHandleForField(self, method_handle, referrer);
8359 case DexFile::MethodHandleType::kInvokeStatic:
8360 case DexFile::MethodHandleType::kInvokeInstance:
8361 case DexFile::MethodHandleType::kInvokeConstructor:
8362 case DexFile::MethodHandleType::kInvokeDirect:
8363 case DexFile::MethodHandleType::kInvokeInterface:
8364 return ResolveMethodHandleForMethod(self, dex_file, method_handle, referrer);
8365 }
Orion Hodsonc069a302017-01-18 09:23:12 +00008366}
8367
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008368bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
8369 return (entry_point == GetQuickResolutionStub()) ||
8370 (quick_resolution_trampoline_ == entry_point);
8371}
8372
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008373bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
8374 return (entry_point == GetQuickToInterpreterBridge()) ||
8375 (quick_to_interpreter_bridge_trampoline_ == entry_point);
8376}
8377
8378bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
8379 return (entry_point == GetQuickGenericJniStub()) ||
8380 (quick_generic_jni_trampoline_ == entry_point);
8381}
8382
David Sehra49e0532017-08-25 08:05:29 -07008383bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
8384 return entry_point == GetJniDlsymLookupStub();
8385}
8386
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008387const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
8388 return GetQuickGenericJniStub();
8389}
8390
Mathieu Chartiere401d142015-04-22 13:56:20 -07008391void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008392 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008393 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
8394 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02008395 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008396 }
8397}
8398
Alex Lightdb01a092017-04-03 15:39:55 -07008399void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
8400 DCHECK(method->IsObsolete());
8401 // We cannot mess with the entrypoints of native methods because they are used to determine how
8402 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
8403 if (!method->IsNative()) {
8404 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
8405 }
8406}
8407
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008408void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07008409 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07008410 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008411 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
8412 << NumNonZygoteClasses() << "\n";
8413}
8414
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008415class CountClassesVisitor : public ClassLoaderVisitor {
8416 public:
8417 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
8418
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008419 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07008420 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008421 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07008422 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00008423 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
8424 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07008425 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008426 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008427
8428 size_t num_zygote_classes;
8429 size_t num_non_zygote_classes;
8430};
8431
8432size_t ClassLinker::NumZygoteClasses() const {
8433 CountClassesVisitor visitor;
8434 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008435 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008436}
8437
8438size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008439 CountClassesVisitor visitor;
8440 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008441 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07008442}
8443
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008444size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07008445 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08008446 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008447 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07008448}
8449
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008450pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07008451 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008452}
8453
8454pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08008455 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07008456}
8457
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008458void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008459 DCHECK(!init_done_);
8460
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008461 DCHECK(klass != nullptr);
8462 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008463
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07008464 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008465 DCHECK(class_roots != nullptr);
8466 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07008467 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008468}
8469
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008470const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
8471 static const char* class_roots_descriptors[] = {
8472 "Ljava/lang/Class;",
8473 "Ljava/lang/Object;",
8474 "[Ljava/lang/Class;",
8475 "[Ljava/lang/Object;",
8476 "Ljava/lang/String;",
8477 "Ljava/lang/DexCache;",
8478 "Ljava/lang/ref/Reference;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008479 "Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008480 "Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008481 "Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008482 "Ljava/lang/reflect/Proxy;",
8483 "[Ljava/lang/String;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008484 "[Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008485 "[Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008486 "[Ljava/lang/reflect/Method;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008487 "Ljava/lang/invoke/CallSite;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008488 "Ljava/lang/invoke/MethodHandleImpl;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008489 "Ljava/lang/invoke/MethodHandles$Lookup;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008490 "Ljava/lang/invoke/MethodType;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008491 "Ljava/lang/ClassLoader;",
8492 "Ljava/lang/Throwable;",
8493 "Ljava/lang/ClassNotFoundException;",
8494 "Ljava/lang/StackTraceElement;",
Narayan Kamath000e1882016-10-24 17:14:25 +01008495 "Ldalvik/system/EmulatedStackFrame;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008496 "Z",
8497 "B",
8498 "C",
8499 "D",
8500 "F",
8501 "I",
8502 "J",
8503 "S",
8504 "V",
8505 "[Z",
8506 "[B",
8507 "[C",
8508 "[D",
8509 "[F",
8510 "[I",
8511 "[J",
8512 "[S",
8513 "[Ljava/lang/StackTraceElement;",
Alex Lightd6251582016-10-31 11:12:30 -07008514 "Ldalvik/system/ClassExt;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008515 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08008516 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
8517 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008518
8519 const char* descriptor = class_roots_descriptors[class_root];
8520 CHECK(descriptor != nullptr);
8521 return descriptor;
8522}
8523
Calin Juravle7865ac72017-06-28 11:03:12 -07008524jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
8525 const std::vector<const DexFile*>& dex_files,
8526 jclass loader_class,
8527 jobject parent_loader) {
8528 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
8529 WellKnownClasses::dalvik_system_PathClassLoader) ||
8530 self->GetJniEnv()->IsSameObject(loader_class,
8531 WellKnownClasses::dalvik_system_DelegateLastClassLoader));
8532
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008533 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
8534 // We could move the jobject to the callers, but all call-sites do this...
8535 ScopedObjectAccessUnchecked soa(self);
8536
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008537 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Vladimir Marko19a4d372016-12-08 14:41:46 +00008538 StackHandleScope<6> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008539
Mathieu Chartierc7853442015-03-27 14:35:38 -07008540 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008541 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008542
Mathieu Chartier3398c782016-09-30 10:27:43 -07008543 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->GetType<true>()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008544 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008545 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008546 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07008547 mirror::ObjectArray<mirror::Object>::Alloc(self,
8548 dex_elements_class.Get(),
8549 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008550 Handle<mirror::Class> h_dex_element_class =
8551 hs.NewHandle(dex_elements_class->GetComponentType());
8552
Mathieu Chartierc7853442015-03-27 14:35:38 -07008553 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008554 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008555 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008556
Andreas Gampe08883de2016-11-08 13:20:52 -08008557 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008558 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008559
Andreas Gampe08883de2016-11-08 13:20:52 -08008560 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008561 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->GetType<false>());
8562
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008563 // Fill the elements array.
8564 int32_t index = 0;
8565 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008566 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008567
Calin Juravle7865ac72017-06-28 11:03:12 -07008568 // CreateWellKnownClassLoader is only used by gtests and compiler.
8569 // Index 0 of h_long_array is supposed to be the oat file but we can leave it null.
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008570 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
8571 self,
8572 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008573 DCHECK(h_long_array != nullptr);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008574 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008575
Mathieu Chartier3738e982017-05-12 16:07:28 -07008576 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
8577 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008578 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008579 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008580 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008581 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008582
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008583 Handle<mirror::String> h_file_name = hs2.NewHandle(
8584 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008585 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008586 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
8587
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008588 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008589 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008590 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008591
8592 h_dex_elements->Set(index, h_element.Get());
8593 index++;
8594 }
8595 DCHECK_EQ(index, h_dex_elements->GetLength());
8596
8597 // Create DexPathList.
8598 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008599 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008600 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008601 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008602 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008603
Calin Juravle7865ac72017-06-28 11:03:12 -07008604 // Create the class loader..
8605 Handle<mirror::Class> h_loader_class = hs.NewHandle(soa.Decode<mirror::Class>(loader_class));
8606 Handle<mirror::Object> h_class_loader = hs.NewHandle(h_loader_class->AllocObject(self));
8607 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008608 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008609 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008610 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008611 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008612 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008613
8614 // Make a pretend boot-classpath.
8615 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07008616 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00008617 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07008618 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00008619 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07008620 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01008621 DCHECK(parent_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008622
8623 ObjPtr<mirror::Object> parent = (parent_loader != nullptr)
8624 ? soa.Decode<mirror::ClassLoader>(parent_loader)
8625 : soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
8626 parent_field->SetObject<false>(h_class_loader.Get(), parent);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008627
8628 // Make it a global ref and return.
8629 ScopedLocalRef<jobject> local_ref(
Calin Juravle7865ac72017-06-28 11:03:12 -07008630 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_class_loader.Get()));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008631 return soa.Env()->NewGlobalRef(local_ref.get());
8632}
8633
Calin Juravle7865ac72017-06-28 11:03:12 -07008634jobject ClassLinker::CreatePathClassLoader(Thread* self,
8635 const std::vector<const DexFile*>& dex_files) {
8636 return CreateWellKnownClassLoader(self,
8637 dex_files,
8638 WellKnownClasses::dalvik_system_PathClassLoader,
8639 nullptr);
8640}
8641
Andreas Gampe8ac75952015-06-02 21:01:45 -07008642void ClassLinker::DropFindArrayClassCache() {
8643 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
8644 find_array_class_cache_next_victim_ = 0;
8645}
8646
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008647void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008648 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008649 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07008650 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008651 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
8652 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008653 if (class_loader != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008654 visitor->Visit(class_loader.Ptr());
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008655 }
8656 }
8657}
8658
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008659void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
8660 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008661 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07008662 Thread* const self = Thread::Current();
8663 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008664 ClassTable* const table = ClassTableForClassLoader(class_loader.Ptr());
Mathieu Chartier00310e02015-10-17 12:46:42 -07008665 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07008666 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008667 // It was not already inserted, perform the write barrier to let the GC know the class loader's
8668 // class table was modified.
8669 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
8670 }
8671}
8672
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008673void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008674 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07008675 std::vector<ClassLoaderData> to_delete;
8676 // Do the delete outside the lock to avoid lock violation in jit code cache.
8677 {
8678 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8679 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
8680 const ClassLoaderData& data = *it;
8681 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008682 ObjPtr<mirror::ClassLoader> class_loader =
8683 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07008684 if (class_loader != nullptr) {
8685 ++it;
8686 } else {
8687 VLOG(class_linker) << "Freeing class loader";
8688 to_delete.push_back(data);
8689 it = class_loaders_.erase(it);
8690 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008691 }
8692 }
Mathieu Chartier65975772016-08-05 10:46:36 -07008693 for (ClassLoaderData& data : to_delete) {
8694 DeleteClassLoader(self, data);
8695 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008696}
8697
Vladimir Marko21300532017-01-24 18:06:55 +00008698class GetResolvedClassesVisitor : public ClassVisitor {
8699 public:
8700 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
8701 : result_(result),
8702 ignore_boot_classes_(ignore_boot_classes),
8703 last_resolved_classes_(result->end()),
8704 last_dex_file_(nullptr),
8705 vlog_is_on_(VLOG_IS_ON(class_linker)),
8706 extra_stats_(),
8707 last_extra_stats_(extra_stats_.end()) { }
8708
8709 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
8710 if (!klass->IsProxyClass() &&
8711 !klass->IsArrayClass() &&
8712 klass->IsResolved() &&
8713 !klass->IsErroneousResolved() &&
8714 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
8715 const DexFile& dex_file = klass->GetDexFile();
8716 if (&dex_file != last_dex_file_) {
8717 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07008718 DexCacheResolvedClasses resolved_classes(
8719 dex_file.GetLocation(),
8720 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
8721 dex_file.GetLocationChecksum(),
8722 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00008723 last_resolved_classes_ = result_->find(resolved_classes);
8724 if (last_resolved_classes_ == result_->end()) {
8725 last_resolved_classes_ = result_->insert(resolved_classes).first;
8726 }
8727 }
8728 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
8729 if (UNLIKELY(vlog_is_on_) && added) {
8730 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
8731 if (last_extra_stats_ == extra_stats_.end() ||
8732 last_extra_stats_->first != resolved_classes) {
8733 last_extra_stats_ = extra_stats_.find(resolved_classes);
8734 if (last_extra_stats_ == extra_stats_.end()) {
8735 last_extra_stats_ =
8736 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
8737 }
8738 }
8739 }
8740 }
8741 return true;
8742 }
8743
8744 void PrintStatistics() const {
8745 if (vlog_is_on_) {
8746 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
8747 auto it = extra_stats_.find(std::addressof(resolved_classes));
8748 DCHECK(it != extra_stats_.end());
8749 const ExtraStats& extra_stats = it->second;
8750 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
8751 << " has " << resolved_classes.GetClasses().size() << " / "
8752 << extra_stats.number_of_class_defs_ << " resolved classes";
8753 }
8754 }
8755 }
8756
8757 private:
8758 struct ExtraStats {
8759 explicit ExtraStats(uint32_t number_of_class_defs)
8760 : number_of_class_defs_(number_of_class_defs) {}
8761 uint32_t number_of_class_defs_;
8762 };
8763
8764 std::set<DexCacheResolvedClasses>* result_;
8765 bool ignore_boot_classes_;
8766 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
8767 const DexFile* last_dex_file_;
8768
8769 // Statistics.
8770 bool vlog_is_on_;
8771 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
8772 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
8773};
8774
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008775std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08008776 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008777 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07008778 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008779 std::set<DexCacheResolvedClasses> ret;
8780 VLOG(class_linker) << "Collecting resolved classes";
8781 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00008782 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
8783 VisitClasses(&visitor);
8784 if (VLOG_IS_ON(class_linker)) {
8785 visitor.PrintStatistics();
8786 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008787 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008788 return ret;
8789}
8790
Mathieu Chartier65975772016-08-05 10:46:36 -07008791class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
8792 public:
8793 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
8794 : method_(method),
8795 pointer_size_(pointer_size) {}
8796
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008797 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier65975772016-08-05 10:46:36 -07008798 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
8799 holder_ = klass;
8800 }
8801 // Return false to stop searching if holder_ is not null.
8802 return holder_ == nullptr;
8803 }
8804
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008805 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07008806 const ArtMethod* const method_;
8807 const PointerSize pointer_size_;
8808};
8809
8810mirror::Class* ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
8811 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
8812 CHECK(method->IsCopied());
8813 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
8814 VisitClasses(&visitor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008815 return visitor.holder_.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07008816}
8817
Andreas Gampec6ea7d02017-02-01 16:46:28 -08008818mirror::IfTable* ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
8819 return down_cast<mirror::IfTable*>(
8820 mirror::IfTable::Alloc(self,
8821 GetClassRoot(kObjectArrayClass),
8822 ifcount * mirror::IfTable::kMax));
8823}
8824
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008825// Instantiate ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01008826template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008827 const DexFile& dex_file,
8828 uint32_t method_idx,
8829 Handle<mirror::DexCache> dex_cache,
8830 Handle<mirror::ClassLoader> class_loader,
8831 ArtMethod* referrer,
8832 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01008833template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008834 const DexFile& dex_file,
8835 uint32_t method_idx,
8836 Handle<mirror::DexCache> dex_cache,
8837 Handle<mirror::ClassLoader> class_loader,
8838 ArtMethod* referrer,
8839 InvokeType type);
8840
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008841} // namespace art