blob: fd92c14951e7d1ea7aec03c82b56bdff92347b33 [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"
David Sehr67bf42e2018-02-26 16:43:04 -080039#include "base/leb128.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080040#include "base/logging.h"
David Sehrc431b9d2018-03-02 12:01:51 -080041#include "base/os.h"
42#include "base/quasi_atomic.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070043#include "base/scoped_arena_containers.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010044#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080045#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080046#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010047#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080048#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080049#include "base/utils.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070050#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070051#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "class_linker-inl.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070053#include "class_loader_utils.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070054#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000055#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080056#include "debugger.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080057#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080058#include "dex/dex_file-inl.h"
59#include "dex/dex_file_exception_helpers.h"
60#include "dex/dex_file_loader.h"
David Sehr0225f8e2018-01-31 08:52:24 +000061#include "dex/utf.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070062#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070063#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070064#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070065#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080066#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000067#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070068#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070069#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070070#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070071#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000072#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070073#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070074#include "handle_scope-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080075#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070076#include "imt_conflict_table.h"
77#include "imtable-inl.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070078#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070079#include "interpreter/interpreter.h"
Andreas Gampec15a2f42017-04-21 12:09:39 -070080#include "java_vm_ext.h"
David Srbeckyfb3de3d2018-01-29 16:11:49 +000081#include "jit/debugger_interface.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080082#include "jit/jit.h"
83#include "jit/jit_code_cache.h"
Calin Juravle33083d62017-01-18 15:29:12 -080084#include "jit/profile_compilation_info.h"
Andreas Gampe08883de2016-11-08 13:20:52 -080085#include "jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070086#include "linear_alloc.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000087#include "mirror/call_site.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080088#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070089#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -070090#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080091#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070092#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070093#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +010094#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070095#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080096#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070097#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +010098#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000099#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -0700100#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800101#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +0000102#include "mirror/object-refvisitor-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700103#include "mirror/object_array-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800104#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700105#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800106#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700107#include "mirror/string-inl.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100108#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700109#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700110#include "nativehelper/scoped_local_ref.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700111#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700112#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700113#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700114#include "oat_file_assistant.h"
115#include "oat_file_manager.h"
116#include "object_lock.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700117#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800118#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700119#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700120#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700121#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700122#include "trace.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100123#include "utils/dex_cache_arrays_layout-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800124#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700125#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700126
127namespace art {
128
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800129using android::base::StringPrintf;
130
Mathieu Chartierc7853442015-03-27 14:35:38 -0700131static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700132static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700133
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700134static void ThrowNoClassDefFoundError(const char* fmt, ...)
135 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700136 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700137static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700138 va_list args;
139 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800140 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000141 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800142 va_end(args);
143}
144
Andreas Gampe99babb62015-11-02 16:20:00 -0800145static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700146 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700147 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700148 StackHandleScope<1> hs(self);
149 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700150 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700151 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700152
153 if (exception_class == nullptr) {
154 // No exc class ~ no <init>-with-string.
155 CHECK(self->IsExceptionPending());
156 self->ClearException();
157 return false;
158 }
159
Vladimir Markoba118822017-06-12 15:41:56 +0100160 ArtMethod* exception_init_method = exception_class->FindConstructor(
161 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700162 return exception_init_method != nullptr;
163}
164
Alex Lightd6251582016-10-31 11:12:30 -0700165static mirror::Object* GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700166 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700167 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
168 if (ext == nullptr) {
169 return nullptr;
170 } else {
171 return ext->GetVerifyError();
172 }
173}
174
175// Helper for ThrowEarlierClassFailure. Throws the stored error.
176static void HandleEarlierVerifyError(Thread* self,
177 ClassLinker* class_linker,
178 ObjPtr<mirror::Class> c)
179 REQUIRES_SHARED(Locks::mutator_lock_) {
180 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800181 DCHECK(obj != nullptr);
182 self->AssertNoPendingException();
183 if (obj->IsClass()) {
184 // Previous error has been stored as class. Create a new exception of that type.
185
186 // It's possible the exception doesn't have a <init>(String).
187 std::string temp;
188 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
189
190 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700191 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800192 } else {
193 self->ThrowNewException(descriptor, nullptr);
194 }
195 } else {
196 // Previous error has been stored as an instance. Just rethrow.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700197 ObjPtr<mirror::Class> throwable_class =
Andreas Gampe99babb62015-11-02 16:20:00 -0800198 self->DecodeJObject(WellKnownClasses::java_lang_Throwable)->AsClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700199 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800200 CHECK(throwable_class->IsAssignableFrom(error_class));
201 self->SetException(obj->AsThrowable());
202 }
203 self->AssertPendingException();
204}
205
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700206void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c, bool wrap_in_no_class_def) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700207 // The class failed to initialize on a previous attempt, so we want to throw
208 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
209 // failed in verification, in which case v2 5.4.1 says we need to re-throw
210 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800211 Runtime* const runtime = Runtime::Current();
212 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700213 std::string extra;
Alex Lightd6251582016-10-31 11:12:30 -0700214 if (GetVerifyError(c) != nullptr) {
215 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
Andreas Gampe369c8512016-01-28 15:31:39 -0800216 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700217 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800218 } else {
219 extra = verify_error->AsThrowable()->Dump();
220 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700221 }
David Sehr709b0702016-10-13 09:12:37 -0700222 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
223 << ": " << extra;
Ian Rogers87e552d2012-08-31 15:54:48 -0700224 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700225
David Sehr709b0702016-10-13 09:12:37 -0700226 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800227 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800228 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700229 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700230 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000231 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700232 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700233 if (GetVerifyError(c) != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800234 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800235 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800236 }
Alex Lightd6251582016-10-31 11:12:30 -0700237 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
238 // might have meant to go down the earlier if statement with the original error but it got
239 // swallowed by the OOM so we end up here.
240 if (GetVerifyError(c) == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800241 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
242 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
243 // exception will be a cause.
244 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700245 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700246 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700247 }
248}
249
Brian Carlstromb23eab12014-10-08 17:55:21 -0700250static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700251 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700252 if (VLOG_IS_ON(class_linker)) {
253 std::string temp;
254 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000255 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700256 }
257}
258
259static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700260 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700261 Thread* self = Thread::Current();
262 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700263
264 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700265 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700266
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800267 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
268 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
269 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800270 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800271 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
272 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
273 // could have caused the error.
274 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
275 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
276 << " failed initialization: "
277 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800278 }
279
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700280 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700281 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
282 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700283
Elliott Hughesa4f94742012-05-29 16:28:38 -0700284 // We only wrap non-Error exceptions; an Error can just be used as-is.
285 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000286 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700287 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700288 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700289}
290
Fred Shih381e4ca2014-08-25 17:24:27 -0700291// Gap between two fields in object layout.
292struct FieldGap {
293 uint32_t start_offset; // The offset from the start of the object.
294 uint32_t size; // The gap size of 1, 2, or 4 bytes.
295};
296struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800297 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700298 }
299 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
300 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800301 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700302 // Note that the priority queue returns the largest element, so operator()
303 // should return true if lhs is less than rhs.
304 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700305 }
306};
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700307typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
Fred Shih381e4ca2014-08-25 17:24:27 -0700308
309// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800310static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700311 DCHECK(gaps != nullptr);
312
313 uint32_t current_offset = gap_start;
314 while (current_offset != gap_end) {
315 size_t remaining = gap_end - current_offset;
316 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
317 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
318 current_offset += sizeof(uint32_t);
319 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
320 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
321 current_offset += sizeof(uint16_t);
322 } else {
323 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
324 current_offset += sizeof(uint8_t);
325 }
326 DCHECK_LE(current_offset, gap_end) << "Overran gap";
327 }
328}
329// Shuffle fields forward, making use of gaps whenever possible.
330template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000331static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700332 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700333 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700334 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700335 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700336 DCHECK(current_field_idx != nullptr);
337 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700338 DCHECK(gaps != nullptr);
339 DCHECK(field_offset != nullptr);
340
341 DCHECK(IsPowerOfTwo(n));
342 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700343 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700344 Primitive::Type type = field->GetTypeAsPrimitiveType();
345 if (Primitive::ComponentSize(type) < n) {
346 break;
347 }
348 if (!IsAligned<n>(field_offset->Uint32Value())) {
349 MemberOffset old_offset = *field_offset;
350 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
351 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
352 }
David Sehr709b0702016-10-13 09:12:37 -0700353 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700354 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700355 if (!gaps->empty() && gaps->top().size >= n) {
356 FieldGap gap = gaps->top();
357 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100358 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700359 field->SetOffset(MemberOffset(gap.start_offset));
360 if (gap.size > n) {
361 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
362 }
363 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100364 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700365 field->SetOffset(*field_offset);
366 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
367 }
368 ++(*current_field_idx);
369 }
370}
371
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800372ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampe2af99022017-04-25 08:32:59 -0700373 : boot_class_table_(new ClassTable()),
374 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800375 class_roots_(nullptr),
376 array_iftable_(nullptr),
377 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700378 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000379 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700380 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800381 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800382 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100383 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800384 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700385 image_pointer_size_(kRuntimePointerSize),
Andreas Gampe7dface32017-07-25 21:32:59 -0700386 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
387 // For CHA disabled during Aot, see b/34193647.
388
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700389 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700390 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
391 "Array cache size wrong.");
392 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700393}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700394
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800395void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700396 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800397 if (c2 == nullptr) {
398 LOG(FATAL) << "Could not find class " << descriptor;
399 UNREACHABLE();
400 }
401 if (c1.Get() != c2) {
402 std::ostringstream os1, os2;
403 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
404 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
405 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
406 << ". This is most likely the result of a broken build. Make sure that "
407 << "libcore and art projects match.\n\n"
408 << os1.str() << "\n\n" << os2.str();
409 UNREACHABLE();
410 }
411}
412
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800413bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
414 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800415 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700416
Mathieu Chartiere401d142015-04-22 13:56:20 -0700417 Thread* const self = Thread::Current();
418 Runtime* const runtime = Runtime::Current();
419 gc::Heap* const heap = runtime->GetHeap();
420
Jeff Haodcdc85b2015-12-04 14:06:18 -0800421 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700422 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700423
Mathieu Chartiere401d142015-04-22 13:56:20 -0700424 // Use the pointer size from the runtime since we are probably creating the image.
425 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
426
Elliott Hughes30646832011-10-13 16:59:46 -0700427 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700428 // 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 -0800429 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700430 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700431 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700432 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700433 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800434 CHECK(java_lang_Class != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700435 mirror::Class::SetClassClass(java_lang_Class.Get());
436 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700437 if (kUseBakerReadBarrier) {
438 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800439 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700440 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700441 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800442 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700443 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700444
Elliott Hughes418d20f2011-09-22 14:00:39 -0700445 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700446 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700447 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700448 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700449 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700450
Ian Rogers23435d02012-09-24 11:23:12 -0700451 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700452 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700453 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800454 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700455 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700456 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000457 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700458
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700459 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800460 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
461 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
462 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
463 java_lang_Object.Get(),
464 java_lang_Object->GetObjectSize(),
465 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700466
Igor Murashkin86083f72017-10-27 10:59:04 -0700467 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000468 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700469 // It might seem the lock here is unnecessary, however all the SubtypeCheck
470 // functions are annotated to require locks all the way down.
471 //
472 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
473 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000474 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
475 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700476 }
477
Ian Rogers23435d02012-09-24 11:23:12 -0700478 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700479 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700480 AllocClass(self, java_lang_Class.Get(),
481 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700482 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700483
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700484 // Setup the char (primitive) class to be used for char[].
485 Handle<mirror::Class> char_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700486 AllocClass(self, java_lang_Class.Get(),
487 mirror::Class::PrimitiveClassSize(image_pointer_size_))));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700488 // The primitive char class won't be initialized by
489 // InitializePrimitiveClass until line 459, but strings (and
490 // internal char arrays) will be allocated before that and the
491 // component size, which is computed from the primitive type, needs
492 // to be set here.
493 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700494
Ian Rogers23435d02012-09-24 11:23:12 -0700495 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700496 Handle<mirror::Class> char_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700497 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700498 char_array_class->SetComponentType(char_class.Get());
499 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700500
Ian Rogers23435d02012-09-24 11:23:12 -0700501 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700502 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700503 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700504 java_lang_String->SetStringClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700505 mirror::String::SetClass(java_lang_String.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000506 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400507
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700508 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700509 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700510 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700511 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
512 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000513 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700514
Ian Rogers23435d02012-09-24 11:23:12 -0700515 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700516 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700517 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
518 kClassRootsMax));
519 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700520 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
521 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
522 SetClassRoot(kClassArrayClass, class_array_class.Get());
523 SetClassRoot(kObjectArrayClass, object_array_class.Get());
524 SetClassRoot(kCharArrayClass, char_array_class.Get());
525 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700526 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700527
Mathieu Chartier6beced42016-11-15 15:51:31 -0800528 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
529 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
530
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700531 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700532 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
533 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
534 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
535 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
536 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
537 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
538 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
539 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700540
Ian Rogers23435d02012-09-24 11:23:12 -0700541 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700542 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700543
Ian Rogers23435d02012-09-24 11:23:12 -0700544 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700545 Handle<mirror::Class> int_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700546 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700547 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700548 mirror::IntArray::SetArrayClass(int_array_class.Get());
549 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700550
Mathieu Chartierc7853442015-03-27 14:35:38 -0700551 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
552 Handle<mirror::Class> long_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700553 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700554 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
555 mirror::LongArray::SetArrayClass(long_array_class.Get());
556 SetClassRoot(kLongArrayClass, long_array_class.Get());
557
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700558 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700559
Ian Rogers52813c92012-10-11 11:50:38 -0700560 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700561 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700562 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700563 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100564 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700565 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000566 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700567
Alex Lightd6251582016-10-31 11:12:30 -0700568
569 // Setup dalvik.system.ClassExt
570 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
571 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
572 SetClassRoot(kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
573 mirror::ClassExt::SetClass(dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000574 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700575
Mathieu Chartier66f19252012-09-18 08:57:04 -0700576 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700577 Handle<mirror::Class> object_array_string(hs.NewHandle(
578 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700579 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700580 object_array_string->SetComponentType(java_lang_String.Get());
581 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700582
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000583 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700584 // Create runtime resolution and imt conflict methods.
585 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000586 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
587 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700588
Ian Rogers23435d02012-09-24 11:23:12 -0700589 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
590 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
591 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800592 if (boot_class_path.empty()) {
593 *error_msg = "Boot classpath is empty.";
594 return false;
595 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800596 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800597 if (dex_file.get() == nullptr) {
598 *error_msg = "Null dex file.";
599 return false;
600 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700601 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800602 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700603 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700604
605 // now we can use FindSystemClass
606
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700607 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700608 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
609 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700610
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700611 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
612 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700613 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800614 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700615 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700616 quick_resolution_trampoline_ = GetQuickResolutionStub();
617 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
618 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700619 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700620
Alex Lightd6251582016-10-31 11:12:30 -0700621 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000622 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800623 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700624 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000625 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800626 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000627 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800628 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700629 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000630 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700631 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
632 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700633
Ian Rogers23435d02012-09-24 11:23:12 -0700634 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800635 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800636 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700637
Ian Rogers98379392014-02-24 16:53:16 -0800638 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800639 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700640
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800641 CheckSystemClass(self, char_array_class, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700642
Ian Rogers98379392014-02-24 16:53:16 -0800643 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800644 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700645
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800646 CheckSystemClass(self, int_array_class, "[I");
647 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700648
Ian Rogers98379392014-02-24 16:53:16 -0800649 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800650 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700651
Ian Rogers98379392014-02-24 16:53:16 -0800652 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800653 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700654
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800655 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
656 // in class_table_.
657 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700658
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800659 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
660 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700661
Ian Rogers23435d02012-09-24 11:23:12 -0700662 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700663 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800664 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700665 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800666 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700667 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
668 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700669 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
670 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700671
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700672 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
673 // suspension.
674 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000675 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700676 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000677 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700678 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000679 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700680 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000681 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700682
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700683 CHECK_EQ(object_array_string.Get(),
684 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700685
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800686 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700687
Ian Rogers23435d02012-09-24 11:23:12 -0700688 // Create java.lang.reflect.Proxy root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700689 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700690
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700691 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700692 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
693 CHECK(class_root != nullptr);
694 SetClassRoot(kJavaLangReflectField, class_root);
695 mirror::Field::SetClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700696
697 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700698 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
699 CHECK(class_root != nullptr);
700 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
701 mirror::Field::SetArrayClass(class_root);
702
703 // Create java.lang.reflect.Constructor.class root and array root.
704 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
705 CHECK(class_root != nullptr);
706 SetClassRoot(kJavaLangReflectConstructor, class_root);
707 mirror::Constructor::SetClass(class_root);
708 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
709 CHECK(class_root != nullptr);
710 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
711 mirror::Constructor::SetArrayClass(class_root);
712
713 // Create java.lang.reflect.Method.class root and array root.
714 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
715 CHECK(class_root != nullptr);
716 SetClassRoot(kJavaLangReflectMethod, class_root);
717 mirror::Method::SetClass(class_root);
718 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
719 CHECK(class_root != nullptr);
720 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
721 mirror::Method::SetArrayClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700722
Orion Hodson005ac512017-10-24 15:43:43 +0100723 // Create java.lang.invoke.CallSite.class root
724 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
725 CHECK(class_root != nullptr);
726 SetClassRoot(kJavaLangInvokeCallSite, class_root);
727 mirror::CallSite::SetClass(class_root);
728
Narayan Kamathafa48272016-08-03 12:46:58 +0100729 // Create java.lang.invoke.MethodType.class root
730 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
731 CHECK(class_root != nullptr);
732 SetClassRoot(kJavaLangInvokeMethodType, class_root);
733 mirror::MethodType::SetClass(class_root);
734
735 // Create java.lang.invoke.MethodHandleImpl.class root
736 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
737 CHECK(class_root != nullptr);
738 SetClassRoot(kJavaLangInvokeMethodHandleImpl, class_root);
739 mirror::MethodHandleImpl::SetClass(class_root);
740
Orion Hodsonc069a302017-01-18 09:23:12 +0000741 // Create java.lang.invoke.MethodHandles.Lookup.class root
742 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
743 CHECK(class_root != nullptr);
744 SetClassRoot(kJavaLangInvokeMethodHandlesLookup, class_root);
745 mirror::MethodHandlesLookup::SetClass(class_root);
746
Orion Hodson005ac512017-10-24 15:43:43 +0100747 // Create java.lang.invoke.VarHandle.class root
748 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000749 CHECK(class_root != nullptr);
Orion Hodson005ac512017-10-24 15:43:43 +0100750 SetClassRoot(kJavaLangInvokeVarHandle, class_root);
751 mirror::VarHandle::SetClass(class_root);
752
753 // Create java.lang.invoke.FieldVarHandle.class root
754 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
755 CHECK(class_root != nullptr);
756 SetClassRoot(kJavaLangInvokeFieldVarHandle, class_root);
757 mirror::FieldVarHandle::SetClass(class_root);
758
759 // Create java.lang.invoke.ArrayElementVarHandle.class root
760 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
761 CHECK(class_root != nullptr);
762 SetClassRoot(kJavaLangInvokeArrayElementVarHandle, class_root);
763 mirror::ArrayElementVarHandle::SetClass(class_root);
764
765 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
766 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
767 CHECK(class_root != nullptr);
768 SetClassRoot(kJavaLangInvokeByteArrayViewVarHandle, class_root);
769 mirror::ByteArrayViewVarHandle::SetClass(class_root);
770
771 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
772 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
773 CHECK(class_root != nullptr);
774 SetClassRoot(kJavaLangInvokeByteBufferViewVarHandle, class_root);
775 mirror::ByteBufferViewVarHandle::SetClass(class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000776
Narayan Kamath000e1882016-10-24 17:14:25 +0100777 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
778 CHECK(class_root != nullptr);
779 SetClassRoot(kDalvikSystemEmulatedStackFrame, class_root);
780 mirror::EmulatedStackFrame::SetClass(class_root);
781
Brian Carlstrom1f870082011-08-23 16:02:11 -0700782 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700783 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000784 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800785 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700786 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700787 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
788 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700789 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700790 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700791 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700792 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700793 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700794 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700795 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700796 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700797 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700798 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700799 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700800 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700801
Ian Rogers23435d02012-09-24 11:23:12 -0700802 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700803 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700804 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700805 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
806 SetClassRoot(kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700807
jeffhao8cd6dda2012-02-22 10:15:34 -0800808 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700809 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800810 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800811 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700812 SetClassRoot(kJavaLangClassNotFoundException,
813 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800814 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700815 SetClassRoot(kJavaLangStackTraceElementArrayClass,
816 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800817 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700818
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700819 // Create conflict tables that depend on the class linker.
820 runtime->FixupConflictTables();
821
Ian Rogers98379392014-02-24 16:53:16 -0800822 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700823
Brian Carlstroma004aa92012-02-08 18:05:09 -0800824 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800825
826 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700827}
828
Ian Rogers98379392014-02-24 16:53:16 -0800829void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800830 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700831
832 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700833 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700834 // as the types of the field can't be resolved prior to the runtime being
835 // fully initialized
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700836 StackHandleScope<2> hs(self);
837 Handle<mirror::Class> java_lang_ref_Reference = hs.NewHandle(GetClassRoot(kJavaLangRefReference));
838 Handle<mirror::Class> java_lang_ref_FinalizerReference =
839 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800840
Mathieu Chartierc7853442015-03-27 14:35:38 -0700841 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700842 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
843 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700844
Mathieu Chartierc7853442015-03-27 14:35:38 -0700845 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700846 CHECK_STREQ(queue->GetName(), "queue");
847 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700848
Mathieu Chartierc7853442015-03-27 14:35:38 -0700849 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700850 CHECK_STREQ(queueNext->GetName(), "queueNext");
851 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700852
Mathieu Chartierc7853442015-03-27 14:35:38 -0700853 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700854 CHECK_STREQ(referent->GetName(), "referent");
855 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700856
Mathieu Chartierc7853442015-03-27 14:35:38 -0700857 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700858 CHECK_STREQ(zombie->GetName(), "zombie");
859 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700860
Brian Carlstroma663ea52011-08-19 23:33:41 -0700861 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700862 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700863 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700864 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700865 CHECK(klass != nullptr);
866 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700867 // note SetClassRoot does additional validation.
868 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700869 }
870
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700871 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700872
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700873 // disable the slow paths in FindClass and CreatePrimitiveClass now
874 // that Object, Class, and Object[] are setup
875 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700876
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800877 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700878}
879
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700880void ClassLinker::RunRootClinits() {
881 Thread* self = Thread::Current();
882 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700883 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700884 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700885 StackHandleScope<1> hs(self);
886 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700887 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700888 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700889 }
890 }
891}
892
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200893// Set image methods' entry point to interpreter.
894class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
895 public:
Andreas Gampe542451c2016-07-26 09:02:02 -0700896 explicit SetInterpreterEntrypointArtMethodVisitor(PointerSize image_pointer_size)
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200897 : image_pointer_size_(image_pointer_size) {}
898
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700899 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200900 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
901 CHECK(method->GetDeclaringClass() != nullptr);
902 }
903 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
904 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
905 image_pointer_size_);
906 }
907 }
908
909 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700910 const PointerSize image_pointer_size_;
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200911
912 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
913};
914
Jeff Haodcdc85b2015-12-04 14:06:18 -0800915struct TrampolineCheckData {
916 const void* quick_resolution_trampoline;
917 const void* quick_imt_conflict_trampoline;
918 const void* quick_generic_jni_trampoline;
919 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700920 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800921 ArtMethod* m;
922 bool error;
923};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800924
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800925bool ClassLinker::InitFromBootImage(std::string* error_msg) {
926 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700927 CHECK(!init_done_);
928
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700929 Runtime* const runtime = Runtime::Current();
930 Thread* const self = Thread::Current();
931 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800932 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
933 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700934 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
935 if (!ValidPointerSize(pointer_size_unchecked)) {
936 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800937 return false;
938 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700939 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800940 if (!runtime->IsAotCompiler()) {
941 // Only the Aot compiler supports having an image with a different pointer size than the
942 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
943 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700944 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800945 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700946 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800947 sizeof(void*));
948 return false;
949 }
950 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800951 std::vector<const OatFile*> oat_files =
952 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
953 DCHECK(!oat_files.empty());
954 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800955 CHECK_EQ(default_oat_header.GetImageFileLocationOatDataBegin(), 0U);
956 const char* image_file_location = oat_files[0]->GetOatHeader().
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700957 GetStoreValueByKey(OatHeader::kImageLocationKey);
958 CHECK(image_file_location == nullptr || *image_file_location == 0);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800959 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
960 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
961 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
962 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
963 if (kIsDebugBuild) {
964 // Check that the other images use the same trampoline.
965 for (size_t i = 1; i < oat_files.size(); ++i) {
966 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
967 const void* ith_quick_resolution_trampoline =
968 ith_oat_header.GetQuickResolutionTrampoline();
969 const void* ith_quick_imt_conflict_trampoline =
970 ith_oat_header.GetQuickImtConflictTrampoline();
971 const void* ith_quick_generic_jni_trampoline =
972 ith_oat_header.GetQuickGenericJniTrampoline();
973 const void* ith_quick_to_interpreter_bridge_trampoline =
974 ith_oat_header.GetQuickToInterpreterBridge();
975 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
976 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
977 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
978 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
979 // Make sure that all methods in this image do not contain those trampolines as
980 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
981 TrampolineCheckData data;
982 data.error = false;
983 data.pointer_size = GetImagePointerSize();
984 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
985 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
986 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
987 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
988 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700989 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
990 if (obj->IsClass()) {
991 ObjPtr<mirror::Class> klass = obj->AsClass();
992 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
993 const void* entrypoint =
994 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
995 if (entrypoint == data.quick_resolution_trampoline ||
996 entrypoint == data.quick_imt_conflict_trampoline ||
997 entrypoint == data.quick_generic_jni_trampoline ||
998 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
999 data.m = &m;
1000 data.error = true;
1001 return;
1002 }
1003 }
1004 }
1005 };
1006 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001007 if (data.error) {
1008 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001009 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001010 *error_msg = "Found an ArtMethod with a bad entrypoint";
1011 return false;
1012 }
1013 }
1014 }
1015 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001016
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001017 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
1018 down_cast<mirror::ObjectArray<mirror::Class>*>(
1019 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)));
1020 mirror::Class::SetClassClass(class_roots_.Read()->Get(kJavaLangClass));
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001021
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001022 // Special case of setting up the String class early so that we can test arbitrary objects
1023 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001024 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001025
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001026 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot(kJavaLangObject);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001027 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001028 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1029 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001030 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1031 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001032
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001033 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001034 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001035 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001036 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001037 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
1038 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001039 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
1040 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
1041 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
1042 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
Orion Hodson005ac512017-10-24 15:43:43 +01001043 mirror::CallSite::SetClass(GetClassRoot(kJavaLangInvokeCallSite));
Narayan Kamathafa48272016-08-03 12:46:58 +01001044 mirror::MethodHandleImpl::SetClass(GetClassRoot(kJavaLangInvokeMethodHandleImpl));
Orion Hodsonc069a302017-01-18 09:23:12 +00001045 mirror::MethodHandlesLookup::SetClass(GetClassRoot(kJavaLangInvokeMethodHandlesLookup));
Orion Hodson005ac512017-10-24 15:43:43 +01001046 mirror::MethodType::SetClass(GetClassRoot(kJavaLangInvokeMethodType));
1047 mirror::VarHandle::SetClass(GetClassRoot(kJavaLangInvokeVarHandle));
1048 mirror::FieldVarHandle::SetClass(GetClassRoot(kJavaLangInvokeFieldVarHandle));
1049 mirror::ArrayElementVarHandle::SetClass(GetClassRoot(kJavaLangInvokeArrayElementVarHandle));
1050 mirror::ByteArrayViewVarHandle::SetClass(GetClassRoot(kJavaLangInvokeByteArrayViewVarHandle));
1051 mirror::ByteBufferViewVarHandle::SetClass(GetClassRoot(kJavaLangInvokeByteBufferViewVarHandle));
Fred Shih4ee7a662014-07-11 09:59:27 -07001052 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001053 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1054 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1055 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1056 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1057 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1058 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1059 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1060 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1061 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1062 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Narayan Kamath000e1882016-10-24 17:14:25 +01001063 mirror::EmulatedStackFrame::SetClass(GetClassRoot(kDalvikSystemEmulatedStackFrame));
Alex Lightd6251582016-10-31 11:12:30 -07001064 mirror::ClassExt::SetClass(GetClassRoot(kDalvikSystemClassExt));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001065
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001066 for (gc::space::ImageSpace* image_space : spaces) {
1067 // Boot class loader, use a null handle.
1068 std::vector<std::unique_ptr<const DexFile>> dex_files;
1069 if (!AddImageSpace(image_space,
1070 ScopedNullHandle<mirror::ClassLoader>(),
1071 /*dex_elements*/nullptr,
1072 /*dex_location*/nullptr,
1073 /*out*/&dex_files,
1074 error_msg)) {
1075 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001076 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001077 // Append opened dex files at the end.
1078 boot_dex_files_.insert(boot_dex_files_.end(),
1079 std::make_move_iterator(dex_files.begin()),
1080 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001081 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001082 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1083 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1084 }
Ian Rogers98379392014-02-24 16:53:16 -08001085 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001086
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001087 VLOG(startup) << __FUNCTION__ << " exiting";
1088 return true;
1089}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001090
Jeff Hao5872d7c2016-04-27 11:07:41 -07001091bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001092 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001093 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001094 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1095 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001096}
1097
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001098static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1099 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001100 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001101 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001102 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001103 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001104 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001105 DCHECK(dex_file_field != nullptr);
1106 DCHECK(dex_file_name_field != nullptr);
1107 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001108 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001109 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001110 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001111 // Null dex file means it was probably a jar with no dex files, return a null string.
1112 *out_name = nullptr;
1113 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001114 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001115 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001116 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001117 *out_name = name_object->AsString();
1118 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001119 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001120 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001121}
1122
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001123static bool FlattenPathClassLoader(ObjPtr<mirror::ClassLoader> class_loader,
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001124 std::list<ObjPtr<mirror::String>>* out_dex_file_names,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001125 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001126 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001127 DCHECK(out_dex_file_names != nullptr);
1128 DCHECK(error_msg != nullptr);
1129 ScopedObjectAccessUnchecked soa(Thread::Current());
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001130 StackHandleScope<1> hs(soa.Self());
1131 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Jeff Hao5872d7c2016-04-27 11:07:41 -07001132 while (!ClassLinker::IsBootClassLoader(soa, class_loader)) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07001133 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1134 class_loader->GetClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001135 *error_msg = StringPrintf("Unknown class loader type %s",
1136 class_loader->PrettyTypeOf().c_str());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001137 // Unsupported class loader.
1138 return false;
1139 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001140 // Get element names. Sets error to true on failure.
1141 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1142 REQUIRES_SHARED(Locks::mutator_lock_) {
1143 if (element == nullptr) {
1144 *error_msg = "Null dex element";
1145 *error = true; // Null element is a critical error.
1146 return false; // Had an error, stop the visit.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001147 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001148 ObjPtr<mirror::String> name;
1149 if (!GetDexPathListElementName(element, &name)) {
1150 *error_msg = "Invalid dex path list element";
1151 *error = false; // Invalid element is not a critical error.
1152 return false; // Stop the visit.
1153 }
1154 if (name != nullptr) {
1155 out_dex_file_names->push_front(name.Ptr());
1156 }
1157 return true; // Continue with the next Element.
1158 };
1159 bool error = VisitClassLoaderDexElements(soa, handle, add_element_names, /* error */ false);
1160 if (error) {
1161 // An error occurred during DexPathList Element visiting.
1162 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001163 }
1164 class_loader = class_loader->GetParent();
1165 }
1166 return true;
1167}
1168
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001169class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1170 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001171 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001172 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1173
1174 virtual void Visit(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001175 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001176 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked();
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001177 if (klass != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001178 CHECK(live_bitmap_->Test(klass.Ptr())) << "Image method has unmarked declaring class";
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001179 }
1180 }
1181
1182 private:
1183 gc::accounting::HeapBitmap* const live_bitmap_;
1184};
1185
Chang Xingba17dbd2017-06-28 21:27:56 +00001186class FixupInternVisitor {
1187 public:
1188 ALWAYS_INLINE ObjPtr<mirror::Object> TryInsertIntern(mirror::Object* obj) const
1189 REQUIRES_SHARED(Locks::mutator_lock_) {
1190 if (obj != nullptr && obj->IsString()) {
1191 const auto intern = Runtime::Current()->GetInternTable()->InternStrong(obj->AsString());
1192 return intern;
1193 }
1194 return obj;
1195 }
1196
1197 ALWAYS_INLINE void VisitRootIfNonNull(
1198 mirror::CompressedReference<mirror::Object>* root) const
1199 REQUIRES_SHARED(Locks::mutator_lock_) {
1200 if (!root->IsNull()) {
1201 VisitRoot(root);
1202 }
1203 }
1204
1205 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1206 REQUIRES_SHARED(Locks::mutator_lock_) {
1207 root->Assign(TryInsertIntern(root->AsMirrorPtr()));
1208 }
1209
1210 // Visit Class Fields
1211 ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
1212 MemberOffset offset,
1213 bool is_static ATTRIBUTE_UNUSED) const
1214 REQUIRES_SHARED(Locks::mutator_lock_) {
1215 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1216 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1217 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1218 // Updating images, don't do a read barrier.
1219 // Only string fields are fixed, don't do a verify.
1220 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
1221 offset);
1222 obj->SetFieldObject<false, false>(offset, TryInsertIntern(ref));
1223 }
1224 }
1225
1226 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1227 ObjPtr<mirror::Reference> ref) const
1228 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1229 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1230 }
1231
1232 void operator()(mirror::Object* obj) const
1233 REQUIRES_SHARED(Locks::mutator_lock_) {
1234 if (obj->IsDexCache()) {
1235 obj->VisitReferences<true, kVerifyNone, kWithoutReadBarrier>(*this, *this);
1236 } else {
1237 // Don't visit native roots for non-dex-cache
1238 obj->VisitReferences<false, kVerifyNone, kWithoutReadBarrier>(*this, *this);
1239 }
1240 }
1241};
1242
Andreas Gampe2af99022017-04-25 08:32:59 -07001243// new_class_set is the set of classes that were read from the class table section in the image.
1244// If there was no class table section, it is null.
1245// Note: using a class here to avoid having to make ClassLinker internals public.
1246class AppImageClassLoadersAndDexCachesHelper {
1247 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001248 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001249 ClassLinker* class_linker,
1250 gc::space::ImageSpace* space,
1251 Handle<mirror::ClassLoader> class_loader,
1252 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001253 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001254 REQUIRES(!Locks::dex_lock_)
1255 REQUIRES_SHARED(Locks::mutator_lock_);
1256};
1257
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001258void AppImageClassLoadersAndDexCachesHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001259 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001260 gc::space::ImageSpace* space,
1261 Handle<mirror::ClassLoader> class_loader,
1262 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001263 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001264 REQUIRES(!Locks::dex_lock_)
1265 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001266 Thread* const self = Thread::Current();
1267 gc::Heap* const heap = Runtime::Current()->GetHeap();
1268 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001269 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001270 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001271 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001272 const size_t num_dex_caches = dex_caches->GetLength();
1273 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001274 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001275 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001276 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001277 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001278 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1279 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001280 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001281 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001282 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001283 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001284 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001285 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001286 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001287 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001288 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001289 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001290 auto it = new_class_set->Find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001291 DCHECK(it != new_class_set->end());
1292 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001293 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001294 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001295 auto it2 = new_class_set->Find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001296 DCHECK(it2 != new_class_set->end());
1297 DCHECK_EQ(it2->Read(), super_class);
1298 }
1299 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1300 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001301 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1302 if (!class_linker->IsQuickResolutionStub(code) &&
1303 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001304 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001305 !m.IsNative()) {
1306 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001307 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001308 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01001309 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1310 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001311 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1312 if (!class_linker->IsQuickResolutionStub(code) &&
1313 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001314 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001315 !m.IsNative()) {
1316 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001317 }
1318 }
1319 }
1320 }
1321 }
1322 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001323 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001324 {
1325 // Fixup all the literal strings happens at app images which are supposed to be interned.
1326 ScopedTrace timing("Fixup String Intern in image and dex_cache");
1327 const auto& image_header = space->GetImageHeader();
1328 const auto bitmap = space->GetMarkBitmap(); // bitmap of objects
1329 const uint8_t* target_base = space->GetMemMap()->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001330 const ImageSection& objects_section = image_header.GetObjectsSection();
Chang Xingba17dbd2017-06-28 21:27:56 +00001331
1332 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1333 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1334
1335 FixupInternVisitor fixup_intern_visitor;
1336 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_intern_visitor);
1337 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001338 if (kVerifyArtMethodDeclaringClasses) {
1339 ScopedTrace timing("Verify declaring classes");
1340 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1341 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001342 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001343 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001344}
1345
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001346// Update the class loader. Should only be used on classes in the image space.
1347class UpdateClassLoaderVisitor {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001348 public:
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001349 UpdateClassLoaderVisitor(gc::space::ImageSpace* space, ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001350 : space_(space),
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001351 class_loader_(class_loader) {}
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001352
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001353 bool operator()(ObjPtr<mirror::Class> klass) const REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001354 // Do not update class loader for boot image classes where the app image
1355 // class loader is only the initiating loader but not the defining loader.
1356 if (klass->GetClassLoader() != nullptr) {
1357 klass->SetClassLoader(class_loader_);
1358 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001359 return true;
1360 }
1361
1362 gc::space::ImageSpace* const space_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001363 ObjPtr<mirror::ClassLoader> const class_loader_;
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001364};
1365
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001366static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1367 const char* location,
1368 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001369 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001370 DCHECK(error_msg != nullptr);
1371 std::unique_ptr<const DexFile> dex_file;
Richard Uhler9a37efc2016-08-05 16:32:55 -07001372 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001373 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001374 return std::unique_ptr<const DexFile>();
1375 }
1376 std::string inner_error_msg;
1377 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1378 if (dex_file == nullptr) {
1379 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1380 location,
1381 oat_file->GetLocation().c_str(),
1382 inner_error_msg.c_str());
1383 return std::unique_ptr<const DexFile>();
1384 }
1385
1386 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1387 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1388 location,
1389 dex_file->GetLocationChecksum(),
1390 oat_dex_file->GetDexFileLocationChecksum());
1391 return std::unique_ptr<const DexFile>();
1392 }
1393 return dex_file;
1394}
1395
1396bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1397 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1398 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001399 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001400 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001401 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001402 DCHECK(dex_caches_object != nullptr);
1403 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1404 dex_caches_object->AsObjectArray<mirror::DexCache>();
1405 const OatFile* oat_file = space->GetOatFile();
1406 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001407 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001408 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1409 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1410 dex_file_location.c_str(),
1411 error_msg);
1412 if (dex_file == nullptr) {
1413 return false;
1414 }
1415 dex_cache->SetDexFile(dex_file.get());
1416 out_dex_files->push_back(std::move(dex_file));
1417 }
1418 return true;
1419}
1420
Andreas Gampe0793bec2016-12-01 11:37:33 -08001421// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1422// together and caches some intermediate results.
1423class ImageSanityChecks FINAL {
1424 public:
1425 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1426 REQUIRES_SHARED(Locks::mutator_lock_) {
1427 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001428 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1429 DCHECK(obj != nullptr);
1430 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1431 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1432 if (obj->IsClass()) {
1433 auto klass = obj->AsClass();
1434 for (ArtField& field : klass->GetIFields()) {
1435 CHECK_EQ(field.GetDeclaringClass(), klass);
1436 }
1437 for (ArtField& field : klass->GetSFields()) {
1438 CHECK_EQ(field.GetDeclaringClass(), klass);
1439 }
1440 const auto pointer_size = isc.pointer_size_;
1441 for (auto& m : klass->GetMethods(pointer_size)) {
1442 isc.SanityCheckArtMethod(&m, klass);
1443 }
1444 auto* vtable = klass->GetVTable();
1445 if (vtable != nullptr) {
1446 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1447 }
1448 if (klass->ShouldHaveImt()) {
1449 ImTable* imt = klass->GetImt(pointer_size);
1450 for (size_t i = 0; i < ImTable::kSize; ++i) {
1451 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1452 }
1453 }
1454 if (klass->ShouldHaveEmbeddedVTable()) {
1455 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1456 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1457 }
1458 }
1459 mirror::IfTable* iftable = klass->GetIfTable();
1460 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1461 if (iftable->GetMethodArrayCount(i) > 0) {
1462 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1463 }
1464 }
1465 }
1466 };
1467 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001468 }
1469
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001470 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1471 ClassLinker* class_linker,
1472 mirror::MethodDexCacheType* arr,
1473 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001474 REQUIRES_SHARED(Locks::mutator_lock_) {
1475 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001476 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001477 }
1478
Andreas Gampe0793bec2016-12-01 11:37:33 -08001479 private:
1480 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1481 : spaces_(heap->GetBootImageSpaces()),
1482 pointer_size_(class_linker->GetImagePointerSize()) {
1483 space_begin_.reserve(spaces_.size());
1484 method_sections_.reserve(spaces_.size());
1485 runtime_method_sections_.reserve(spaces_.size());
1486 for (gc::space::ImageSpace* space : spaces_) {
1487 space_begin_.push_back(space->Begin());
1488 auto& header = space->GetImageHeader();
1489 method_sections_.push_back(&header.GetMethodsSection());
1490 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1491 }
1492 }
1493
1494 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1495 REQUIRES_SHARED(Locks::mutator_lock_) {
1496 if (m->IsRuntimeMethod()) {
1497 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1498 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1499 } else if (m->IsCopied()) {
1500 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1501 } else if (expected_class != nullptr) {
1502 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1503 }
1504 if (!spaces_.empty()) {
1505 bool contains = false;
1506 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1507 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1508 contains = method_sections_[i]->Contains(offset) ||
1509 runtime_method_sections_[i]->Contains(offset);
1510 }
1511 CHECK(contains) << m << " not found";
1512 }
1513 }
1514
1515 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1516 ObjPtr<mirror::Class> expected_class)
1517 REQUIRES_SHARED(Locks::mutator_lock_) {
1518 CHECK(arr != nullptr);
1519 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1520 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1521 // expected_class == null means we are a dex cache.
1522 if (expected_class != nullptr) {
1523 CHECK(method != nullptr);
1524 }
1525 if (method != nullptr) {
1526 SanityCheckArtMethod(method, expected_class);
1527 }
1528 }
1529 }
1530
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001531 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001532 REQUIRES_SHARED(Locks::mutator_lock_) {
1533 CHECK_EQ(arr != nullptr, size != 0u);
1534 if (arr != nullptr) {
1535 bool contains = false;
1536 for (auto space : spaces_) {
1537 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001538 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001539 contains = true;
1540 break;
1541 }
1542 }
1543 CHECK(contains);
1544 }
1545 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001546 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1547 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001548 // expected_class == null means we are a dex cache.
1549 if (method != nullptr) {
1550 SanityCheckArtMethod(method, nullptr);
1551 }
1552 }
1553 }
1554
1555 const std::vector<gc::space::ImageSpace*>& spaces_;
1556 const PointerSize pointer_size_;
1557
1558 // Cached sections from the spaces.
1559 std::vector<const uint8_t*> space_begin_;
1560 std::vector<const ImageSection*> method_sections_;
1561 std::vector<const ImageSection*> runtime_method_sections_;
1562};
1563
Andreas Gampebe7af222017-07-25 09:57:28 -07001564static void VerifyAppImage(const ImageHeader& header,
1565 const Handle<mirror::ClassLoader>& class_loader,
1566 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1567 ClassTable* class_table, gc::space::ImageSpace* space)
1568 REQUIRES_SHARED(Locks::mutator_lock_) {
1569 {
1570 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1571 public:
1572 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1573
1574 virtual void Visit(ArtMethod* method)
1575 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
1576 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1577 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1578 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << mirror::Class::PrettyClass(klass);
1579 }
1580 }
1581
1582 private:
1583 ClassTable* const table_;
1584 };
1585 VerifyClassInTableArtMethodVisitor visitor(class_table);
1586 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
1587 }
1588 {
1589 // Verify that all direct interfaces of classes in the class table are also resolved.
1590 std::vector<ObjPtr<mirror::Class>> classes;
1591 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1592 REQUIRES_SHARED(Locks::mutator_lock_) {
1593 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1594 classes.push_back(klass);
1595 }
1596 return true;
1597 };
1598 class_table->Visit(verify_direct_interfaces_in_table);
1599 Thread* self = Thread::Current();
1600 for (ObjPtr<mirror::Class> klass : classes) {
1601 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1602 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1603 << klass->PrettyDescriptor() << " iface #" << i;
1604 }
1605 }
1606 }
1607 // Check that all non-primitive classes in dex caches are also in the class table.
1608 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1609 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1610 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1611 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1612 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1613 if (klass != nullptr && !klass->IsPrimitive()) {
1614 CHECK(class_table->Contains(klass))
1615 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1616 }
1617 }
1618 }
1619}
1620
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001621bool ClassLinker::AddImageSpace(
1622 gc::space::ImageSpace* space,
1623 Handle<mirror::ClassLoader> class_loader,
1624 jobjectArray dex_elements,
1625 const char* dex_location,
1626 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1627 std::string* error_msg) {
1628 DCHECK(out_dex_files != nullptr);
1629 DCHECK(error_msg != nullptr);
1630 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001631 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001632 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001633 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001634 DCHECK(dex_caches_object != nullptr);
1635 Runtime* const runtime = Runtime::Current();
1636 gc::Heap* const heap = runtime->GetHeap();
1637 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001638 // Check that the image is what we are expecting.
1639 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1640 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1641 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1642 image_pointer_size_);
1643 return false;
1644 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001645 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1646 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1647 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1648 expected_image_roots,
1649 header.GetImageRoots()->GetLength());
1650 return false;
1651 }
1652 StackHandleScope<3> hs(self);
1653 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1654 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1655 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1656 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
1657 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1658 "Class loader should be the last image root.");
1659 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
1660 app_image ? header.GetImageRoot(ImageHeader::kClassLoader)->AsClassLoader() : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001661 DCHECK(class_roots != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001662 if (class_roots->GetLength() != static_cast<int32_t>(kClassRootsMax)) {
1663 *error_msg = StringPrintf("Expected %d class roots but got %d",
1664 class_roots->GetLength(),
1665 static_cast<int32_t>(kClassRootsMax));
1666 return false;
1667 }
1668 // Check against existing class roots to make sure they match the ones in the boot image.
1669 for (size_t i = 0; i < kClassRootsMax; i++) {
1670 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i))) {
1671 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1672 return false;
1673 }
1674 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001675 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001676 if (oat_file->GetOatHeader().GetDexFileCount() !=
1677 static_cast<uint32_t>(dex_caches->GetLength())) {
1678 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1679 "image";
1680 return false;
1681 }
1682
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001683 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001684 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1685 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001686 // TODO: Only store qualified paths.
1687 // If non qualified, qualify it.
1688 if (dex_file_location.find('/') == std::string::npos) {
1689 std::string dex_location_path = dex_location;
1690 const size_t pos = dex_location_path.find_last_of('/');
1691 CHECK_NE(pos, std::string::npos);
1692 dex_location_path = dex_location_path.substr(0, pos + 1); // Keep trailing '/'
1693 dex_file_location = dex_location_path + dex_file_location;
1694 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001695 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1696 dex_file_location.c_str(),
1697 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001698 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001699 return false;
1700 }
1701
1702 if (app_image) {
1703 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
1704 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00001705 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001706 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00001707 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001708 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001709 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001710 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001711 }
1712 }
1713 } else {
1714 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001715 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
1716 this,
1717 dex_cache->GetResolvedMethods(),
1718 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001719 }
1720 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00001721 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001722 }
1723 out_dex_files->push_back(std::move(dex_file));
1724 }
1725
1726 if (app_image) {
1727 ScopedObjectAccessUnchecked soa(Thread::Current());
1728 // Check that the class loader resolves the same way as the ones in the image.
1729 // Image class loader [A][B][C][image dex files]
1730 // Class loader = [???][dex_elements][image dex files]
1731 // Need to ensure that [???][dex_elements] == [A][B][C].
1732 // For each class loader, PathClassLoader, the laoder checks the parent first. Also the logic
1733 // for PathClassLoader does this by looping through the array of dex files. To ensure they
1734 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
1735 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001736 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1737 *error_msg = "Unexpected BootClassLoader in app image";
1738 return false;
1739 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001740 std::list<ObjPtr<mirror::String>> image_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001741 std::string temp_error_msg;
1742 if (!FlattenPathClassLoader(image_class_loader.Get(), &image_dex_file_names, &temp_error_msg)) {
1743 *error_msg = StringPrintf("Failed to flatten image class loader hierarchy '%s'",
1744 temp_error_msg.c_str());
1745 return false;
1746 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001747 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001748 if (!FlattenPathClassLoader(class_loader.Get(), &loader_dex_file_names, &temp_error_msg)) {
1749 *error_msg = StringPrintf("Failed to flatten class loader hierarchy '%s'",
1750 temp_error_msg.c_str());
1751 return false;
1752 }
1753 // Add the temporary dex path list elements at the end.
1754 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
1755 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
1756 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
1757 if (element != nullptr) {
1758 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001759 ObjPtr<mirror::String> name;
1760 if (GetDexPathListElementName(element, &name) && name != nullptr) {
1761 loader_dex_file_names.push_back(name);
1762 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01001763 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001764 }
1765 // Ignore the number of image dex files since we are adding those to the class loader anyways.
1766 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
1767 static_cast<size_t>(dex_caches->GetLength()));
1768 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
1769 // Check that the dex file names match.
1770 bool equal = image_count == loader_dex_file_names.size();
1771 if (equal) {
1772 auto it1 = image_dex_file_names.begin();
1773 auto it2 = loader_dex_file_names.begin();
1774 for (size_t i = 0; equal && i < image_count; ++i, ++it1, ++it2) {
1775 equal = equal && (*it1)->Equals(*it2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001776 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001777 }
1778 if (!equal) {
1779 VLOG(image) << "Image dex files " << image_dex_file_names.size();
1780 for (ObjPtr<mirror::String> name : image_dex_file_names) {
1781 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001782 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001783 VLOG(image) << "Loader dex files " << loader_dex_file_names.size();
1784 for (ObjPtr<mirror::String> name : loader_dex_file_names) {
1785 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001786 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001787 *error_msg = "Rejecting application image due to class loader mismatch";
1788 // Ignore class loader mismatch for now since these would just use possibly incorrect
1789 // oat code anyways. The structural class check should be done in the parent.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001790 }
1791 }
1792
1793 if (kSanityCheckObjects) {
1794 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1795 auto* dex_cache = dex_caches->Get(i);
1796 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
1797 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
1798 if (field != nullptr) {
1799 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
1800 }
1801 }
1802 }
1803 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001804 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001805 }
1806 }
1807
1808 // Set entry point to interpreter if in InterpretOnly mode.
1809 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001810 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001811 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001812 }
1813
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001814 ClassTable* class_table = nullptr;
1815 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001816 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001817 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08001818 }
1819 // If we have a class table section, read it and use it for verification in
1820 // UpdateAppImageClassLoadersAndDexCaches.
1821 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001822 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08001823 const bool added_class_table = class_table_section.Size() > 0u;
1824 if (added_class_table) {
1825 const uint64_t start_time2 = NanoTime();
1826 size_t read_count = 0;
1827 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
1828 /*make copy*/false,
1829 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08001830 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001831 }
1832 if (app_image) {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001833 AppImageClassLoadersAndDexCachesHelper::Update(this,
1834 space,
1835 class_loader,
1836 dex_caches,
1837 &temp_set);
Mathieu Chartier69731002016-03-02 16:08:31 -08001838 // Update class loader and resolved strings. If added_class_table is false, the resolved
1839 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001840 UpdateClassLoaderVisitor visitor(space, class_loader.Get());
1841 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001842 visitor(root.Read());
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001843 }
Igor Murashkin86083f72017-10-27 10:59:04 -07001844
Vladimir Marko305c38b2018-02-14 11:50:07 +00001845 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07001846 // Every class in the app image has initially SubtypeCheckInfo in the
1847 // Uninitialized state.
1848 //
1849 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
1850 // after class initialization is complete. The app image ClassStatus as-is
1851 // are almost all ClassStatus::Initialized, and being in the
1852 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
1853 //
1854 // Force every app image class's SubtypeCheck to be at least kIninitialized.
1855 //
1856 // See also ImageWriter::FixupClass.
1857 ScopedTrace trace("Recalculate app image SubtypeCheck bitstrings");
1858 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
1859 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00001860 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07001861 }
1862 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001863 }
1864 if (!oat_file->GetBssGcRoots().empty()) {
1865 // Insert oat file to class table for visiting .bss GC roots.
1866 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001867 }
Igor Murashkin86083f72017-10-27 10:59:04 -07001868
Mathieu Chartier69731002016-03-02 16:08:31 -08001869 if (added_class_table) {
1870 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1871 class_table->AddClassSet(std::move(temp_set));
1872 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001873
Mathieu Chartier69731002016-03-02 16:08:31 -08001874 if (kIsDebugBuild && app_image) {
1875 // This verification needs to happen after the classes have been added to the class loader.
1876 // Since it ensures classes are in the class table.
Andreas Gampeacbd98b2017-10-12 10:44:11 -07001877 ScopedTrace trace("VerifyAppImage");
Andreas Gampebe7af222017-07-25 09:57:28 -07001878 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08001879 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001880
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001881 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001882 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001883}
1884
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001885bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001886 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
1887 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001888}
1889
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001890void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001891 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
1892 // enabling tracing requires the mutator lock, there are no race conditions here.
1893 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001894 Thread* const self = Thread::Current();
1895 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001896 if (kUseReadBarrier) {
1897 // We do not track new roots for CC.
1898 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
1899 kVisitRootFlagClearRootLog |
1900 kVisitRootFlagStartLoggingNewRoots |
1901 kVisitRootFlagStopLoggingNewRoots));
1902 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001903 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001904 // Argument for how root visiting deals with ArtField and ArtMethod roots.
1905 // There is 3 GC cases to handle:
1906 // Non moving concurrent:
1907 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001908 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001909 //
1910 // Moving non-concurrent:
1911 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
1912 // To prevent missing roots, this case needs to ensure that there is no
1913 // suspend points between the point which we allocate ArtMethod arrays and place them in a
1914 // class which is in the class table.
1915 //
1916 // Moving concurrent:
1917 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
1918 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001919 //
1920 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
1921 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
1922 // these objects.
1923 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07001924 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07001925 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09001926 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001927 for (const ClassLoaderData& data : class_loaders_) {
1928 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
1929 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
1930 }
1931 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001932 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001933 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001934 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001935 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001936 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001937 // Concurrent moving GC marked new roots through the to-space invariant.
1938 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001939 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001940 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
1941 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
1942 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
1943 if (old_ref != nullptr) {
1944 DCHECK(old_ref->IsClass());
1945 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
1946 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
1947 // Concurrent moving GC marked new roots through the to-space invariant.
1948 CHECK_EQ(new_ref, old_ref);
1949 }
1950 }
1951 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001952 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001953 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001954 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00001955 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001956 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001957 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001958 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001959 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001960 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001961 }
1962 // We deliberately ignore the class roots in the image since we
1963 // handle image roots by using the MS/CMS rescanning of dirty cards.
1964}
1965
Brian Carlstroma663ea52011-08-19 23:33:41 -07001966// Keep in sync with InitCallback. Anything we visit, we need to
1967// reinit references to when reinitializing a ClassLinker from a
1968// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001969void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07001970 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001971 VisitClassRoots(visitor, flags);
Mathieu Chartier31000802015-06-14 14:14:37 -07001972 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07001973 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
1974 // unloading if we are marking roots.
1975 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001976}
1977
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001978class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
1979 public:
1980 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
1981 : visitor_(visitor),
1982 done_(false) {}
1983
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001984 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001985 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001986 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001987 if (!done_ && class_table != nullptr) {
1988 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
1989 if (!class_table->Visit(visitor)) {
1990 // If the visitor ClassTable returns false it means that we don't need to continue.
1991 done_ = true;
1992 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001993 }
1994 }
1995
1996 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001997 // Class visitor that limits the class visits from a ClassTable to the classes with
1998 // the provided defining class loader. This filter is used to avoid multiple visits
1999 // of the same class which can be recorded for multiple initiating class loaders.
2000 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2001 public:
2002 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2003 ClassVisitor* visitor)
2004 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2005
2006 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
2007 if (klass->GetClassLoader() != defining_class_loader_) {
2008 return true;
2009 }
2010 return (*visitor_)(klass);
2011 }
2012
2013 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2014 ClassVisitor* const visitor_;
2015 };
2016
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002017 ClassVisitor* const visitor_;
2018 // If done is true then we don't need to do any more visiting.
2019 bool done_;
2020};
2021
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002022void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002023 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002024 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2025 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002026 }
2027}
2028
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002029void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002030 Thread* const self = Thread::Current();
2031 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2032 // Not safe to have thread suspension when we are holding a lock.
2033 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002034 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002035 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002036 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002037 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002038 }
2039}
2040
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002041class GetClassesInToVector : public ClassVisitor {
2042 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002043 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002044 classes_.push_back(klass);
2045 return true;
2046 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002047 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002048};
2049
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002050class GetClassInToObjectArray : public ClassVisitor {
2051 public:
2052 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2053 : arr_(arr), index_(0) {}
2054
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002055 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002056 ++index_;
2057 if (index_ <= arr_->GetLength()) {
2058 arr_->Set(index_ - 1, klass);
2059 return true;
2060 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002061 return false;
2062 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002063
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002064 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002065 return index_ <= arr_->GetLength();
2066 }
2067
2068 private:
2069 mirror::ObjectArray<mirror::Class>* const arr_;
2070 int32_t index_;
2071};
2072
2073void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002074 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2075 // is avoiding duplicates.
2076 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002077 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002078 GetClassesInToVector accumulator;
2079 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002080 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002081 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002082 return;
2083 }
2084 }
2085 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002086 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002087 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002088 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002089 // We size the array assuming classes won't be added to the class table during the visit.
2090 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002091 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002092 size_t class_table_size;
2093 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002094 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002095 // Add 100 in case new classes get loaded when we are filling in the object array.
2096 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002097 }
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07002098 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002099 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002100 classes.Assign(
2101 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002102 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002103 GetClassInToObjectArray accumulator(classes.Get());
2104 VisitClasses(&accumulator);
2105 if (accumulator.Succeeded()) {
2106 break;
2107 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002108 }
2109 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2110 // If the class table shrank during creation of the clases array we expect null elements. If
2111 // the class table grew then the loop repeats. If classes are created after the loop has
2112 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002113 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002114 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002115 return;
2116 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002117 }
2118 }
2119}
2120
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002121ClassLinker::~ClassLinker() {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002122 mirror::Class::ResetClass();
2123 mirror::Constructor::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07002124 mirror::Field::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002125 mirror::Method::ResetClass();
2126 mirror::Reference::ResetClass();
2127 mirror::StackTraceElement::ResetClass();
2128 mirror::String::ResetClass();
2129 mirror::Throwable::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002130 mirror::BooleanArray::ResetArrayClass();
2131 mirror::ByteArray::ResetArrayClass();
2132 mirror::CharArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002133 mirror::Constructor::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002134 mirror::DoubleArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002135 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002136 mirror::FloatArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002137 mirror::Method::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002138 mirror::IntArray::ResetArrayClass();
2139 mirror::LongArray::ResetArrayClass();
2140 mirror::ShortArray::ResetArrayClass();
Orion Hodson005ac512017-10-24 15:43:43 +01002141 mirror::CallSite::ResetClass();
Narayan Kamathafa48272016-08-03 12:46:58 +01002142 mirror::MethodType::ResetClass();
2143 mirror::MethodHandleImpl::ResetClass();
Orion Hodsonc069a302017-01-18 09:23:12 +00002144 mirror::MethodHandlesLookup::ResetClass();
Orion Hodson005ac512017-10-24 15:43:43 +01002145 mirror::VarHandle::ResetClass();
2146 mirror::FieldVarHandle::ResetClass();
2147 mirror::ArrayElementVarHandle::ResetClass();
2148 mirror::ByteArrayViewVarHandle::ResetClass();
2149 mirror::ByteBufferViewVarHandle::ResetClass();
Narayan Kamath000e1882016-10-24 17:14:25 +01002150 mirror::EmulatedStackFrame::ResetClass();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002151 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002152 for (const ClassLoaderData& data : class_loaders_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002153 DeleteClassLoader(self, data);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002154 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002155 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002156}
2157
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002158void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data) {
2159 Runtime* const runtime = Runtime::Current();
2160 JavaVMExt* const vm = runtime->GetJavaVM();
2161 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002162 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002163 if (runtime->GetJit() != nullptr) {
2164 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2165 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002166 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002167 code_cache->RemoveMethodsIn(self, *data.allocator);
2168 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002169 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002170 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002171 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002172 }
2173 delete data.allocator;
2174 delete data.class_table;
2175}
2176
Mathieu Chartiere401d142015-04-22 13:56:20 -07002177mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) {
Andreas Gampe542451c2016-07-26 09:02:02 -07002178 return down_cast<mirror::PointerArray*>(
2179 image_pointer_size_ == PointerSize::k64
2180 ? static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length))
2181 : static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002182}
2183
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002184mirror::DexCache* ClassLinker::AllocDexCache(ObjPtr<mirror::String>* out_location,
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002185 Thread* self,
2186 const DexFile& dex_file) {
2187 StackHandleScope<1> hs(self);
2188 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002189 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002190 GetClassRoot(kJavaLangDexCache)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002191 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002192 self->AssertPendingOOMException();
2193 return nullptr;
2194 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002195 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002196 if (location == nullptr) {
2197 self->AssertPendingOOMException();
2198 return nullptr;
2199 }
2200 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002201 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002202}
2203
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002204mirror::DexCache* ClassLinker::AllocAndInitializeDexCache(Thread* self,
2205 const DexFile& dex_file,
2206 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002207 ObjPtr<mirror::String> location = nullptr;
2208 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002209 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002210 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002211 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002212 mirror::DexCache::InitializeDexCache(self,
2213 dex_cache,
2214 location,
2215 &dex_file,
2216 linear_alloc,
2217 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002218 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002219 return dex_cache.Ptr();
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002220}
2221
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002222mirror::Class* ClassLinker::AllocClass(Thread* self,
2223 ObjPtr<mirror::Class> java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08002224 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002225 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002226 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002227 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002228 ObjPtr<mirror::Object> k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002229 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2230 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002231 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002232 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002233 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002234 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002235 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002236}
2237
Ian Rogers6fac4472014-02-25 17:01:10 -08002238mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002239 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002240}
2241
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002242mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002243 Thread* self,
2244 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002245 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2246 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002247}
2248
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002249mirror::Class* ClassLinker::EnsureResolved(Thread* self,
2250 const char* descriptor,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002251 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002252 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002253 if (kIsDebugBuild) {
2254 StackHandleScope<1> hs(self);
2255 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2256 Thread::PoisonObjectPointersIfDebug();
2257 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002258
2259 // For temporary classes we must wait for them to be retired.
2260 if (init_done_ && klass->IsTemp()) {
2261 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002262 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002263 ThrowEarlierClassFailure(klass);
2264 return nullptr;
2265 }
2266 StackHandleScope<1> hs(self);
2267 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2268 ObjectLock<mirror::Class> lock(self, h_class);
2269 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002270 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002271 lock.WaitIgnoringInterrupts();
2272 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002273 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002274 ThrowEarlierClassFailure(h_class.Get());
2275 return nullptr;
2276 }
2277 CHECK(h_class->IsRetired());
2278 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002279 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002280 }
2281
Brian Carlstromaded5f72011-10-07 17:15:04 -07002282 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002283 size_t index = 0;
2284 // Maximum number of yield iterations until we start sleeping.
2285 static const size_t kNumYieldIterations = 1000;
2286 // How long each sleep is in us.
2287 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002288 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002289 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002290 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002291 {
2292 ObjectTryLock<mirror::Class> lock(self, h_class);
2293 // Can not use a monitor wait here since it may block when returning and deadlock if another
2294 // thread has locked klass.
2295 if (lock.Acquired()) {
2296 // Check for circular dependencies between classes, the lock is required for SetStatus.
2297 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2298 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002299 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002300 return nullptr;
2301 }
2302 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002303 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002304 {
2305 // Handle wrapper deals with klass moving.
2306 ScopedThreadSuspension sts(self, kSuspended);
2307 if (index < kNumYieldIterations) {
2308 sched_yield();
2309 } else {
2310 usleep(kSleepDurationUS);
2311 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002312 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002313 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002314 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002315
Vladimir Marko72ab6842017-01-20 19:32:50 +00002316 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002317 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002318 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002319 }
2320 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002321 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002322 self->AssertNoPendingException();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002323 return klass.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002324}
2325
Ian Rogers68b56852014-08-29 20:19:11 -07002326typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2327
2328// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002329ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002330 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002331 for (const DexFile* dex_file : class_path) {
David Sehr9aa352e2016-09-15 18:13:52 -07002332 const DexFile::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002333 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002334 return ClassPathEntry(dex_file, dex_class_def);
2335 }
2336 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002337 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002338}
2339
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002340bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2341 Thread* self,
2342 const char* descriptor,
2343 size_t hash,
2344 Handle<mirror::ClassLoader> class_loader,
2345 ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002346 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002347 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002348 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002349 return true;
2350 }
2351
Calin Juravlecdd49122017-07-05 20:09:53 -07002352 if (IsPathOrDexClassLoader(soa, class_loader)) {
2353 // For regular path or dex class loader the search order is:
2354 // - parent
2355 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002356
Calin Juravlecdd49122017-07-05 20:09:53 -07002357 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2358 StackHandleScope<1> hs(self);
2359 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2360 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2361 return false; // One of the parents is not supported.
2362 }
2363 if (*result != nullptr) {
2364 return true; // Found the class up the chain.
2365 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002366
Calin Juravlecdd49122017-07-05 20:09:53 -07002367 // Search the current class loader classpath.
2368 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002369 return true;
2370 }
2371
Calin Juravlecdd49122017-07-05 20:09:53 -07002372 if (IsDelegateLastClassLoader(soa, class_loader)) {
2373 // For delegate last, the search order is:
2374 // - boot class path
2375 // - class loader dex files
2376 // - parent
2377 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2378 if (*result != nullptr) {
2379 return true; // The class is part of the boot class path.
2380 }
2381
2382 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2383 if (*result != nullptr) {
2384 return true; // Found the class in the current class loader
2385 }
2386
2387 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2388 StackHandleScope<1> hs(self);
2389 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2390 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2391 }
2392
2393 // Unsupported class loader.
2394 *result = nullptr;
2395 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002396}
2397
2398// Finds the class in the boot class loader.
2399// If the class is found the method returns the resolved class. Otherwise it returns null.
2400ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2401 const char* descriptor,
2402 size_t hash) {
2403 ObjPtr<mirror::Class> result = nullptr;
2404 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2405 if (pair.second != nullptr) {
2406 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2407 if (klass != nullptr) {
2408 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002409 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002410 result = DefineClass(self,
2411 descriptor,
2412 hash,
2413 ScopedNullHandle<mirror::ClassLoader>(),
2414 *pair.first,
2415 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002416 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002417 if (result == nullptr) {
2418 CHECK(self->IsExceptionPending()) << descriptor;
2419 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002420 }
2421 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002422 return result;
2423}
Andreas Gampef865ea92015-04-13 22:14:19 -07002424
Calin Juravle415dc3d2017-06-28 11:03:12 -07002425ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2426 ScopedObjectAccessAlreadyRunnable& soa,
2427 const char* descriptor,
2428 size_t hash,
2429 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002430 DCHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002431 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002432
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002433 ObjPtr<mirror::Class> ret;
2434 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
2435 const DexFile::ClassDef* dex_class_def =
2436 OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
2437 if (dex_class_def != nullptr) {
2438 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2439 descriptor,
2440 hash,
2441 class_loader,
2442 *cp_dex_file,
2443 *dex_class_def);
2444 if (klass == nullptr) {
2445 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2446 soa.Self()->ClearException();
2447 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002448 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002449 ret = klass;
2450 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002451 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002452 return true; // Continue with the next DexFile.
2453 };
2454
2455 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2456 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002457}
2458
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002459mirror::Class* ClassLinker::FindClass(Thread* self,
2460 const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002461 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002462 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002463 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002464 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002465 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002466 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002467 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2468 // for primitive classes that aren't backed by dex files.
2469 return FindPrimitiveClass(descriptor[0]);
2470 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002471 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002472 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002473 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002474 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002475 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002476 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002477 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002478 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002479 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002480 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002481 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002482 return DefineClass(self,
2483 descriptor,
2484 hash,
2485 ScopedNullHandle<mirror::ClassLoader>(),
2486 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002487 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002488 } else {
2489 // The boot class loader is searched ahead of the application class loader, failures are
2490 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2491 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002492 ObjPtr<mirror::Throwable> pre_allocated =
2493 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002494 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002495 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002496 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002497 }
2498 ObjPtr<mirror::Class> result_ptr;
2499 bool descriptor_equals;
2500 if (descriptor[0] == '[') {
2501 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2502 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2503 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2504 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002505 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002506 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002507 bool known_hierarchy =
2508 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2509 if (result_ptr != nullptr) {
2510 // The chain was understood and we found the class. We still need to add the class to
2511 // the class table to protect from racy programs that can try and redefine the path list
2512 // which would change the Class<?> returned for subsequent evaluation of const-class.
2513 DCHECK(known_hierarchy);
2514 DCHECK(result_ptr->DescriptorEquals(descriptor));
2515 descriptor_equals = true;
2516 } else {
2517 // Either the chain wasn't understood or the class wasn't found.
2518 //
2519 // If the chain was understood but we did not find the class, let the Java-side
2520 // rediscover all this and throw the exception with the right stack trace. Note that
2521 // the Java-side could still succeed for racy programs if another thread is actively
2522 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002523
Calin Juravleccd56952016-12-15 17:57:38 +00002524 if (!self->CanCallIntoJava()) {
2525 // Oops, we can't call into java so we can't run actual class-loader code.
2526 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002527 ObjPtr<mirror::Throwable> pre_allocated =
2528 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2529 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002530 return nullptr;
2531 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002532
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002533 // Inlined DescriptorToDot(descriptor) with extra validation.
2534 //
2535 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2536 // the DescriptorEquals() check below and give a confusing error message. For example,
2537 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2538 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2539 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2540 size_t descriptor_length = strlen(descriptor);
2541 if (UNLIKELY(descriptor[0] != 'L') ||
2542 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2543 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2544 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2545 return nullptr;
2546 }
2547 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2548 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2549
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002550 ScopedLocalRef<jobject> class_loader_object(
2551 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002552 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2553 {
2554 ScopedThreadStateChange tsc(self, kNative);
2555 ScopedLocalRef<jobject> class_name_object(
2556 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2557 if (class_name_object.get() == nullptr) {
2558 DCHECK(self->IsExceptionPending()); // OOME.
2559 return nullptr;
2560 }
2561 CHECK(class_loader_object.get() != nullptr);
2562 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2563 WellKnownClasses::java_lang_ClassLoader_loadClass,
2564 class_name_object.get()));
2565 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002566 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002567 // broken loader - throw NPE to be compatible with Dalvik
2568 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2569 class_name_string.c_str()).c_str());
2570 return nullptr;
2571 }
2572 result_ptr = soa.Decode<mirror::Class>(result.get());
2573 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002574 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002575 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002576 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002577
2578 if (self->IsExceptionPending()) {
2579 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2580 // However, to comply with the RI behavior, first check if another thread succeeded.
2581 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2582 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2583 self->ClearException();
2584 return EnsureResolved(self, descriptor, result_ptr);
2585 }
2586 return nullptr;
2587 }
2588
2589 // Try to insert the class to the class table, checking for mismatch.
2590 ObjPtr<mirror::Class> old;
2591 {
2592 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2593 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2594 old = class_table->Lookup(descriptor, hash);
2595 if (old == nullptr) {
2596 old = result_ptr; // For the comparison below, after releasing the lock.
2597 if (descriptor_equals) {
2598 class_table->InsertWithHash(result_ptr.Ptr(), hash);
2599 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get());
2600 } // else throw below, after releasing the lock.
2601 }
2602 }
2603 if (UNLIKELY(old != result_ptr)) {
2604 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2605 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2606 mirror::Class* loader_class = class_loader->GetClass();
2607 const char* loader_class_name =
2608 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2609 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2610 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2611 << DescriptorToDot(descriptor) << "\").";
2612 return EnsureResolved(self, descriptor, old);
2613 }
2614 if (UNLIKELY(!descriptor_equals)) {
2615 std::string result_storage;
2616 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2617 std::string loader_storage;
2618 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2619 ThrowNoClassDefFoundError(
2620 "Initiating class loader of type %s returned class %s instead of %s.",
2621 DescriptorToDot(loader_class_name).c_str(),
2622 DescriptorToDot(result_name).c_str(),
2623 DescriptorToDot(descriptor).c_str());
2624 return nullptr;
2625 }
2626 // success, return mirror::Class*
2627 return result_ptr.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002628}
2629
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002630mirror::Class* ClassLinker::DefineClass(Thread* self,
2631 const char* descriptor,
2632 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002633 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002634 const DexFile& dex_file,
2635 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002636 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002637 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002638
Brian Carlstromaded5f72011-10-07 17:15:04 -07002639 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002640 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002641 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002642 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002643 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002644 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002645 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002646 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002647 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002648 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2649 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002650 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002651 klass.Assign(GetClassRoot(kJavaLangDexCache));
Alex Lightd6251582016-10-31 11:12:30 -07002652 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
2653 klass.Assign(GetClassRoot(kDalvikSystemClassExt));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002654 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002655 }
2656
Andreas Gampefa4333d2017-02-14 11:10:34 -08002657 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002658 // Allocate a class with the status of not ready.
2659 // Interface object should get the right size here. Regular class will
2660 // figure out the right size later and be replaced with one of the right
2661 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002662 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002663 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08002664 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002665 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07002666 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002667 }
Alex Lightb0f11922017-01-23 14:25:17 -08002668 // Get the real dex file. This will return the input if there aren't any callbacks or they do
2669 // nothing.
2670 DexFile const* new_dex_file = nullptr;
2671 DexFile::ClassDef const* new_class_def = nullptr;
2672 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
2673 // will only be called once.
2674 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
2675 klass,
2676 class_loader,
2677 dex_file,
2678 dex_class_def,
2679 &new_dex_file,
2680 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08002681 // Check to see if an exception happened during runtime callbacks. Return if so.
2682 if (self->IsExceptionPending()) {
2683 return nullptr;
2684 }
Alex Lightb0f11922017-01-23 14:25:17 -08002685 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002686 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002687 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002688 return nullptr;
2689 }
2690 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08002691 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002692
Jeff Hao848f70a2014-01-15 13:49:50 -08002693 // Mark the string class by setting its access flag.
2694 if (UNLIKELY(!init_done_)) {
2695 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2696 klass->SetStringClass();
2697 }
2698 }
2699
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002700 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002701 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08002702 // Make sure we have a valid empty iftable even if there are errors.
2703 klass->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002704
Mathieu Chartier590fee92013-09-13 13:46:47 -07002705 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002706 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002707 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002708 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2709 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002710 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002711 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002712
Mathieu Chartierc7853442015-03-27 14:35:38 -07002713 // Load the fields and other things after we are inserted in the table. This is so that we don't
2714 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
2715 // other reason is that the field roots are only visited from the class table. So we need to be
2716 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08002717 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002718 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002719 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07002720 // An exception occured during load, set status to erroneous while holding klass' lock in case
2721 // notification is necessary.
2722 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002723 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002724 }
2725 return nullptr;
2726 }
2727
Brian Carlstromaded5f72011-10-07 17:15:04 -07002728 // Finish loading (if necessary) by finding parents
2729 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08002730 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002731 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002732 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002733 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002734 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002735 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002736 }
2737 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08002738
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07002739 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08002740 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08002741 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08002742
Brian Carlstromaded5f72011-10-07 17:15:04 -07002743 // Link the class (if necessary)
2744 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002745 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002746 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002747
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002748 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002749 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002750 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002751 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002752 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002753 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002754 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002755 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002756 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002757 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00002758 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002759
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002760 // Instrumentation may have updated entrypoints for all methods of all
2761 // classes. However it could not update methods of this class while we
2762 // were loading it. Now the class is resolved, we can update entrypoints
2763 // as required by instrumentation.
2764 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2765 // We must be in the kRunnable state to prevent instrumentation from
2766 // suspending all threads to update entrypoints while we are doing it
2767 // for this class.
2768 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002769 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002770 }
2771
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002772 /*
2773 * We send CLASS_PREPARE events to the debugger from here. The
2774 * definition of "preparation" is creating the static fields for a
2775 * class and initializing them to the standard default values, but not
2776 * executing any code (that comes later, during "initialization").
2777 *
2778 * We did the static preparation in LinkClass.
2779 *
2780 * The class has been prepared and resolved but possibly not yet verified
2781 * at this point.
2782 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08002783 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002784
Tamas Berghammer160e6df2016-01-05 14:29:02 +00002785 // Notify native debugger of the new class and its layout.
2786 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
2787
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002788 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002789}
2790
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002791uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2792 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002793 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002794 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002795 size_t num_8 = 0;
2796 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002797 size_t num_32 = 0;
2798 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002799 if (class_data != nullptr) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002800 // We allow duplicate definitions of the same field in a class_data_item
2801 // but ignore the repeated indexes here, b/21868015.
Andreas Gampee2abbc62017-09-15 11:59:26 -07002802 uint32_t last_field_idx = dex::kDexNoIndex;
Ian Rogers0571d352011-11-03 19:51:38 -07002803 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002804 uint32_t field_idx = it.GetMemberIndex();
2805 // Ordering enforced by DexFileVerifier.
Andreas Gampee2abbc62017-09-15 11:59:26 -07002806 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
Vladimir Marko879d27b2016-03-15 20:31:50 +00002807 if (UNLIKELY(field_idx == last_field_idx)) {
2808 continue;
2809 }
2810 last_field_idx = field_idx;
2811 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002812 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002813 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002814 switch (c) {
2815 case 'L':
2816 case '[':
2817 num_ref++;
2818 break;
2819 case 'J':
2820 case 'D':
2821 num_64++;
2822 break;
2823 case 'I':
2824 case 'F':
2825 num_32++;
2826 break;
2827 case 'S':
2828 case 'C':
2829 num_16++;
2830 break;
2831 case 'B':
2832 case 'Z':
2833 num_8++;
2834 break;
2835 default:
2836 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002837 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002838 }
2839 }
2840 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002841 return mirror::Class::ComputeClassSize(false,
2842 0,
2843 num_8,
2844 num_16,
2845 num_32,
2846 num_64,
2847 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002848 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002849}
2850
Alex Lightfc49fec2018-01-16 22:28:36 +00002851// Special case to get oat code without overwriting a trampoline.
2852const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07002853 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00002854 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002855 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002856 }
Alex Lightfc49fec2018-01-16 22:28:36 +00002857 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
2858 if (code != nullptr) {
2859 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08002860 }
Alex Lightfc49fec2018-01-16 22:28:36 +00002861 if (method->IsNative()) {
2862 // No code and native? Use generic trampoline.
2863 return GetQuickGenericJniStub();
2864 }
2865 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07002866}
2867
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002868bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
2869 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
2870 return false;
2871 }
2872
Elliott Hughes956af0f2014-12-11 14:34:28 -08002873 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002874 return true;
2875 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002876
2877 Runtime* runtime = Runtime::Current();
2878 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
2879 if (instr->InterpretOnly()) {
2880 return true;
2881 }
2882
2883 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
2884 // Doing this check avoids doing compiled/interpreter transitions.
2885 return true;
2886 }
2887
2888 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
2889 // Force the use of interpreter when it is required by the debugger.
2890 return true;
2891 }
2892
Alex Light8f34aba2017-10-09 13:46:32 -07002893 if (Thread::Current()->IsAsyncExceptionPending()) {
2894 // Force use of interpreter to handle async-exceptions
2895 return true;
2896 }
2897
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002898 if (runtime->IsJavaDebuggable()) {
2899 // For simplicity, we ignore precompiled code and go to the interpreter
2900 // assuming we don't already have jitted code.
2901 // We could look at the oat file where `quick_code` is being defined,
2902 // and check whether it's been compiled debuggable, but we decided to
2903 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08002904 jit::Jit* jit = Runtime::Current()->GetJit();
2905 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
2906 }
2907
David Srbeckyf4480162016-03-16 00:06:24 +00002908 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01002909 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00002910 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002911 // since we want to JIT it (at first use) with extra stackmaps for native
2912 // debugging. We keep however all AOT code from the boot image,
2913 // since the JIT-at-first-use is blocking and would result in non-negligible
2914 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00002915 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002916 }
2917
2918 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002919}
2920
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002921void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07002922 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07002923 if (klass->NumDirectMethods() == 0) {
2924 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002925 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002926 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002927 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002928 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002929 return; // OAT file unavailable.
2930 }
Ian Rogers19846512012-02-24 11:42:47 -08002931 }
Alex Light64ad14d2014-08-19 14:23:13 -07002932
Mathieu Chartierf8322842014-05-16 10:59:25 -07002933 const DexFile& dex_file = klass->GetDexFile();
2934 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002935 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002936 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002937 // There should always be class data if there were direct methods.
David Sehr709b0702016-10-13 09:12:37 -07002938 CHECK(class_data != nullptr) << klass->PrettyDescriptor();
Ian Rogers19846512012-02-24 11:42:47 -08002939 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002940 it.SkipAllFields();
Ian Rogers97b52f82014-08-14 11:34:07 -07002941 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002942 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
2943 klass->GetDexClassDefIndex(),
2944 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002945 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002946 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002947 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002948 if (!method->IsStatic()) {
2949 // Only update static methods.
2950 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002951 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002952 const void* quick_code = nullptr;
2953 if (has_oat_class) {
2954 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002955 quick_code = oat_method.GetQuickCode();
2956 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002957 // Check whether the method is native, in which case it's generic JNI.
2958 if (quick_code == nullptr && method->IsNative()) {
2959 quick_code = GetQuickGenericJniStub();
2960 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002961 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002962 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002963 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002964 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08002965 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002966 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002967}
2968
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002969// Does anything needed to make sure that the compiler will not generate a direct invoke to this
2970// method. Should only be called on non-invokable methods.
2971inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07002972 DCHECK(method != nullptr);
2973 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002974 method->SetEntryPointFromQuickCompiledCodePtrSize(
2975 class_linker->GetQuickToInterpreterBridgeTrampoline(),
2976 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07002977}
2978
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002979static void LinkCode(ClassLinker* class_linker,
2980 ArtMethod* method,
2981 const OatFile::OatClass* oat_class,
2982 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002983 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002984 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002985 // The following code only applies to a non-compiler runtime.
2986 return;
2987 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002988 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002989 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002990 if (oat_class != nullptr) {
2991 // Every kind of method should at least get an invoke stub from the oat_method.
2992 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002993 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002994 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002995 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002996
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00002997 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002998 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002999 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003000
Alex Light9139e002015-10-09 15:59:48 -07003001 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003002 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003003 return;
3004 }
Ian Rogers19846512012-02-24 11:42:47 -08003005
3006 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003007 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003008 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3009 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003010 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003011 } else if (quick_code == nullptr && method->IsNative()) {
3012 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003013 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003014 // Set entry point from compiled code if there's no code or in interpreter only mode.
3015 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003016 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003017
Ian Rogers62d6c772013-02-27 08:32:07 -08003018 if (method->IsNative()) {
3019 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003020 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003021
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003022 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003023 // We have a native method here without code. Then it should have either the generic JNI
3024 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3025 // TODO: this doesn't handle all the cases where trampolines may be installed.
3026 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003027 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3028 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003029 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003030 }
3031}
3032
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003033void ClassLinker::SetupClass(const DexFile& dex_file,
3034 const DexFile::ClassDef& dex_class_def,
3035 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003036 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003037 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003038 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003039 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003040 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003041 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003042
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003043 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07003044 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003045 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003046 klass->SetAccessFlags(access_flags);
3047 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003048 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003049 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003050
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003051 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003052 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003053}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003054
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003055void ClassLinker::LoadClass(Thread* self,
3056 const DexFile& dex_file,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003057 const DexFile::ClassDef& dex_class_def,
3058 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07003059 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003060 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07003061 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07003062 }
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003063 LoadClassMembers(self, dex_file, class_data, klass);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003064}
3065
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003066LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3067 LinearAlloc* allocator,
3068 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003069 if (length == 0) {
3070 return nullptr;
3071 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003072 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3073 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3074 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003075 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003076 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003077 CHECK(ret != nullptr);
3078 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3079 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003080}
3081
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003082LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3083 LinearAlloc* allocator,
3084 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003085 if (length == 0) {
3086 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003087 }
Vladimir Marko14632852015-08-17 12:07:23 +01003088 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3089 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003090 const size_t storage_size =
3091 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003092 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003093 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003094 CHECK(ret != nullptr);
3095 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003096 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003097 }
3098 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003099}
3100
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003101LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003102 if (class_loader == nullptr) {
3103 return Runtime::Current()->GetLinearAlloc();
3104 }
3105 LinearAlloc* allocator = class_loader->GetAllocator();
3106 DCHECK(allocator != nullptr);
3107 return allocator;
3108}
3109
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003110LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003111 if (class_loader == nullptr) {
3112 return Runtime::Current()->GetLinearAlloc();
3113 }
3114 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3115 LinearAlloc* allocator = class_loader->GetAllocator();
3116 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003117 RegisterClassLoader(class_loader);
3118 allocator = class_loader->GetAllocator();
3119 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003120 }
3121 return allocator;
3122}
3123
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003124void ClassLinker::LoadClassMembers(Thread* self,
3125 const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07003126 const uint8_t* class_data,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003127 Handle<mirror::Class> klass) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003128 {
3129 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3130 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003131 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003132 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003133 // We allow duplicate definitions of the same field in a class_data_item
3134 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003135 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003136 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003137 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3138 allocator,
3139 it.NumStaticFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003140 size_t num_sfields = 0;
3141 uint32_t last_field_idx = 0u;
3142 for (; it.HasNextStaticField(); it.Next()) {
3143 uint32_t field_idx = it.GetMemberIndex();
3144 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3145 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
3146 DCHECK_LT(num_sfields, it.NumStaticFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003147 LoadField(it, klass, &sfields->At(num_sfields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003148 ++num_sfields;
3149 last_field_idx = field_idx;
3150 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003151 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003152
Mathieu Chartiere401d142015-04-22 13:56:20 -07003153 // Load instance fields.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003154 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3155 allocator,
3156 it.NumInstanceFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003157 size_t num_ifields = 0u;
3158 last_field_idx = 0u;
3159 for (; it.HasNextInstanceField(); it.Next()) {
3160 uint32_t field_idx = it.GetMemberIndex();
3161 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3162 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
3163 DCHECK_LT(num_ifields, it.NumInstanceFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003164 LoadField(it, klass, &ifields->At(num_ifields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003165 ++num_ifields;
3166 last_field_idx = field_idx;
3167 }
3168 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003169
Vladimir Marko23682bf2015-06-24 14:28:03 +01003170 if (UNLIKELY(num_sfields != it.NumStaticFields()) ||
3171 UNLIKELY(num_ifields != it.NumInstanceFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003172 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Vladimir Marko23682bf2015-06-24 14:28:03 +01003173 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields()
3174 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003175 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3176 if (sfields != nullptr) {
3177 sfields->SetSize(num_sfields);
3178 }
3179 if (ifields != nullptr) {
3180 ifields->SetSize(num_ifields);
3181 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003182 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003183 // Set the field arrays.
3184 klass->SetSFieldsPtr(sfields);
3185 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003186 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003187 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
3188 // Load methods.
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003189 bool has_oat_class = false;
3190 const OatFile::OatClass oat_class =
3191 (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler())
3192 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3193 : OatFile::OatClass::Invalid();
3194 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
Alex Lighte64300b2015-12-15 15:02:47 -08003195 klass->SetMethodsPtr(
3196 AllocArtMethodArray(self, allocator, it.NumDirectMethods() + it.NumVirtualMethods()),
3197 it.NumDirectMethods(),
3198 it.NumVirtualMethods());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003199 size_t class_def_method_index = 0;
Andreas Gampee2abbc62017-09-15 11:59:26 -07003200 uint32_t last_dex_method_index = dex::kDexNoIndex;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003201 size_t last_class_def_method_index = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08003202 // TODO These should really use the iterators.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003203 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
3204 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003205 LoadMethod(dex_file, it, klass, method);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003206 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003207 uint32_t it_method_index = it.GetMemberIndex();
3208 if (last_dex_method_index == it_method_index) {
3209 // duplicate case
3210 method->SetMethodIndex(last_class_def_method_index);
3211 } else {
3212 method->SetMethodIndex(class_def_method_index);
3213 last_dex_method_index = it_method_index;
3214 last_class_def_method_index = class_def_method_index;
3215 }
3216 class_def_method_index++;
3217 }
3218 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
3219 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003220 LoadMethod(dex_file, it, klass, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003221 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003222 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003223 class_def_method_index++;
3224 }
3225 DCHECK(!it.HasNext());
Ian Rogers0571d352011-11-03 19:51:38 -07003226 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003227 // Ensure that the card is marked so that remembered sets pick up native roots.
3228 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003229 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003230}
3231
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003232void ClassLinker::LoadField(const ClassDataItemIterator& it,
3233 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003234 ArtField* dst) {
3235 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003236 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003237 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003238
3239 // Get access flags from the DexFile. If this is a boot class path class,
3240 // also set its runtime hidden API access flags.
3241 uint32_t access_flags = it.GetFieldAccessFlags();
3242 if (klass->IsBootStrapClassLoaded()) {
3243 access_flags =
3244 HiddenApiAccessFlags::EncodeForRuntime(access_flags, it.DecodeHiddenAccessFlags());
3245 }
3246 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003247}
3248
Mathieu Chartier268764d2016-09-13 12:09:38 -07003249void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003250 const ClassDataItemIterator& it,
3251 Handle<mirror::Class> klass,
3252 ArtMethod* dst) {
Ian Rogers19846512012-02-24 11:42:47 -08003253 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08003254 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003255 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003256
Mathieu Chartier268764d2016-09-13 12:09:38 -07003257 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003258 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003259 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07003260 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003261
David Brazdilf6a8a552018-01-15 18:10:50 +00003262 // Get access flags from the DexFile. If this is a boot class path class,
3263 // also set its runtime hidden API access flags.
Andreas Gampe51829322014-08-25 15:05:04 -07003264 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07003265
David Brazdilf6a8a552018-01-15 18:10:50 +00003266 if (klass->IsBootStrapClassLoaded()) {
3267 access_flags =
3268 HiddenApiAccessFlags::EncodeForRuntime(access_flags, it.DecodeHiddenAccessFlags());
3269 }
3270
Ian Rogersdfb325e2013-10-30 01:00:44 -07003271 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003272 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003273 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3274 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003275 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003276 klass->SetFinalizable();
3277 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003278 std::string temp;
3279 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003280 // The Enum class declares a "final" finalize() method to prevent subclasses from
3281 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3282 // subclasses, so we exclude it here.
3283 // We also want to avoid setting the flag on Object, where we know that finalize() is
3284 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003285 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3286 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003287 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003288 }
3289 }
3290 }
3291 } else if (method_name[0] == '<') {
3292 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003293 bool is_init = (strcmp("<init>", method_name) == 0);
3294 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003295 if (UNLIKELY(!is_init && !is_clinit)) {
3296 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3297 } else {
3298 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3299 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003300 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003301 access_flags |= kAccConstructor;
3302 }
3303 }
3304 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003305 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3306 // Check if the native method is annotated with @FastNative or @CriticalNative.
3307 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3308 dex_file, dst->GetClassDef(), dex_method_idx);
3309 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003310 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003311}
3312
Ian Rogers7b078e82014-09-10 14:44:24 -07003313void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003314 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003315 self,
3316 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003317 Runtime::Current()->GetLinearAlloc());
3318 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003319 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003320}
3321
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003322void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003323 ObjPtr<mirror::DexCache> dex_cache) {
3324 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003325 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003326 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
3327 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003328}
3329
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003330void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003331 ObjPtr<mirror::DexCache> dex_cache,
3332 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003333 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003334 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003335 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003336 // For app images, the dex cache location may be a suffix of the dex file location since the
3337 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003338 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3339 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003340 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3341 std::string dex_file_location = dex_file.GetLocation();
3342 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003343 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003344 // Take suffix.
3345 const std::string dex_file_suffix = dex_file_location.substr(
3346 dex_file_location.length() - dex_cache_length,
3347 dex_cache_length);
3348 // Example dex_cache location is SettingsProvider.apk and
3349 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003350 CHECK_EQ(dex_cache_location, dex_file_suffix);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003351 const OatFile* oat_file =
3352 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003353 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3354 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3355 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3356 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003357 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003358 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3359 DexCacheData data = *it;
3360 if (self->IsJWeakCleared(data.weak_root)) {
3361 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003362 it = dex_caches_.erase(it);
3363 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003364 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003365 it->dex_file->GetOatDexFile() != nullptr &&
3366 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003367 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003368 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003369 ++it;
3370 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003371 }
Vladimir Markob066d432018-01-03 13:14:37 +00003372 if (initialize_oat_file_data) {
3373 // Initialize the .data.bimg.rel.ro section.
3374 if (!oat_file->GetBootImageRelocations().empty()) {
3375 uint8_t* reloc_begin = const_cast<uint8_t*>(oat_file->DataBimgRelRoBegin());
3376 CheckedCall(mprotect,
3377 "un-protect boot image relocations",
3378 reloc_begin,
3379 oat_file->DataBimgRelRoSize(),
3380 PROT_READ | PROT_WRITE);
3381 uint32_t boot_image_begin = dchecked_integral_cast<uint32_t>(reinterpret_cast<uintptr_t>(
3382 Runtime::Current()->GetHeap()->GetBootImageSpaces().front()->Begin()));
3383 for (const uint32_t& relocation : oat_file->GetBootImageRelocations()) {
3384 const_cast<uint32_t&>(relocation) += boot_image_begin;
3385 }
3386 CheckedCall(mprotect,
3387 "protect boot image relocations",
3388 reloc_begin,
3389 oat_file->DataBimgRelRoSize(),
3390 PROT_READ);
3391 }
3392
3393 // Initialize the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003394 // TODO: Pre-initialize from boot/app image?
3395 ArtMethod* resolution_method = Runtime::Current()->GetResolutionMethod();
3396 for (ArtMethod*& entry : oat_file->GetBssMethods()) {
3397 entry = resolution_method;
3398 }
3399 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003400 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003401 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003402 DexCacheData data;
3403 data.weak_root = dex_cache_jweak;
3404 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003405 data.class_table = ClassTableForClassLoader(class_loader);
David Srbecky440a9b32018-02-15 17:47:29 +00003406 AddNativeDebugInfoForDex(self, ArrayRef<const uint8_t>(data.dex_file->Begin(),
3407 data.dex_file->Size()));
Vladimir Markocd556b02017-02-03 11:47:34 +00003408 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003409 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3410 // path dex caches without an image.
3411 data.class_table->InsertStrongRoot(dex_cache);
3412 if (class_loader != nullptr) {
3413 // Since we added a strong root to the class table, do the write barrier as required for
3414 // remembered sets and generational GCs.
3415 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3416 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003417 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003418}
3419
Vladimir Markocd556b02017-02-03 11:47:34 +00003420ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3421 return data.IsValid()
3422 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3423 : nullptr;
3424}
3425
3426ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3427 Thread* self,
3428 ObjPtr<mirror::DexCache> dex_cache,
3429 const DexCacheData& data,
3430 ObjPtr<mirror::ClassLoader> class_loader) {
3431 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3432 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3433 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3434 "Attempt to register dex file %s with multiple class loaders",
3435 data.dex_file->GetLocation().c_str());
3436 return nullptr;
3437 }
3438 return dex_cache;
3439}
3440
Alex Light07f06212017-06-01 14:01:43 -07003441void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3442 ObjPtr<mirror::ClassLoader> class_loader) {
3443 Thread* self = Thread::Current();
3444 StackHandleScope<2> hs(self);
3445 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3446 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3447 const DexFile* dex_file = dex_cache->GetDexFile();
3448 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3449 if (kIsDebugBuild) {
3450 DexCacheData old_data;
3451 {
3452 ReaderMutexLock mu(self, *Locks::dex_lock_);
3453 old_data = FindDexCacheDataLocked(*dex_file);
3454 }
3455 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3456 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3457 << "been registered on dex file " << dex_file->GetLocation();
3458 }
3459 ClassTable* table;
3460 {
3461 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3462 table = InsertClassTableForClassLoader(h_class_loader.Get());
3463 }
3464 WriterMutexLock mu(self, *Locks::dex_lock_);
3465 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3466 table->InsertStrongRoot(h_dex_cache.Get());
3467 if (h_class_loader.Get() != nullptr) {
3468 // Since we added a strong root to the class table, do the write barrier as required for
3469 // remembered sets and generational GCs.
3470 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3471 }
3472}
3473
Vladimir Markocd556b02017-02-03 11:47:34 +00003474ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3475 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003476 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003477 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003478 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003479 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003480 old_data = FindDexCacheDataLocked(dex_file);
3481 }
3482 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3483 if (old_dex_cache != nullptr) {
3484 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003485 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003486 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3487 DCHECK(linear_alloc != nullptr);
3488 ClassTable* table;
3489 {
3490 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3491 table = InsertClassTableForClassLoader(class_loader);
3492 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003493 // Don't alloc while holding the lock, since allocation may need to
3494 // suspend all threads and another thread may need the dex_lock_ to
3495 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003496 StackHandleScope<3> hs(self);
3497 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003498 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003499 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3500 self,
3501 dex_file)));
3502 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003503 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003504 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003505 old_data = FindDexCacheDataLocked(dex_file);
3506 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003507 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003508 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3509 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3510 // that the arrays are null.
3511 mirror::DexCache::InitializeDexCache(self,
3512 h_dex_cache.Get(),
3513 h_location.Get(),
3514 &dex_file,
3515 linear_alloc,
3516 image_pointer_size_);
3517 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003518 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003519 }
3520 if (old_dex_cache != nullptr) {
3521 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3522 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003523 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003524 self->ClearException();
3525 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3526 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3527 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003528 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003529 self->AssertPendingOOMException();
3530 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003531 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003532 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003533 if (h_class_loader.Get() != nullptr) {
3534 // Since we added a strong root to the class table, do the write barrier as required for
3535 // remembered sets and generational GCs.
3536 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3537 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003538 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003539}
3540
Vladimir Markocd556b02017-02-03 11:47:34 +00003541bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003542 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003543 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003544}
3545
Vladimir Markocd556b02017-02-03 11:47:34 +00003546ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3547 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003548 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3549 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003550 if (dex_cache != nullptr) {
3551 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003552 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003553 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003554 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003555 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003556 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003557 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003558 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003559 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3560 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003561 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003562}
3563
Vladimir Markocd556b02017-02-03 11:47:34 +00003564ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3565 const DexFile* dex_file = dex_cache->GetDexFile();
3566 DCHECK(dex_file != nullptr);
3567 ReaderMutexLock mu(self, *Locks::dex_lock_);
3568 // Search assuming unique-ness of dex file.
3569 for (const DexCacheData& data : dex_caches_) {
3570 // Avoid decoding (and read barriers) other unrelated dex caches.
3571 if (data.dex_file == dex_file) {
3572 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3573 if (registered_dex_cache != nullptr) {
3574 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3575 return data.class_table;
3576 }
3577 }
3578 }
3579 return nullptr;
3580}
3581
3582ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3583 // Search assuming unique-ness of dex file.
3584 for (const DexCacheData& data : dex_caches_) {
3585 // Avoid decoding (and read barriers) other unrelated dex caches.
3586 if (data.dex_file == &dex_file) {
3587 return data;
3588 }
3589 }
3590 return DexCacheData();
3591}
3592
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003593mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003594 ObjPtr<mirror::Class> klass =
3595 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003596 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003597 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003598 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003599 }
3600 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003601}
3602
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003603mirror::Class* ClassLinker::InitializePrimitiveClass(ObjPtr<mirror::Class> primitive_class,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003604 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003605 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003606 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003607 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003608 StackHandleScope<1> hs(self);
3609 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003610 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003611 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3612 h_class->SetPrimitiveType(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003613 h_class->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00003614 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003615 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003616 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3617 h_class.Get(),
3618 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003619 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003620 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003621}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003622
Brian Carlstrombe977852011-07-19 14:54:54 -07003623// Create an array class (i.e. the class object for the array, not the
3624// array itself). "descriptor" looks like "[C" or "[[[[B" or
3625// "[Ljava/lang/String;".
3626//
3627// If "descriptor" refers to an array of primitives, look up the
3628// primitive type's internally-generated class object.
3629//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003630// "class_loader" is the class loader of the class that's referring to
3631// us. It's used to ensure that we're looking for the element type in
3632// the right context. It does NOT become the class loader for the
3633// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003634//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003635// Returns null with an exception raised on failure.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003636mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003637 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003638 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003639 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003640 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003641 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3642 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003643 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003644 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003645 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003646 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3647 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003648 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003649 DCHECK(self->IsExceptionPending());
3650 return nullptr;
3651 } else {
3652 self->ClearException();
3653 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003654 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003655 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3656 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3657 return nullptr;
3658 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003659 // See if the component type is already loaded. Array classes are
3660 // always associated with the class loader of their underlying
3661 // element type -- an array of Strings goes with the loader for
3662 // java/lang/String -- so we need to look for it there. (The
3663 // caller should have checked for the existence of the class
3664 // before calling here, but they did so with *their* class loader,
3665 // not the component type's loader.)
3666 //
3667 // If we find it, the caller adds "loader" to the class' initiating
3668 // loader list, which should prevent us from going through this again.
3669 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003670 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003671 // are the same, because our caller (FindClass) just did the
3672 // lookup. (Even if we get this wrong we still have correct behavior,
3673 // because we effectively do this lookup again when we add the new
3674 // class to the hash table --- necessary because of possible races with
3675 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003676 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003677 ObjPtr<mirror::Class> new_class =
3678 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003679 if (new_class != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003680 return new_class.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003681 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003682 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003683
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003684 // Fill out the fields in the Class.
3685 //
3686 // It is possible to execute some methods against arrays, because
3687 // all arrays are subclasses of java_lang_Object_, so we need to set
3688 // up a vtable. We can just point at the one in java_lang_Object_.
3689 //
3690 // Array classes are simple enough that we don't need to do a full
3691 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003692 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003693 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003694 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003695 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003696 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003697 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003698 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003699 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003700 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003701 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003702 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003703 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003704 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07003705 } else if (strcmp(descriptor, "[J") == 0) {
3706 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003707 }
3708 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003709 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003710 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003711 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003712 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003713 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003714 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003715 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003716 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003717 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003718 DCHECK(new_class->GetComponentType() != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003719 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003720 new_class->SetSuperClass(java_lang_Object);
3721 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003722 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003723 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07003724 if (component_type->IsPrimitive()) {
3725 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
3726 } else {
3727 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
3728 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00003729 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00003730 new_class->PopulateEmbeddedVTable(image_pointer_size_);
3731 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
3732 new_class->SetImt(object_imt, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003733 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003734 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003735 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003736
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003737 // All arrays have java/lang/Cloneable and java/io/Serializable as
3738 // interfaces. We need to set that up here, so that stuff like
3739 // "instanceof" works right.
3740 //
3741 // Note: The GC could run during the call to FindSystemClass,
3742 // so we need to make sure the class object is GC-valid while we're in
3743 // there. Do this by clearing the interface list so the GC will just
3744 // think that the entries are null.
3745
3746
3747 // Use the single, global copies of "interfaces" and "iftable"
3748 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003749 {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003750 ObjPtr<mirror::IfTable> array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003751 CHECK(array_iftable != nullptr);
3752 new_class->SetIfTable(array_iftable);
3753 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003754
Elliott Hughes00626c22013-06-14 15:04:14 -07003755 // Inherit access flags from the component type.
3756 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3757 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3758 access_flags &= kAccJavaFlagsMask;
3759 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003760 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003761 access_flags |= kAccAbstract | kAccFinal;
3762 access_flags &= ~kAccInterface;
3763
3764 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003765
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003766 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003767 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003768 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
3769 // duplicate events in case of races. Array classes don't really follow dedicated
3770 // load and prepare, anyways.
3771 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
3772 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
3773
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003774 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003775 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003776 }
3777 // Another thread must have loaded the class after we
3778 // started but before we finished. Abandon what we've
3779 // done.
3780 //
3781 // (Yes, this happens.)
3782
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003783 return existing.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003784}
3785
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003786mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003787 switch (type) {
3788 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003789 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003790 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003791 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003792 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003793 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003794 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003795 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003796 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003797 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003798 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003799 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003800 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003801 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003802 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003803 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003804 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003805 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003806 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003807 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003808 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003809 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003810 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003811 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003812}
3813
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003814mirror::Class* ClassLinker::InsertClass(const char* descriptor, ObjPtr<mirror::Class> klass, size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003815 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003816 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003817 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003818 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003819 source += " from ";
3820 source += dex_cache->GetLocation()->ToModifiedUtf8();
3821 }
3822 LOG(INFO) << "Loaded class " << descriptor << source;
3823 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003824 {
3825 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003826 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07003827 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003828 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003829 if (existing != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003830 return existing.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07003831 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003832 VerifyObject(klass);
3833 class_table->InsertWithHash(klass, hash);
3834 if (class_loader != nullptr) {
3835 // This is necessary because we need to have the card dirtied for remembered sets.
3836 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3837 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00003838 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07003839 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003840 }
3841 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003842 if (kIsDebugBuild) {
3843 // Test that copied methods correctly can find their holder.
3844 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
3845 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
3846 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08003847 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003848 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003849}
3850
Vladimir Marko1998cd02017-01-13 13:02:58 +00003851void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003852 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3853 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
3854 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
3855 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00003856 }
3857}
3858
Alex Lighte64300b2015-12-15 15:02:47 -08003859// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003860void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08003861 LengthPrefixedArray<ArtMethod>* new_methods) {
3862 klass->SetMethodsPtrUnchecked(new_methods,
3863 klass->NumDirectMethods(),
3864 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003865 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003866 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003867}
3868
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003869mirror::Class* ClassLinker::LookupClass(Thread* self,
Andreas Gampe2ff3b972017-06-05 18:14:53 -07003870 const char* descriptor,
3871 ObjPtr<mirror::ClassLoader> class_loader) {
3872 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
3873}
3874
3875mirror::Class* ClassLinker::LookupClass(Thread* self,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003876 const char* descriptor,
3877 size_t hash,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003878 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01003879 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3880 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3881 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003882 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01003883 if (result != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003884 return result.Ptr();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003885 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003886 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01003887 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003888}
3889
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003890class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
3891 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08003892 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003893
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003894 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003895 REQUIRES(Locks::classlinker_classes_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003896 REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003897 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07003898 if (class_table != nullptr) {
3899 class_table->FreezeSnapshot();
3900 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003901 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003902};
3903
3904void ClassLinker::MoveClassTableToPreZygote() {
3905 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07003906 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003907 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003908 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003909}
3910
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003911// Look up classes by hash and descriptor and put all matching ones in the result array.
3912class LookupClassesVisitor : public ClassLoaderVisitor {
3913 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003914 LookupClassesVisitor(const char* descriptor,
3915 size_t hash,
3916 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003917 : descriptor_(descriptor),
3918 hash_(hash),
3919 result_(result) {}
3920
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003921 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003922 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003923 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003924 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003925 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
3926 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003927 result_->push_back(klass);
3928 }
3929 }
3930
3931 private:
3932 const char* const descriptor_;
3933 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003934 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003935};
3936
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003937void ClassLinker::LookupClasses(const char* descriptor,
3938 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003939 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003940 Thread* const self = Thread::Current();
3941 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003942 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07003943 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003944 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003945 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003946 result.push_back(klass);
3947 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003948 LookupClassesVisitor visitor(descriptor, hash, &result);
3949 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003950}
3951
Alex Lightf1f10492015-10-07 16:08:36 -07003952bool ClassLinker::AttemptSupertypeVerification(Thread* self,
3953 Handle<mirror::Class> klass,
3954 Handle<mirror::Class> supertype) {
3955 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003956 DCHECK(klass != nullptr);
3957 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07003958
Alex Lightf1f10492015-10-07 16:08:36 -07003959 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
3960 VerifyClass(self, supertype);
3961 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00003962
3963 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
3964 // The supertype is either verified, or we soft failed at AOT time.
3965 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07003966 return true;
3967 }
3968 // If we got this far then we have a hard failure.
3969 std::string error_msg =
3970 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07003971 klass->PrettyDescriptor().c_str(),
3972 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07003973 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003974 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07003975 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003976 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003977 // Set during VerifyClass call (if at all).
3978 self->ClearException();
3979 }
3980 // Change into a verify error.
3981 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08003982 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003983 self->GetException()->SetCause(cause.Get());
3984 }
3985 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
3986 if (Runtime::Current()->IsAotCompiler()) {
3987 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3988 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07003989 // Need to grab the lock to change status.
3990 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003991 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07003992 return false;
3993}
3994
Andreas Gampecc1b5352016-12-01 16:58:38 -08003995// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
3996// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
3997// before.
3998static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
3999 REQUIRES_SHARED(Locks::mutator_lock_) {
4000 if (!klass->WasVerificationAttempted()) {
4001 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
4002 klass->SetVerificationAttempted();
4003 }
4004}
4005
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004006verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004007 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004008 {
4009 // TODO: assert that the monitor on the Class is held
4010 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004011
Andreas Gampe884f3b82016-03-30 19:52:58 -07004012 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004013 ClassStatus old_status = klass->GetStatus();
4014 while (old_status == ClassStatus::kVerifying ||
4015 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004016 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004017 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4018 // case we may see the same status again. b/62912904. This is why the check is
4019 // greater or equal.
4020 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004021 << "Class '" << klass->PrettyClass()
4022 << "' performed an illegal verification state transition from " << old_status
4023 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004024 old_status = klass->GetStatus();
4025 }
jeffhao98eacac2011-09-14 16:11:53 -07004026
Andreas Gampe884f3b82016-03-30 19:52:58 -07004027 // The class might already be erroneous, for example at compile time if we attempted to verify
4028 // this class as a parent to another.
4029 if (klass->IsErroneous()) {
4030 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004031 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004032 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004033
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004034 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004035 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004036 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004037 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004038 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004039
4040 // For AOT, don't attempt to re-verify if we have already found we should
4041 // verify at runtime.
4042 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004043 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004044 }
jeffhao98eacac2011-09-14 16:11:53 -07004045
Vladimir Marko2c64a832018-01-04 11:31:56 +00004046 if (klass->GetStatus() == ClassStatus::kResolved) {
4047 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004048 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004049 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004050 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004051 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004052 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004053 }
4054
4055 // Skip verification if disabled.
4056 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004057 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004058 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004059 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004060 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004061 }
4062
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004063 VLOG(class_linker) << "Beginning verification for class: "
4064 << klass->PrettyDescriptor()
4065 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4066
Ian Rogers9ffb0392012-09-10 11:56:50 -07004067 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004068 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004069 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4070 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004071 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004072 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004073 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004074 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004075
Alex Lightf1f10492015-10-07 16:08:36 -07004076 // Verify all default super-interfaces.
4077 //
4078 // (1) Don't bother if the superclass has already had a soft verification failure.
4079 //
4080 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4081 // recursive initialization by themselves. This is because when an interface is initialized
4082 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4083 // but choose not to for an optimization. If the interfaces is being verified due to a class
4084 // initialization (which would need all the default interfaces to be verified) the class code
4085 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004086 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004087 && !klass->IsInterface()) { // See (2)
4088 int32_t iftable_count = klass->GetIfTableCount();
4089 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4090 // Loop through all interfaces this class has defined. It doesn't matter the order.
4091 for (int32_t i = 0; i < iftable_count; i++) {
4092 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004093 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004094 // We only care if we have default interfaces and can skip if we are already verified...
4095 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4096 continue;
4097 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4098 // We had a hard failure while verifying this interface. Just return immediately.
4099 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004100 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004101 } else if (UNLIKELY(!iface->IsVerified())) {
4102 // We softly failed to verify the iface. Stop checking and clean up.
4103 // Put the iface into the supertype handle so we know what caused us to fail.
4104 supertype.Assign(iface.Get());
4105 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004106 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004107 }
4108 }
4109
Alex Lightf1f10492015-10-07 16:08:36 -07004110 // At this point if verification failed, then supertype is the "first" supertype that failed
4111 // verification (without a specific order). If verification succeeded, then supertype is either
4112 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004113 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004114 supertype.Get() == klass->GetSuperClass() ||
4115 !supertype->IsVerified());
4116
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004117 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004118 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004119 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004120 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004121
4122 VLOG(class_linker) << "Class preverified status for class "
4123 << klass->PrettyDescriptor()
4124 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4125 << ": "
4126 << preverified;
4127
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004128 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4129 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004130 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4131 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004132
Ian Rogers62d6c772013-02-27 08:32:07 -08004133 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004134 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004135 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004136 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004137 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004138
4139 // Verification is done, grab the lock again.
4140 ObjectLock<mirror::Class> lock(self, klass);
4141
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004142 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4143 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004144 VLOG(class_linker) << "Soft verification failure in class "
4145 << klass->PrettyDescriptor()
4146 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4147 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004148 }
Ian Rogers1f539342012-10-03 21:09:42 -07004149 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004150 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004151 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004152 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004153 // Even though there were no verifier failures we need to respect whether the super-class and
4154 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004155 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004156 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004157 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004158 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4159 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004160 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004161 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004162 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004163 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004164 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004165 // Soft failures at compile time should be retried at runtime. Soft
4166 // failures at runtime will be handled by slow paths in the generated
4167 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004168 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004169 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004170 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004171 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004172 // As this is a fake verified status, make sure the methods are _not_ marked
4173 // kAccSkipAccessChecks later.
4174 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004175 }
4176 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004177 } else {
David Sehr709b0702016-10-13 09:12:37 -07004178 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004179 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4180 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004181 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004182 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004183 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004184 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004185 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004186 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004187 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004188 // method.
4189 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004190 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004191 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004192
4193 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4194 // Never skip access checks if the verification soft fail is forced.
4195 // Mark the class as having a verification attempt to avoid re-running the verifier.
4196 klass->SetVerificationAttempted();
4197 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004198 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004199 }
Andreas Gampe48498592014-09-10 19:48:05 -07004200 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004201 // Done verifying. Notify the compiler about the verification status, in case the class
4202 // was verified implicitly (eg super class of a compiled class).
4203 if (Runtime::Current()->IsAotCompiler()) {
4204 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4205 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4206 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004207 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004208}
4209
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004210verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4211 Handle<mirror::Class> klass,
4212 verifier::HardFailLogMode log_level,
4213 std::string* error_msg) {
4214 Runtime* const runtime = Runtime::Current();
4215 return verifier::MethodVerifier::VerifyClass(self,
4216 klass.Get(),
4217 runtime->GetCompilerCallbacks(),
4218 runtime->IsAotCompiler(),
4219 log_level,
4220 error_msg);
4221}
4222
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004223bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004224 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004225 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004226 // If we're compiling, we can only verify the class using the oat file if
4227 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004228 // the compilation unit (app - dependencies). We will let the compiler callback
4229 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004230 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004231 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004232 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004233 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004234 return false;
4235 }
4236 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004237 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004238 return false;
4239 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004240 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004241
Richard Uhler07b3c232015-03-31 15:57:54 -07004242 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004243 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004244 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004245 return false;
4246 }
4247
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004248 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004249 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004250 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004251 return true;
4252 }
4253 // If we only verified a subset of the classes at compile time, we can end up with classes that
4254 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004255 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004256 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004257 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004258 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004259 // Compile time verification failed with a soft error. Compile time verification can fail
4260 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004261 // class ... {
4262 // Foo x;
4263 // .... () {
4264 // if (...) {
4265 // v1 gets assigned a type of resolved class Foo
4266 // } else {
4267 // v1 gets assigned a type of unresolved class Bar
4268 // }
4269 // iput x = v1
4270 // } }
4271 // when we merge v1 following the if-the-else it results in Conflict
4272 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4273 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4274 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4275 // at compile time).
4276 return false;
4277 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004278 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004279 // Compile time verification failed with a hard error. This is caused by invalid instructions
4280 // in the class. These errors are unrecoverable.
4281 return false;
4282 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004283 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004284 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4285 // not loading the class.
4286 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4287 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004288 return false;
4289 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004290 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004291 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004292 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004293 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004294 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004295}
4296
Alex Light5a559862016-01-29 12:24:48 -08004297void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004298 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004299 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004300 }
4301}
4302
Alex Light5a559862016-01-29 12:24:48 -08004303void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004304 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004305 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004306 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004307 return; // native or abstract method
4308 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004309 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004310 return; // nothing to process
4311 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004312 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004313 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004314 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4315 CatchHandlerIterator iterator(handlers_ptr);
4316 for (; iterator.HasNext(); iterator.Next()) {
4317 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4318 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004319 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004320 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004321 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004322 DCHECK(Thread::Current()->IsExceptionPending());
4323 Thread::Current()->ClearException();
4324 }
4325 }
4326 }
4327 handlers_ptr = iterator.EndDataPointer();
4328 }
4329}
4330
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004331mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4332 jstring name,
4333 jobjectArray interfaces,
4334 jobject loader,
4335 jobjectArray methods,
4336 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004337 Thread* self = soa.Self();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004338 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004339 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004340 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004341 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004342 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004343 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004344 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004345 DCHECK(temp_klass->GetClass() != nullptr);
4346 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004347 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4348 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004349 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4350 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4351 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4352 temp_klass->SetName(soa.Decode<mirror::String>(name));
4353 temp_klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004354 // Object has an empty iftable, copy it for that reason.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004355 temp_klass->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004356 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004357 std::string descriptor(GetDescriptorForProxy(temp_klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004358 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004359
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004360 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004361 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004362
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004363 // Insert the class before loading the fields as the field roots
4364 // (ArtField::declaring_class_) are only visited from the class
4365 // table. There can't be any suspend points between inserting the
4366 // class and setting the field arrays below.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004367 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004368 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004369
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004370 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004371 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004372 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004373 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004374
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004375 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4376 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004377 ArtField& interfaces_sfield = sfields->At(0);
4378 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004379 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004380 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004381
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004382 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004383 ArtField& throws_sfield = sfields->At(1);
4384 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004385 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004386 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004387
Ian Rogers466bb252011-10-14 03:29:56 -07004388 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004389 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004390
Alex Lighte64300b2015-12-15 15:02:47 -08004391 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004392 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004393 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
David Sehr709b0702016-10-13 09:12:37 -07004394 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004395 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004396
4397 // Create the methods array.
4398 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4399 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004400 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4401 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004402 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004403 self->AssertPendingOOMException();
4404 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004405 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004406 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004407
4408 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004409 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004410
4411 // Create virtual method using specified prototypes.
4412 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004413 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004414 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004415 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004416 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004417 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4418 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004419 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004420
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004421 // The super class is java.lang.reflect.Proxy
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004422 temp_klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004423 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004424 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004425 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004426
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004427 // At this point the class is loaded. Publish a ClassLoad event.
4428 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4429 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4430
4431 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004432 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004433 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004434 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004435 // Link the fields and virtual methods, creating vtable and iftables.
4436 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004437 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004438 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004439 if (!LinkClass(self, descriptor.c_str(), temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004440 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004441 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004442 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004443 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004444 CHECK(temp_klass->IsRetired());
4445 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004446
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004447 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004448 interfaces_sfield.SetObject<false>(
4449 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004450 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004451 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4452 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004453 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004454 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004455
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004456 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4457
Vladimir Marko305c38b2018-02-14 11:50:07 +00004458 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4459 // See also ClassLinker::EnsureInitialized().
4460 if (kBitstringSubtypeCheckEnabled) {
4461 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4462 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4463 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4464 }
4465
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004466 {
4467 // Lock on klass is released. Lock new class object.
4468 ObjectLock<mirror::Class> initialization_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004469 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004470 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004471
4472 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004473 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004474 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004475 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4476
Ian Rogersc2b44472011-12-14 21:17:17 -08004477 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004478 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4479 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004480 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004481 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004482
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004483 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004484 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004485 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004486 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004487 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004488
4489 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004490 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004491 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004492
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004493 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004494 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004495 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004496 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004497 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004498 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004499}
4500
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004501std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004502 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004503 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004504 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004505 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4506}
4507
Mathieu Chartiere401d142015-04-22 13:56:20 -07004508void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4509 // Create constructor for Proxy that must initialize the method.
Neil Fullerd12c3b02017-11-30 18:03:15 +00004510 CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004511
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004512 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4513 // on which front-end compiler was used to build the libcore DEX files.
Vladimir Markoba118822017-06-12 15:41:56 +01004514 ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->FindConstructor(
4515 "(Ljava/lang/reflect/InvocationHandler;)V", image_pointer_size_);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004516 DCHECK(proxy_constructor != nullptr)
4517 << "Could not find <init> method in java.lang.reflect.Proxy";
4518
Jeff Haodb8a6642014-08-14 17:18:52 -07004519 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4520 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004521 DCHECK(out != nullptr);
4522 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004523 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004524 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004525 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004526 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4527 kAccPublic |
4528 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004529 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004530
4531 // Set the original constructor method.
4532 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004533}
4534
Mathieu Chartiere401d142015-04-22 13:56:20 -07004535void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004536 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004537 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4538 CHECK_STREQ(np->GetName(), "<init>");
4539 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004540 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004541}
4542
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004543void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004544 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004545 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004546 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004547 DCHECK(out != nullptr);
4548 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004549
Alex Lighte9dd04f2016-03-16 16:09:45 -07004550 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004551 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004552 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4553 // preference to the invocation handler.
4554 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4555 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004556 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4557 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004558 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4559
4560 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4561 // method they copy might (if it's a default method).
4562 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004563
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004564 // Set the original interface method.
4565 out->SetDataPtrSize(prototype, image_pointer_size_);
4566
Ian Rogers466bb252011-10-14 03:29:56 -07004567 // At runtime the method looks like a reference and argument saving method, clone the code
4568 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004569 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004570}
Jesse Wilson95caa792011-10-12 18:14:17 -04004571
Mathieu Chartiere401d142015-04-22 13:56:20 -07004572void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004573 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004574 CHECK(!prototype->IsFinal());
4575 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004576 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004577
4578 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4579 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08004580 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01004581 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004582}
4583
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004584bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004585 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004586 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004587 return true;
4588 }
4589 if (!can_init_statics) {
4590 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004591 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004592 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004593 return false;
4594 }
4595 // Check if there are encoded static values needing initialization.
4596 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004597 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004598 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004599 if (dex_class_def->static_values_off_ != 0) {
4600 return false;
4601 }
4602 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004603 // If we are a class we need to initialize all interfaces with default methods when we are
4604 // initialized. Check all of them.
4605 if (!klass->IsInterface()) {
4606 size_t num_interfaces = klass->GetIfTableCount();
4607 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004608 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07004609 if (iface->HasDefaultMethods() &&
4610 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
4611 return false;
4612 }
4613 }
4614 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004615 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004616 if (klass->IsInterface() || !klass->HasSuperClass()) {
4617 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004618 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004619 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07004620 if (!can_init_parents && !super_class->IsInitialized()) {
4621 return false;
4622 }
4623 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004624}
4625
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004626bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
4627 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004628 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4629
4630 // Are we already initialized and therefore done?
4631 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4632 // an initialized class will never change its state.
4633 if (klass->IsInitialized()) {
4634 return true;
4635 }
4636
4637 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004638 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004639 return false;
4640 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004641
Ian Rogers7b078e82014-09-10 14:44:24 -07004642 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004643 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004644 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004645 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004646
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004647 // Re-check under the lock in case another thread initialized ahead of us.
4648 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004649 return true;
4650 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004651
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004652 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004653 if (klass->IsErroneous()) {
Andreas Gampecb086952015-11-02 16:20:00 -08004654 ThrowEarlierClassFailure(klass.Get(), true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07004655 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004656 return false;
4657 }
4658
Vladimir Marko72ab6842017-01-20 19:32:50 +00004659 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
4660 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004661
4662 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004663 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004664 if (!klass->IsVerified()) {
4665 // We failed to verify, expect either the klass to be erroneous or verification failed at
4666 // compile time.
4667 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07004668 // The class is erroneous. This may be a verifier error, or another thread attempted
4669 // verification and/or initialization and failed. We can distinguish those cases by
4670 // whether an exception is already pending.
4671 if (self->IsExceptionPending()) {
4672 // Check that it's a VerifyError.
4673 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07004674 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07004675 } else {
4676 // Check that another thread attempted initialization.
4677 DCHECK_NE(0, klass->GetClinitThreadId());
4678 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
4679 // Need to rethrow the previous failure now.
4680 ThrowEarlierClassFailure(klass.Get(), true);
4681 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07004682 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004683 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004684 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004685 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004686 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004687 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004688 } else {
4689 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004690 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07004691
4692 // A separate thread could have moved us all the way to initialized. A "simple" example
4693 // involves a subclass of the current class being initialized at the same time (which
4694 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00004695 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07004696 if (klass->IsInitialized()) {
4697 return true;
4698 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004699 }
4700
Vladimir Marko2c64a832018-01-04 11:31:56 +00004701 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07004702 // initializing higher up the stack or another thread has beat us
4703 // to initializing and we need to wait. Either way, this
4704 // invocation of InitializeClass will not be responsible for
4705 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004706 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004707 // Could have got an exception during verification.
4708 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004709 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004710 return false;
4711 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004712 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004713 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004714 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004715 return true;
4716 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004717 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004718 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004719 }
4720
Jeff Haoe2e40342017-07-19 10:45:18 -07004721 // Try to get the oat class's status for this class if the oat file is present. The compiler
4722 // tries to validate superclass descriptors, and writes the result into the oat file.
4723 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
4724 // is different at runtime than it was at compile time, the oat file is rejected. So if the
4725 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07004726 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07004727 const Runtime* runtime = Runtime::Current();
4728 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
4729 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
4730 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004731 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07004732 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004733 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004734 return false;
4735 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004736 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004737
Vladimir Marko2c64a832018-01-04 11:31:56 +00004738 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07004739 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004740
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004741 // From here out other threads may observe that we're initializing and so changes of state
4742 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004743 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004744 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004745
4746 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004747 }
4748
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004749 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004750 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004751 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004752 if (!super_class->IsInitialized()) {
4753 CHECK(!super_class->IsInterface());
4754 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004755 StackHandleScope<1> hs(self);
4756 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004757 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004758 if (!super_initialized) {
4759 // The super class was verified ahead of entering initializing, we should only be here if
4760 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07004761 // For the case of aot compiler, the super class might also be initializing but we don't
4762 // want to process circular dependencies in pre-compile.
4763 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004764 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07004765 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004766 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004767 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004768 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004769 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004770 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004771 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004772 return false;
4773 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004774 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004775 }
4776
Alex Lighteb7c1442015-08-31 13:17:42 -07004777 if (!klass->IsInterface()) {
4778 // Initialize interfaces with default methods for the JLS.
4779 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004780 // Only setup the (expensive) handle scope if we actually need to.
4781 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07004782 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07004783 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
4784 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004785 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004786 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004787 CHECK(handle_scope_iface->IsInterface());
4788 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
4789 // We have already done this for this interface. Skip it.
4790 continue;
4791 }
4792 // We cannot just call initialize class directly because we need to ensure that ALL
4793 // interfaces with default methods are initialized. Non-default interface initialization
4794 // will not affect other non-default super-interfaces.
4795 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
4796 handle_scope_iface,
4797 can_init_statics,
4798 can_init_parents);
4799 if (!iface_initialized) {
4800 ObjectLock<mirror::Class> lock(self, klass);
4801 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004802 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07004803 return false;
4804 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004805 }
4806 }
4807 }
4808
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004809 const size_t num_static_fields = klass->NumStaticFields();
4810 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004811 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004812 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004813 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004814 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004815 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004816
4817 // Eagerly fill in static fields so that the we don't have to do as many expensive
4818 // Class::FindStaticField in ResolveField.
4819 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004820 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004821 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004822 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004823 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004824 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004825 } else {
4826 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004827 }
4828 }
4829
Vladimir Markoe11dd502017-12-08 14:09:45 +00004830 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
4831 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07004832 this,
4833 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00004834 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers13735952014-10-08 12:43:28 -07004835 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004836 ClassDataItemIterator field_it(dex_file, class_data);
4837 if (value_it.HasNext()) {
4838 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004839 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004840 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004841 ArtField* field = ResolveField(
Vladimir Markoe11dd502017-12-08 14:09:45 +00004842 field_it.GetMemberIndex(), dex_cache, class_loader, /* is_static */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004843 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004844 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004845 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004846 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004847 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07004848 if (self->IsExceptionPending()) {
4849 break;
4850 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004851 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004852 }
4853 }
4854 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004855
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004856
Mathieu Chartierda595be2016-08-10 13:57:39 -07004857 if (!self->IsExceptionPending()) {
4858 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4859 if (clinit != nullptr) {
4860 CHECK(can_init_statics);
4861 JValue result;
4862 clinit->Invoke(self, nullptr, 0, &result, "V");
4863 }
4864 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004865 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004866 uint64_t t1 = NanoTime();
4867
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004868 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004869 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004870 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004871
4872 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004873 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004874 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004875 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004876 } else if (Runtime::Current()->IsTransactionAborted()) {
4877 // The exception thrown when the transaction aborted has been caught and cleared
4878 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07004879 VLOG(compiler) << "Return from class initializer of "
4880 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01004881 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02004882 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004883 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004884 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004885 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004886 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4887 RuntimeStats* thread_stats = self->GetStats();
4888 ++global_stats->class_init_count;
4889 ++thread_stats->class_init_count;
4890 global_stats->class_init_time_ns += (t1 - t0);
4891 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004892 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004893 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004894 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004895 std::string temp;
4896 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004897 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004898 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004899 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004900 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004901 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004902 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004903 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004904}
4905
Alex Lighteb7c1442015-08-31 13:17:42 -07004906// We recursively run down the tree of interfaces. We need to do this in the order they are declared
4907// and perform the initialization only on those interfaces that contain default methods.
4908bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
4909 Handle<mirror::Class> iface,
4910 bool can_init_statics,
4911 bool can_init_parents) {
4912 CHECK(iface->IsInterface());
4913 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004914 // Only create the (expensive) handle scope if we need it.
4915 if (UNLIKELY(num_direct_ifaces > 0)) {
4916 StackHandleScope<1> hs(self);
4917 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
4918 // First we initialize all of iface's super-interfaces recursively.
4919 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004920 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004921 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004922 if (!super_iface->HasBeenRecursivelyInitialized()) {
4923 // Recursive step
4924 handle_super_iface.Assign(super_iface);
4925 if (!InitializeDefaultInterfaceRecursive(self,
4926 handle_super_iface,
4927 can_init_statics,
4928 can_init_parents)) {
4929 return false;
4930 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004931 }
4932 }
4933 }
4934
4935 bool result = true;
4936 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
4937 // initialize if we don't have default methods.
4938 if (iface->HasDefaultMethods()) {
4939 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
4940 }
4941
4942 // Mark that this interface has undergone recursive default interface initialization so we know we
4943 // can skip it on any later class initializations. We do this even if we are not a default
4944 // interface since we can still avoid the traversal. This is purely a performance optimization.
4945 if (result) {
4946 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08004947 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
4948 // interface. It is bad (Java) style, but not impossible. Marking the recursive
4949 // initialization is a performance optimization (to avoid another idempotent visit
4950 // for other implementing classes/interfaces), and can be revisited later.
4951 ObjectTryLock<mirror::Class> lock(self, iface);
4952 if (lock.Acquired()) {
4953 iface->SetRecursivelyInitialized();
4954 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004955 }
4956 return result;
4957}
4958
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004959bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
4960 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004961 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004962 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004963 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004964 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004965 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004966 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004967
4968 // When we wake up, repeat the test for init-in-progress. If
4969 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004970 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004971 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004972 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004973 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004974 return false;
4975 }
4976 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004977 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004978 continue;
4979 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004980 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004981 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004982 // Compile time initialization failed.
4983 return false;
4984 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004985 if (klass->IsErroneous()) {
4986 // The caller wants an exception, but it was thrown in a
4987 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004988 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07004989 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004990 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004991 return false;
4992 }
4993 if (klass->IsInitialized()) {
4994 return true;
4995 }
David Sehr709b0702016-10-13 09:12:37 -07004996 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004997 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004998 }
Ian Rogers07140832014-09-30 15:43:59 -07004999 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005000}
5001
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005002static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5003 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005004 ArtMethod* method,
5005 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005006 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005007 DCHECK(Thread::Current()->IsExceptionPending());
5008 DCHECK(!m->IsProxyMethod());
5009 const DexFile* dex_file = m->GetDexFile();
5010 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5011 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005012 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005013 std::string return_type = dex_file->PrettyType(return_type_idx);
5014 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005015 ThrowWrappedLinkageError(klass.Get(),
5016 "While checking class %s method %s signature against %s %s: "
5017 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005018 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5019 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005020 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005021 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005022 return_type.c_str(), class_loader.c_str());
5023}
5024
5025static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5026 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005027 ArtMethod* method,
5028 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005029 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005030 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005031 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005032 DCHECK(Thread::Current()->IsExceptionPending());
5033 DCHECK(!m->IsProxyMethod());
5034 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005035 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5036 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005037 ThrowWrappedLinkageError(klass.Get(),
5038 "While checking class %s method %s signature against %s %s: "
5039 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005040 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5041 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005042 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005043 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005044 index, arg_type.c_str(), class_loader.c_str());
5045}
5046
5047static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5048 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005049 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005050 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005051 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005052 ThrowLinkageError(klass.Get(),
5053 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005054 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5055 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005056 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005057 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005058 error_msg.c_str());
5059}
5060
Ian Rogersb5fb2072014-12-02 17:22:02 -08005061static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005062 Handle<mirror::Class> klass,
5063 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005064 ArtMethod* method1,
5065 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005066 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005067 {
5068 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005069 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005070 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005071 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005072 return false;
5073 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005074 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005075 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005076 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005077 return false;
5078 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005079 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005080 ThrowSignatureMismatch(klass, super_klass, method1,
5081 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005082 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005083 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005084 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005085 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005086 return false;
5087 }
5088 }
5089 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
5090 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
5091 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005092 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005093 ThrowSignatureMismatch(klass, super_klass, method1,
5094 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005095 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005096 return false;
5097 }
5098 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005099 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005100 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005101 ThrowSignatureMismatch(klass, super_klass, method1,
5102 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005103 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005104 return false;
5105 }
5106 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005107 }
5108 uint32_t num_types = types1->Size();
5109 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005110 ThrowSignatureMismatch(klass, super_klass, method1,
5111 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005112 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005113 return false;
5114 }
5115 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005116 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005117 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005118 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005119 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005120 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005121 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005122 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005123 return false;
5124 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005125 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005126 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005127 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005128 if (UNLIKELY(other_param_type == nullptr)) {
5129 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005130 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005131 return false;
5132 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005133 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005134 ThrowSignatureMismatch(klass, super_klass, method1,
5135 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5136 i,
David Sehr709b0702016-10-13 09:12:37 -07005137 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005138 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005139 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005140 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005141 return false;
5142 }
5143 }
5144 return true;
5145}
5146
5147
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005148bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005149 if (klass->IsInterface()) {
5150 return true;
5151 }
Ian Rogers151f2212014-05-06 11:27:27 -07005152 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005153 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005154 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005155 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005156 if (klass->HasSuperClass() &&
5157 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005158 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005159 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005160 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5161 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5162 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005163 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5164 klass,
5165 super_klass,
5166 m,
5167 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005168 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005169 return false;
5170 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005171 }
5172 }
5173 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005174 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005175 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5176 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5177 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005178 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005179 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5180 j, image_pointer_size_);
5181 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5182 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005183 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5184 klass,
5185 super_klass,
5186 m,
5187 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005188 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005189 return false;
5190 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005191 }
5192 }
5193 }
5194 }
5195 return true;
5196}
5197
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005198bool ClassLinker::EnsureInitialized(Thread* self,
5199 Handle<mirror::Class> c,
5200 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005201 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005202 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005203
Mathieu Chartier524507a2014-08-27 15:28:28 -07005204 if (c->IsInitialized()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08005205 EnsureSkipAccessChecksMethods(c, image_pointer_size_);
Mathieu Chartier8502f722016-06-08 15:09:08 -07005206 self->AssertNoPendingException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005207 return true;
5208 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005209 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5210 //
5211 // Ensure the bitstring is initialized before any of the class initialization
5212 // logic occurs. Once a class initializer starts running, objects can
5213 // escape into the heap and use the subtype checking code.
5214 //
5215 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5216 // can be used as a source for the IsSubClass check, and that all ancestors
5217 // of the class are Assigned (can be used as a target for IsSubClass check)
5218 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005219 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005220 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005221 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005222 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5223 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005224 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005225 if (!success) {
5226 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005227 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005228 }
5229 } else {
5230 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005231 }
5232 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005233}
5234
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005235void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5236 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005237 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005238 for (ArtField& field : new_class->GetIFields()) {
5239 if (field.GetDeclaringClass() == temp_class) {
5240 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005241 }
5242 }
5243
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005244 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005245 for (ArtField& field : new_class->GetSFields()) {
5246 if (field.GetDeclaringClass() == temp_class) {
5247 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005248 }
5249 }
5250
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005251 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005252 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005253 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005254 if (method.GetDeclaringClass() == temp_class) {
5255 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005256 }
5257 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005258
5259 // Make sure the remembered set and mod-union tables know that we updated some of the native
5260 // roots.
5261 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005262}
5263
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005264void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005265 CHECK(class_loader->GetAllocator() == nullptr);
5266 CHECK(class_loader->GetClassTable() == nullptr);
5267 Thread* const self = Thread::Current();
5268 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005269 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005270 // Create and set the class table.
5271 data.class_table = new ClassTable;
5272 class_loader->SetClassTable(data.class_table);
5273 // Create and set the linear allocator.
5274 data.allocator = Runtime::Current()->CreateLinearAlloc();
5275 class_loader->SetAllocator(data.allocator);
5276 // Add to the list so that we know to free the data later.
5277 class_loaders_.push_back(data);
5278}
5279
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005280ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005281 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005282 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005283 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005284 ClassTable* class_table = class_loader->GetClassTable();
5285 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005286 RegisterClassLoader(class_loader);
5287 class_table = class_loader->GetClassTable();
5288 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005289 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005290 return class_table;
5291}
5292
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005293ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005294 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005295}
5296
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005297static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005298 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005299 while (klass->HasSuperClass()) {
5300 klass = klass->GetSuperClass();
5301 if (klass->ShouldHaveImt()) {
5302 return klass->GetImt(pointer_size);
5303 }
5304 }
5305 return nullptr;
5306}
5307
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005308bool ClassLinker::LinkClass(Thread* self,
5309 const char* descriptor,
5310 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005311 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005312 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005313 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005314
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005315 if (!LinkSuperClass(klass)) {
5316 return false;
5317 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005318 ArtMethod* imt_data[ImTable::kSize];
5319 // If there are any new conflicts compared to super class.
5320 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005321 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005322 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005323 return false;
5324 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005325 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005326 return false;
5327 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005328 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005329 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005330 return false;
5331 }
5332 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005333 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005334
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005335 ImTable* imt = nullptr;
5336 if (klass->ShouldHaveImt()) {
5337 // If there are any new conflicts compared to the super class we can not make a copy. There
5338 // can be cases where both will have a conflict method at the same slot without having the same
5339 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5340 // will possibly create a table that is incorrect for either of the classes.
5341 // Same IMT with new_conflict does not happen very often.
5342 if (!new_conflict) {
5343 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5344 if (super_imt != nullptr) {
5345 bool imt_equals = true;
5346 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5347 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5348 }
5349 if (imt_equals) {
5350 imt = super_imt;
5351 }
5352 }
5353 }
5354 if (imt == nullptr) {
5355 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5356 imt = reinterpret_cast<ImTable*>(
5357 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5358 if (imt == nullptr) {
5359 return false;
5360 }
5361 imt->Populate(imt_data, image_pointer_size_);
5362 }
5363 }
5364
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005365 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5366 // We don't need to retire this class as it has no embedded tables or it was created the
5367 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005368 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005369
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005370 if (klass->ShouldHaveEmbeddedVTable()) {
5371 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005372 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005373 if (klass->ShouldHaveImt()) {
5374 klass->SetImt(imt, image_pointer_size_);
5375 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005376
5377 // Update CHA info based on whether we override methods.
5378 // Have to do this before setting the class as resolved which allows
5379 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005380 if (cha_ != nullptr) {
5381 cha_->UpdateAfterLoadingOf(klass);
5382 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005383
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005384 // This will notify waiters on klass that saw the not yet resolved
5385 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005386 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005387 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005388 } else {
5389 CHECK(!klass->IsResolved());
5390 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005391 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005392 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005393 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5394 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5395 // may not see any references to the target space and clean the card for a class if another
5396 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005397 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005398 klass->SetSFieldsPtrUnchecked(nullptr);
5399 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005400 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005401 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005402 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005403 return false;
5404 }
5405
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005406 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5407 ObjectLock<mirror::Class> lock(self, h_new_class);
5408 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005409
5410 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005411 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005412 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005413 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005414 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005415 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005416 if (class_loader != nullptr) {
5417 // We updated the class in the class table, perform the write barrier so that the GC knows
5418 // about the change.
5419 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
5420 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005421 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005422 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005423 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5424 }
5425 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005426
Mingyao Yang063fc772016-08-02 11:02:54 -07005427 // Update CHA info based on whether we override methods.
5428 // Have to do this before setting the class as resolved which allows
5429 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005430 if (cha_ != nullptr) {
5431 cha_->UpdateAfterLoadingOf(h_new_class);
5432 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005433
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005434 // This will notify waiters on temp class that saw the not yet resolved class in the
5435 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005436 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005437
Vladimir Marko2c64a832018-01-04 11:31:56 +00005438 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005439 // This will notify waiters on new_class that saw the not yet resolved
5440 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005441 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005442 // Return the new class.
5443 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005444 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005445 return true;
5446}
5447
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005448bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005449 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005450 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005451 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5452 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005453 // Check that a class does not inherit from itself directly.
5454 //
5455 // TODO: This is a cheap check to detect the straightforward case
5456 // of a class extending itself (b/28685551), but we should do a
5457 // proper cycle detection on loaded classes, to detect all cases
5458 // of class circularity errors (b/28830038).
5459 if (super_class_idx == class_def.class_idx_) {
5460 ThrowClassCircularityError(klass.Get(),
5461 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005462 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005463 return false;
5464 }
5465
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005466 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005467 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005468 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005469 return false;
5470 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005471 // Verify
5472 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005473 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005474 super_class->PrettyDescriptor().c_str(),
5475 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005476 return false;
5477 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005478 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005479 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005480 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005481 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005482 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005483 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005484 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005485 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005486 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005487 DCHECK(Thread::Current()->IsExceptionPending());
5488 return false;
5489 }
5490 // Verify
5491 if (!klass->CanAccess(interface)) {
5492 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005493 ThrowIllegalAccessError(klass.Get(),
5494 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005495 interface->PrettyDescriptor().c_str(),
5496 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005497 return false;
5498 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005499 }
5500 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005501 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005502 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005503 return true;
5504}
5505
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005506bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005507 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005508 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005509 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005510 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005511 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005512 return false;
5513 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005514 return true;
5515 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005516 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005517 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005518 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005519 return false;
5520 }
5521 // Verify
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005522 if (klass->IsInterface() && super != GetClassRoot(kJavaLangObject)) {
5523 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5524 return false;
5525 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005526 if (super->IsFinal()) {
5527 ThrowVerifyError(klass.Get(),
5528 "Superclass %s of %s is declared final",
5529 super->PrettyDescriptor().c_str(),
5530 klass->PrettyDescriptor().c_str());
5531 return false;
5532 }
5533 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005534 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005535 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005536 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005537 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005538 return false;
5539 }
5540 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005541 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005542 super->PrettyDescriptor().c_str(),
5543 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005544 return false;
5545 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005546
Brian Carlstromf3632832014-05-20 15:36:53 -07005547 // Inherit kAccClassIsFinalizable from the superclass in case this
5548 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005549 if (super->IsFinalizable()) {
5550 klass->SetFinalizable();
5551 }
5552
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005553 // Inherit class loader flag form super class.
5554 if (super->IsClassLoaderClass()) {
5555 klass->SetClassLoaderClass();
5556 }
5557
Elliott Hughes2da50362011-10-10 16:57:08 -07005558 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005559 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005560 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005561 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005562 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005563 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005564 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07005565 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005566 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005567 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005568 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005569 return false;
5570 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005571
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005572 if (kIsDebugBuild) {
5573 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005574 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005575 CHECK(super->IsResolved());
5576 super = super->GetSuperClass();
5577 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005578 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005579 return true;
5580}
5581
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005582// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005583bool ClassLinker::LinkMethods(Thread* self,
5584 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005585 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005586 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005587 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005588 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005589 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5590 // need to have default methods be in the virtuals array of each class but we don't set that up
5591 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07005592 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07005593 // Link virtual methods then interface methods.
5594 // We set up the interface lookup table first because we need it to determine if we need to update
5595 // any vtable entries with new default method implementations.
5596 return SetupInterfaceLookupTable(self, klass, interfaces)
5597 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005598 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005599}
5600
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005601// Comparator for name and signature of a method, used in finding overriding methods. Implementation
5602// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
5603// caches in the implementation below.
5604class MethodNameAndSignatureComparator FINAL : public ValueObject {
5605 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005606 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005607 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005608 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
5609 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07005610 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005611 }
5612
5613 const char* GetName() {
5614 if (name_ == nullptr) {
5615 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
5616 }
5617 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005618 }
5619
Mathieu Chartiere401d142015-04-22 13:56:20 -07005620 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005621 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07005622 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005623 const DexFile* other_dex_file = other->GetDexFile();
5624 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
5625 if (dex_file_ == other_dex_file) {
5626 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
5627 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005628 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005629 uint32_t other_name_len;
5630 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
5631 &other_name_len);
5632 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
5633 return false;
5634 }
5635 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
5636 }
5637
5638 private:
5639 // Dex file for the method to compare against.
5640 const DexFile* const dex_file_;
5641 // MethodId for the method to compare against.
5642 const DexFile::MethodId* const mid_;
5643 // Lazily computed name from the dex file's strings.
5644 const char* name_;
5645 // Lazily computed name length.
5646 uint32_t name_len_;
5647};
5648
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005649class LinkVirtualHashTable {
5650 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005651 LinkVirtualHashTable(Handle<mirror::Class> klass,
5652 size_t hash_size,
5653 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07005654 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005655 : klass_(klass),
5656 hash_size_(hash_size),
5657 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07005658 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005659 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
5660 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005661
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005662 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005663 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
5664 virtual_method_index, image_pointer_size_);
5665 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005666 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005667 uint32_t index = hash % hash_size_;
5668 // Linear probe until we have an empty slot.
5669 while (hash_table_[index] != invalid_index_) {
5670 if (++index == hash_size_) {
5671 index = 0;
5672 }
5673 }
5674 hash_table_[index] = virtual_method_index;
5675 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005676
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005677 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005678 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005679 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005680 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005681 size_t index = hash % hash_size_;
5682 while (true) {
5683 const uint32_t value = hash_table_[index];
5684 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
5685 // the block and can safely assume not found.
5686 if (value == invalid_index_) {
5687 break;
5688 }
5689 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005690 ArtMethod* virtual_method =
5691 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
5692 if (comparator->HasSameNameAndSignature(
5693 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005694 hash_table_[index] = removed_index_;
5695 return value;
5696 }
5697 }
5698 if (++index == hash_size_) {
5699 index = 0;
5700 }
5701 }
5702 return GetNotFoundIndex();
5703 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005704
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005705 static uint32_t GetNotFoundIndex() {
5706 return invalid_index_;
5707 }
5708
5709 private:
5710 static const uint32_t invalid_index_;
5711 static const uint32_t removed_index_;
5712
5713 Handle<mirror::Class> klass_;
5714 const size_t hash_size_;
5715 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07005716 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005717};
5718
5719const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
5720const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
5721
Stephen Hines1ddd9132017-02-08 01:51:18 -08005722bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07005723 Thread* self,
5724 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07005725 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005726 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07005727 if (klass->IsInterface()) {
5728 // No vtable.
5729 if (!IsUint<16>(num_virtual_methods)) {
5730 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
5731 return false;
5732 }
5733 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07005734 // Assign each method an IMT index and set the default flag.
5735 for (size_t i = 0; i < num_virtual_methods; ++i) {
5736 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5737 m->SetMethodIndex(i);
5738 if (!m->IsAbstract()) {
5739 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
5740 has_defaults = true;
5741 }
5742 }
5743 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
5744 // during initialization. This is a performance optimization. We could simply traverse the
5745 // virtual_methods_ array again during initialization.
5746 if (has_defaults) {
5747 klass->SetHasDefaultMethods();
5748 }
5749 return true;
5750 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005751 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
5752 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005753 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07005754 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07005755 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005756 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005757 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005758 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005759 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005760 return false;
5761 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005762 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005763 vtable->SetElementPtrSize(
5764 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005765 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005766 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5767 // might give us new default methods). If no new interfaces then we can skip the rest since
5768 // the class cannot override any of the super-class's methods. This is required for
5769 // correctness since without it we might not update overridden default method vtable entries
5770 // correctly.
5771 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005772 klass->SetVTable(vtable.Get());
5773 return true;
5774 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005775 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07005776 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005777 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07005778 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07005779 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5780 // might give us new default methods). See comment above.
5781 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005782 klass->SetVTable(super_vtable);
5783 return true;
5784 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005785 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
5786 super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005787 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005788 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005789 return false;
5790 }
Ian Rogersa436fde2013-08-27 23:34:06 -07005791 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005792 // How the algorithm works:
5793 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
5794 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
5795 // method which has not been matched to a vtable method, and j if the virtual method at the
5796 // index overrode the super virtual method at index j.
5797 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
5798 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
5799 // the need for the initial vtable which we later shrink back down).
5800 // 3. Add non overridden methods to the end of the vtable.
5801 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07005802 // + 1 so that even if we only have new default methods we will still be able to use this hash
5803 // table (i.e. it will never have 0 size).
5804 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005805 uint32_t* hash_table_ptr;
5806 std::unique_ptr<uint32_t[]> hash_heap_storage;
5807 if (hash_table_size <= kMaxStackHash) {
5808 hash_table_ptr = reinterpret_cast<uint32_t*>(
5809 alloca(hash_table_size * sizeof(*hash_table_ptr)));
5810 } else {
5811 hash_heap_storage.reset(new uint32_t[hash_table_size]);
5812 hash_table_ptr = hash_heap_storage.get();
5813 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005814 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005815 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005816 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005817 DCHECK(klass->GetVirtualMethodDuringLinking(
5818 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005819 hash_table.Add(i);
5820 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005821 // 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 -07005822 // the hash table.
5823 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005824 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005825 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005826 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
5827 super_method->GetAccessFlags())) {
5828 // Continue on to the next method since this one is package private and canot be overridden.
5829 // Before Android 4.1, the package-private method super_method might have been incorrectly
5830 // overridden.
5831 continue;
5832 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005833 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005834 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07005835 // We remove the method so that subsequent lookups will be faster by making the hash-map
5836 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005837 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5838 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005839 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
5840 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005841 if (super_method->IsFinal()) {
5842 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5843 virtual_method->PrettyMethod().c_str(),
5844 super_method->GetDeclaringClassDescriptor());
5845 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005846 }
Alex Lightc7a420c2016-10-18 14:33:18 -07005847 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
5848 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07005849 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005850 // We didn't directly override this method but we might through default methods...
5851 // Check for default method update.
5852 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07005853 switch (FindDefaultMethodImplementation(self,
5854 super_method,
5855 klass,
5856 /*out*/&default_method)) {
5857 case DefaultMethodSearchResult::kDefaultConflict: {
5858 // A conflict was found looking for default methods. Note this (assuming it wasn't
5859 // pre-existing) in the translations map.
5860 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
5861 // Don't generate another conflict method to reduce memory use as an optimization.
5862 default_translations->insert(
5863 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
5864 }
5865 break;
5866 }
5867 case DefaultMethodSearchResult::kAbstractFound: {
5868 // No conflict but method is abstract.
5869 // We note that this vtable entry must be made abstract.
5870 if (UNLIKELY(!super_method->IsAbstract())) {
5871 default_translations->insert(
5872 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
5873 }
5874 break;
5875 }
5876 case DefaultMethodSearchResult::kDefaultFound: {
5877 if (UNLIKELY(super_method->IsDefaultConflicting() ||
5878 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
5879 // Found a default method implementation that is new.
5880 // TODO Refactor this add default methods to virtuals here and not in
5881 // LinkInterfaceMethods maybe.
5882 // The problem is default methods might override previously present
5883 // default-method or miranda-method vtable entries from the superclass.
5884 // Unfortunately we need these to be entries in this class's virtuals. We do not
5885 // give these entries there until LinkInterfaceMethods so we pass this map around
5886 // to let it know which vtable entries need to be updated.
5887 // Make a note that vtable entry j must be updated, store what it needs to be updated
5888 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
5889 // then.
5890 default_translations->insert(
5891 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07005892 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
5893 << " overridden by default "
5894 << default_method->PrettyMethod()
5895 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07005896 }
5897 break;
5898 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005899 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005900 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005901 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005902 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07005903 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005904 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005905 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005906 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5907 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07005908 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005909 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005910 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005911 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005912 local_method->SetMethodIndex(actual_count);
5913 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005914 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005915 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005916 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005917 return false;
5918 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005919 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005920 CHECK_LE(actual_count, max_count);
5921 if (actual_count < max_count) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005922 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005923 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005924 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005925 return false;
5926 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005927 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005928 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005929 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005930 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005931 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005932 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5933 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005934 return false;
5935 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005936 auto* vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005937 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005938 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005939 return false;
5940 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005941 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005942 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5943 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005944 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005945 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005946 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005947 }
5948 return true;
5949}
5950
Alex Light9139e002015-10-09 15:59:48 -07005951// Determine if the given iface has any subinterface in the given list that declares the method
5952// specified by 'target'.
5953//
5954// Arguments
5955// - self: The thread we are running on
5956// - target: A comparator that will match any method that overrides the method we are checking for
5957// - iftable: The iftable we are searching for an overriding method on.
5958// - ifstart: The index of the interface we are checking to see if anything overrides
5959// - iface: The interface we are checking to see if anything overrides.
5960// - image_pointer_size:
5961// The image pointer size.
5962//
5963// Returns
5964// - True: There is some method that matches the target comparator defined in an interface that
5965// is a subtype of iface.
5966// - False: There is no method that matches the target comparator in any interface that is a subtype
5967// of iface.
5968static bool ContainsOverridingMethodOf(Thread* self,
5969 MethodNameAndSignatureComparator& target,
5970 Handle<mirror::IfTable> iftable,
5971 size_t ifstart,
5972 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07005973 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005974 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07005975 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005976 DCHECK(iface != nullptr);
5977 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07005978 DCHECK_GE(ifstart, 0u);
5979 DCHECK_LT(ifstart, iftable->Count());
5980 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
5981 DCHECK(iface->IsInterface());
5982
5983 size_t iftable_count = iftable->Count();
5984 StackHandleScope<1> hs(self);
5985 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
5986 for (size_t k = ifstart + 1; k < iftable_count; k++) {
5987 // Skip ifstart since our current interface obviously cannot override itself.
5988 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08005989 // Iterate through every method on this interface. The order does not matter.
5990 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07005991 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08005992 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07005993 // Check if the i'th interface is a subtype of this one.
5994 if (iface->IsAssignableFrom(current_iface.Get())) {
5995 return true;
5996 }
5997 break;
5998 }
5999 }
6000 }
6001 return false;
6002}
6003
Alex Lighteb7c1442015-08-31 13:17:42 -07006004// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006005// out_default_method and returns kDefaultFound on success. If no default method was found return
6006// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6007// default_method conflict) it will return kDefaultConflict.
6008ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6009 Thread* self,
6010 ArtMethod* target_method,
6011 Handle<mirror::Class> klass,
6012 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006013 DCHECK(self != nullptr);
6014 DCHECK(target_method != nullptr);
6015 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006016
6017 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006018
6019 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6020 // table. This lets us walk the table backwards when searching for default methods. The first one
6021 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6022 // track of it and then continue checking all other interfaces, since we need to throw an error if
6023 // we encounter conflicting default method implementations (one is not a subtype of the other).
6024 //
6025 // The order of unrelated interfaces does not matter and is not defined.
6026 size_t iftable_count = klass->GetIfTableCount();
6027 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006028 // No interfaces. We have already reset out to null so just return kAbstractFound.
6029 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006030 }
6031
Alex Light9139e002015-10-09 15:59:48 -07006032 StackHandleScope<3> hs(self);
6033 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006034 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006035 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006036 MethodNameAndSignatureComparator target_name_comparator(
6037 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6038 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006039 for (size_t k = iftable_count; k != 0; ) {
6040 --k;
6041
Alex Lighteb7c1442015-08-31 13:17:42 -07006042 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006043
6044 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006045 // Iterate through every declared method on this interface. The order does not matter.
6046 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6047 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006048 // Skip abstract methods and methods with different names.
6049 if (current_method->IsAbstract() ||
6050 !target_name_comparator.HasSameNameAndSignature(
6051 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6052 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006053 } else if (!current_method->IsPublic()) {
6054 // The verifier should have caught the non-public method for dex version 37. Just warn and
6055 // skip it since this is from before default-methods so we don't really need to care that it
6056 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006057 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6058 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006059 << "This will be a fatal error in subsequent versions of android. "
6060 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006061 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006062 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006063 // We have multiple default impls of the same method. This is a potential default conflict.
6064 // We need to check if this possibly conflicting method is either a superclass of the chosen
6065 // default implementation or is overridden by a non-default interface method. In either case
6066 // there is no conflict.
6067 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6068 !ContainsOverridingMethodOf(self,
6069 target_name_comparator,
6070 iftable,
6071 k,
6072 iface,
6073 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006074 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006075 << current_method->PrettyMethod() << " and "
6076 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6077 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006078 *out_default_method = nullptr;
6079 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006080 } else {
6081 break; // Continue checking at the next interface.
6082 }
6083 } else {
Alex Light9139e002015-10-09 15:59:48 -07006084 // chosen_iface == null
6085 if (!ContainsOverridingMethodOf(self,
6086 target_name_comparator,
6087 iftable,
6088 k,
6089 iface,
6090 image_pointer_size_)) {
6091 // Don't set this as the chosen interface if something else is overriding it (because that
6092 // other interface would be potentially chosen instead if it was default). If the other
6093 // interface was abstract then we wouldn't select this interface as chosen anyway since
6094 // the abstract method masks it.
6095 *out_default_method = current_method;
6096 chosen_iface.Assign(iface.Get());
6097 // We should now finish traversing the graph to find if we have default methods that
6098 // conflict.
6099 } else {
David Sehr709b0702016-10-13 09:12:37 -07006100 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6101 << "' was "
6102 << "skipped because it was overridden by an abstract method in a "
6103 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006104 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006105 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006106 break;
6107 }
6108 }
Alex Light9139e002015-10-09 15:59:48 -07006109 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006110 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6111 << "' selected "
6112 << "as the implementation for '" << target_method->PrettyMethod()
6113 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006114 return DefaultMethodSearchResult::kDefaultFound;
6115 } else {
6116 return DefaultMethodSearchResult::kAbstractFound;
6117 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006118}
6119
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006120ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006121 ArtMethod* conflict_method,
6122 ArtMethod* interface_method,
6123 ArtMethod* method,
6124 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006125 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006126 Runtime* const runtime = Runtime::Current();
6127 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6128 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6129
6130 // Create a new entry if the existing one is the shared conflict method.
6131 ArtMethod* new_conflict_method = new_entry
6132 ? runtime->CreateImtConflictMethod(linear_alloc)
6133 : conflict_method;
6134
6135 // Allocate a new table. Note that we will leak this table at the next conflict,
6136 // but that's a tradeoff compared to making the table fixed size.
6137 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006138 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6139 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006140 if (data == nullptr) {
6141 LOG(ERROR) << "Failed to allocate conflict table";
6142 return conflict_method;
6143 }
6144 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6145 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006146 method,
6147 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006148
6149 // Do a fence to ensure threads see the data in the table before it is assigned
6150 // to the conflict method.
6151 // Note that there is a race in the presence of multiple threads and we may leak
6152 // memory from the LinearAlloc, but that's a tradeoff compared to using
6153 // atomic operations.
6154 QuasiAtomic::ThreadFenceRelease();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006155 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006156 return new_conflict_method;
6157}
6158
Vladimir Marko921094a2017-01-12 18:37:06 +00006159bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6160 Handle<mirror::Class> klass,
6161 Handle<mirror::IfTable> iftable) {
6162 DCHECK(!klass->IsInterface());
6163 const bool has_superclass = klass->HasSuperClass();
6164 const bool extend_super_iftable = has_superclass;
6165 const size_t ifcount = klass->GetIfTableCount();
6166 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6167 for (size_t i = 0; i < ifcount; ++i) {
6168 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6169 if (num_methods > 0) {
6170 const bool is_super = i < super_ifcount;
6171 // This is an interface implemented by a super-class. Therefore we can just copy the method
6172 // array from the superclass.
6173 const bool super_interface = is_super && extend_super_iftable;
6174 ObjPtr<mirror::PointerArray> method_array;
6175 if (super_interface) {
6176 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6177 DCHECK(if_table != nullptr);
6178 DCHECK(if_table->GetMethodArray(i) != nullptr);
6179 // If we are working on a super interface, try extending the existing method array.
6180 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
6181 } else {
6182 method_array = AllocPointerArray(self, num_methods);
6183 }
6184 if (UNLIKELY(method_array == nullptr)) {
6185 self->AssertPendingOOMException();
6186 return false;
6187 }
6188 iftable->SetMethodArray(i, method_array);
6189 }
6190 }
6191 return true;
6192}
6193
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006194void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6195 ArtMethod* imt_conflict_method,
6196 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006197 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006198 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006199 // Place method in imt if entry is empty, place conflict otherwise.
6200 if (*imt_ref == unimplemented_method) {
6201 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006202 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006203 // If we are not a conflict and we have the same signature and name as the imt
6204 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006205 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6206 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006207 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006208 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006209 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006210 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006211 *imt_ref = current_method;
6212 } else {
Alex Light9139e002015-10-09 15:59:48 -07006213 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006214 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006215 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006216 } else {
6217 // Place the default conflict method. Note that there may be an existing conflict
6218 // method in the IMT, but it could be one tailored to the super class, with a
6219 // specific ImtConflictTable.
6220 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006221 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006222 }
6223}
6224
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006225void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006226 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6227 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006228 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006229 Runtime* const runtime = Runtime::Current();
6230 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6231 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006232 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006233 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006234 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006235 FillIMTFromIfTable(klass->GetIfTable(),
6236 unimplemented_method,
6237 conflict_method,
6238 klass,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006239 /*create_conflict_tables*/true,
6240 /*ignore_copied_methods*/false,
6241 &new_conflict,
6242 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006243 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006244 if (!klass->ShouldHaveImt()) {
6245 return;
6246 }
6247 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6248 // we can just use the same pointer.
6249 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006250 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006251 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6252 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6253 bool same = true;
6254 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6255 ArtMethod* method = imt_data[i];
6256 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6257 if (method != super_method) {
6258 bool is_conflict_table = method->IsRuntimeMethod() &&
6259 method != unimplemented_method &&
6260 method != conflict_method;
6261 // Verify conflict contents.
6262 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6263 super_method != unimplemented_method &&
6264 super_method != conflict_method;
6265 if (!is_conflict_table || !super_conflict_table) {
6266 same = false;
6267 } else {
6268 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6269 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6270 same = same && table1->Equals(table2, image_pointer_size_);
6271 }
6272 }
6273 }
6274 if (same) {
6275 imt = super_imt;
6276 }
6277 }
6278 if (imt == nullptr) {
6279 imt = klass->GetImt(image_pointer_size_);
6280 DCHECK(imt != nullptr);
6281 imt->Populate(imt_data, image_pointer_size_);
6282 } else {
6283 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006284 }
6285}
6286
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006287ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6288 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006289 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006290 void* data = linear_alloc->Alloc(Thread::Current(),
6291 ImtConflictTable::ComputeSize(count,
6292 image_pointer_size));
6293 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6294}
6295
6296ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6297 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6298}
6299
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006300void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006301 ArtMethod* unimplemented_method,
6302 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006303 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006304 bool create_conflict_tables,
6305 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006306 /*out*/bool* new_conflict,
6307 /*out*/ArtMethod** imt) {
6308 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006309 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006310 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006311 const size_t num_virtuals = interface->NumVirtualMethods();
6312 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6313 // Virtual methods can be larger than the if table methods if there are default methods.
6314 DCHECK_GE(num_virtuals, method_array_count);
6315 if (kIsDebugBuild) {
6316 if (klass->IsInterface()) {
6317 DCHECK_EQ(method_array_count, 0u);
6318 } else {
6319 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6320 }
6321 }
6322 if (method_array_count == 0) {
6323 continue;
6324 }
6325 auto* method_array = if_table->GetMethodArray(i);
6326 for (size_t j = 0; j < method_array_count; ++j) {
6327 ArtMethod* implementation_method =
6328 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6329 if (ignore_copied_methods && implementation_method->IsCopied()) {
6330 continue;
6331 }
6332 DCHECK(implementation_method != nullptr);
6333 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6334 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6335 // or interface methods in the IMT here they will not create extra conflicts since we compare
6336 // names and signatures in SetIMTRef.
6337 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006338 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006339
6340 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6341 // the same implementation method, keep track of this to avoid creating a conflict table in
6342 // this case.
6343
6344 // Conflict table size for each IMT slot.
6345 ++conflict_counts[imt_index];
6346
6347 SetIMTRef(unimplemented_method,
6348 imt_conflict_method,
6349 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006350 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006351 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006352 }
6353 }
6354
6355 if (create_conflict_tables) {
6356 // Create the conflict tables.
6357 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006358 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006359 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006360 if (imt[i] == imt_conflict_method) {
6361 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6362 if (new_table != nullptr) {
6363 ArtMethod* new_conflict_method =
6364 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6365 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6366 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006367 } else {
6368 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006369 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006370 }
6371 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006372 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006373 }
6374 }
6375
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006376 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006377 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006378 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6379 // Virtual methods can be larger than the if table methods if there are default methods.
6380 if (method_array_count == 0) {
6381 continue;
6382 }
6383 auto* method_array = if_table->GetMethodArray(i);
6384 for (size_t j = 0; j < method_array_count; ++j) {
6385 ArtMethod* implementation_method =
6386 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6387 if (ignore_copied_methods && implementation_method->IsCopied()) {
6388 continue;
6389 }
6390 DCHECK(implementation_method != nullptr);
6391 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006392 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006393 if (!imt[imt_index]->IsRuntimeMethod() ||
6394 imt[imt_index] == unimplemented_method ||
6395 imt[imt_index] == imt_conflict_method) {
6396 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006397 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006398 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6399 const size_t num_entries = table->NumEntries(image_pointer_size_);
6400 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6401 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006402 }
6403 }
6404 }
6405}
6406
Alex Lighteb7c1442015-08-31 13:17:42 -07006407// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6408// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006409static bool NotSubinterfaceOfAny(
6410 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6411 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006412 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006413 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006414 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006415 for (ObjPtr<mirror::Class> c : classes) {
6416 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006417 return false;
6418 }
6419 }
6420 return true;
6421}
6422
6423// Fills in and flattens the interface inheritance hierarchy.
6424//
6425// By the end of this function all interfaces in the transitive closure of to_process are added to
6426// the iftable and every interface precedes all of its sub-interfaces in this list.
6427//
6428// all I, J: Interface | I <: J implies J precedes I
6429//
6430// (note A <: B means that A is a subtype of B)
6431//
6432// This returns the total number of items in the iftable. The iftable might be resized down after
6433// this call.
6434//
6435// We order this backwards so that we do not need to reorder superclass interfaces when new
6436// interfaces are added in subclass's interface tables.
6437//
6438// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6439// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6440// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6441// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006442static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006443 size_t super_ifcount,
6444 std::vector<mirror::Class*> to_process)
6445 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006446 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006447 // This is the set of all class's already in the iftable. Used to make checking if a class has
6448 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006449 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006450 // The first super_ifcount elements are from the superclass. We note that they are already added.
6451 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006452 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006453 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6454 classes_in_iftable.insert(iface);
6455 }
6456 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006457 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006458 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6459 // At this point in the loop current-iface-list has the invariant that:
6460 // for every pair of interfaces I,J within it:
6461 // if index_of(I) < index_of(J) then I is not a subtype of J
6462
6463 // If we have already seen this element then all of its super-interfaces must already be in the
6464 // current-iface-list so we can skip adding it.
6465 if (!ContainsElement(classes_in_iftable, interface)) {
6466 // We haven't seen this interface so add all of its super-interfaces onto the
6467 // current-iface-list, skipping those already on it.
6468 int32_t ifcount = interface->GetIfTableCount();
6469 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006470 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006471 if (!ContainsElement(classes_in_iftable, super_interface)) {
6472 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6473 classes_in_iftable.insert(super_interface);
6474 iftable->SetInterface(filled_ifcount, super_interface);
6475 filled_ifcount++;
6476 }
6477 }
6478 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6479 // Place this interface onto the current-iface-list after all of its super-interfaces.
6480 classes_in_iftable.insert(interface);
6481 iftable->SetInterface(filled_ifcount, interface);
6482 filled_ifcount++;
6483 } else if (kIsDebugBuild) {
6484 // Check all super-interfaces are already in the list.
6485 int32_t ifcount = interface->GetIfTableCount();
6486 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006487 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006488 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006489 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6490 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006491 }
6492 }
6493 }
6494 if (kIsDebugBuild) {
6495 // Check that the iftable is ordered correctly.
6496 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006497 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006498 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006499 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006500 // !(if_a <: if_b)
6501 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006502 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6503 << ") extends "
6504 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006505 << "interface list.";
6506 }
6507 }
6508 }
6509 return filled_ifcount;
6510}
6511
6512bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6513 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6514 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006515 const bool has_superclass = klass->HasSuperClass();
6516 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006517 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006518 const size_t num_interfaces =
6519 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006520 if (num_interfaces == 0) {
6521 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006522 if (LIKELY(has_superclass)) {
6523 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6524 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006525 // Class implements no interfaces.
6526 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006527 return true;
6528 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006529 // Class implements same interfaces as parent, are any of these not marker interfaces?
6530 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006531 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006532 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006533 if (super_iftable->GetMethodArrayCount(i) > 0) {
6534 has_non_marker_interface = true;
6535 break;
6536 }
6537 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006538 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006539 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006540 klass->SetIfTable(super_iftable);
6541 return true;
6542 }
6543 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006544 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006545 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006546 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006547 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006548 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006549 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006550 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006551 if (UNLIKELY(!interface->IsInterface())) {
6552 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006553 ThrowIncompatibleClassChangeError(klass.Get(),
6554 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006555 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006556 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6557 return false;
6558 }
6559 ifcount += interface->GetIfTableCount();
6560 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006561 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006562 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006563 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006564 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006565 return false;
6566 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006567 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006568 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006569 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006570 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006571 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006572 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006573 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006574 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006575
6576 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6577 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6578 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006579 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006580
6581 size_t new_ifcount;
6582 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006583 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Alex Lighteb7c1442015-08-31 13:17:42 -07006584 std::vector<mirror::Class*> to_add;
6585 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006586 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006587 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006588 to_add.push_back(interface.Ptr());
Ian Rogersb52b01a2012-01-12 17:01:38 -08006589 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006590
6591 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006592 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006593
Ian Rogers7b078e82014-09-10 14:44:24 -07006594 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006595
Ian Rogersb52b01a2012-01-12 17:01:38 -08006596 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07006597 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006598 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006599 iftable.Assign(down_cast<mirror::IfTable*>(
Alex Lighteb7c1442015-08-31 13:17:42 -07006600 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006601 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006602 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006603 return false;
6604 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006605 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08006606 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006607 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006608 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006609 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07006610 return true;
6611}
6612
Alex Light1f3925d2016-09-07 12:04:20 -07006613// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
6614// of methods must be unique.
6615static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
6616 return nullptr;
6617}
6618
6619template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07006620static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07006621 const ScopedArenaVector<ArtMethod*>& list,
6622 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006623 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006624 for (ArtMethod* method : list) {
6625 if (cmp.HasSameNameAndSignature(method)) {
6626 return method;
6627 }
6628 }
Alex Light1f3925d2016-09-07 12:04:20 -07006629 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07006630}
6631
Alex Light1f3925d2016-09-07 12:04:20 -07006632// Check that all vtable entries are present in this class's virtuals or are the same as a
6633// superclasses vtable entry.
6634static void CheckClassOwnsVTableEntries(Thread* self,
6635 Handle<mirror::Class> klass,
6636 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006637 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07006638 StackHandleScope<2> hs(self);
6639 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006640 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07006641 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006642 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006643 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6644 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6645 CHECK(m != nullptr);
6646
Alex Lighta41a30782017-03-29 11:33:19 -07006647 if (m->GetMethodIndexDuringLinking() != i) {
6648 LOG(WARNING) << m->PrettyMethod()
6649 << " has an unexpected method index for its spot in the vtable for class"
6650 << klass->PrettyClass();
6651 }
Alex Lighte64300b2015-12-15 15:02:47 -08006652 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6653 auto is_same_method = [m] (const ArtMethod& meth) {
6654 return &meth == m;
6655 };
Alex Light3f980532017-03-17 15:10:32 -07006656 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6657 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
6658 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
6659 << klass->PrettyClass() << " or any of its superclasses!";
6660 }
Alex Lighte64300b2015-12-15 15:02:47 -08006661 }
6662}
6663
Alex Light1f3925d2016-09-07 12:04:20 -07006664// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
6665// method is overridden in a subclass.
6666static void CheckVTableHasNoDuplicates(Thread* self,
6667 Handle<mirror::Class> klass,
6668 PointerSize pointer_size)
6669 REQUIRES_SHARED(Locks::mutator_lock_) {
6670 StackHandleScope<1> hs(self);
6671 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6672 int32_t num_entries = vtable->GetLength();
6673 for (int32_t i = 0; i < num_entries; i++) {
6674 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6675 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe).
6676 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6677 vtable_entry->GetAccessFlags())) {
6678 continue;
6679 }
6680 MethodNameAndSignatureComparator name_comparator(
6681 vtable_entry->GetInterfaceMethodIfProxy(pointer_size));
Alex Lightc7a420c2016-10-18 14:33:18 -07006682 for (int32_t j = i + 1; j < num_entries; j++) {
Alex Light1f3925d2016-09-07 12:04:20 -07006683 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Alex Lightc7a420c2016-10-18 14:33:18 -07006684 if (!klass->CanAccessMember(other_entry->GetDeclaringClass(),
6685 other_entry->GetAccessFlags())) {
6686 continue;
6687 }
Alex Light3f980532017-03-17 15:10:32 -07006688 if (vtable_entry == other_entry ||
6689 name_comparator.HasSameNameAndSignature(
6690 other_entry->GetInterfaceMethodIfProxy(pointer_size))) {
6691 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
6692 << klass->PrettyClass() << " in method " << vtable_entry->PrettyMethod()
6693 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(vtable_entry) << ") and "
6694 << other_entry->PrettyMethod() << " (0x" << std::hex
6695 << reinterpret_cast<uintptr_t>(other_entry) << ")";
6696 }
Alex Light1f3925d2016-09-07 12:04:20 -07006697 }
6698 }
6699}
6700
6701static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
6702 REQUIRES_SHARED(Locks::mutator_lock_) {
6703 CheckClassOwnsVTableEntries(self, klass, pointer_size);
6704 CheckVTableHasNoDuplicates(self, klass, pointer_size);
6705}
6706
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006707void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
6708 ArtMethod* unimplemented_method,
6709 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006710 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006711 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07006712 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006713 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006714 if (super_class->ShouldHaveImt()) {
6715 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6716 for (size_t i = 0; i < ImTable::kSize; ++i) {
6717 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07006718 }
6719 } else {
6720 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006721 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08006722 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006723 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006724 FillIMTFromIfTable(if_table,
6725 unimplemented_method,
6726 imt_conflict_method,
6727 klass.Get(),
6728 /*create_conflict_table*/false,
6729 /*ignore_copied_methods*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006730 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006731 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07006732 }
6733 }
6734}
6735
Vladimir Marko921094a2017-01-12 18:37:06 +00006736class ClassLinker::LinkInterfaceMethodsHelper {
6737 public:
6738 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
6739 Handle<mirror::Class> klass,
6740 Thread* self,
6741 Runtime* runtime)
6742 : class_linker_(class_linker),
6743 klass_(klass),
6744 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
6745 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
6746 self_(self),
6747 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
6748 allocator_(&stack_),
6749 default_conflict_methods_(allocator_.Adapter()),
6750 overriding_default_conflict_methods_(allocator_.Adapter()),
6751 miranda_methods_(allocator_.Adapter()),
6752 default_methods_(allocator_.Adapter()),
6753 overriding_default_methods_(allocator_.Adapter()),
6754 move_table_(allocator_.Adapter()) {
6755 }
6756
6757 ArtMethod* FindMethod(ArtMethod* interface_method,
6758 MethodNameAndSignatureComparator& interface_name_comparator,
6759 ArtMethod* vtable_impl)
6760 REQUIRES_SHARED(Locks::mutator_lock_);
6761
6762 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
6763 MethodNameAndSignatureComparator& interface_name_comparator)
6764 REQUIRES_SHARED(Locks::mutator_lock_);
6765
6766 bool HasNewVirtuals() const {
6767 return !(miranda_methods_.empty() &&
6768 default_methods_.empty() &&
6769 overriding_default_methods_.empty() &&
6770 overriding_default_conflict_methods_.empty() &&
6771 default_conflict_methods_.empty());
6772 }
6773
6774 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
6775
6776 ObjPtr<mirror::PointerArray> UpdateVtable(
6777 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
6778 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
6779
6780 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
6781
6782 void UpdateIMT(ArtMethod** out_imt);
6783
6784 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
6785 if (kIsDebugBuild) {
6786 PointerSize pointer_size = class_linker_->GetImagePointerSize();
6787 // Check that there are no stale methods are in the dex cache array.
6788 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
6789 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01006790 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
6791 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00006792 CHECK(move_table_.find(m) == move_table_.end() ||
6793 // The original versions of copied methods will still be present so allow those too.
6794 // Note that if the first check passes this might fail to GetDeclaringClass().
6795 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
6796 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
6797 [m] (ArtMethod& meth) {
6798 return &meth == m;
6799 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
6800 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
6801 }
6802 }
6803 }
6804
6805 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
6806 LengthPrefixedArray<ArtMethod>* methods) {
6807 if (kIsDebugBuild) {
6808 CHECK(methods != nullptr);
6809 // Put some random garbage in old methods to help find stale pointers.
6810 if (methods != old_methods && old_methods != nullptr) {
6811 // Need to make sure the GC is not running since it could be scanning the methods we are
6812 // about to overwrite.
6813 ScopedThreadStateChange tsc(self_, kSuspended);
6814 gc::ScopedGCCriticalSection gcs(self_,
6815 gc::kGcCauseClassLinker,
6816 gc::kCollectorTypeClassLinker);
6817 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
6818 method_size_,
6819 method_alignment_);
6820 memset(old_methods, 0xFEu, old_size);
6821 }
6822 }
6823 }
6824
6825 private:
6826 size_t NumberOfNewVirtuals() const {
6827 return miranda_methods_.size() +
6828 default_methods_.size() +
6829 overriding_default_conflict_methods_.size() +
6830 overriding_default_methods_.size() +
6831 default_conflict_methods_.size();
6832 }
6833
6834 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
6835 return !klass_->IsInterface();
6836 }
6837
6838 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
6839 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
6840 << "Interfaces should only have default-conflict methods appended to them.";
6841 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
6842 << miranda_methods_.size()
6843 << " default_methods=" << default_methods_.size()
6844 << " overriding_default_methods=" << overriding_default_methods_.size()
6845 << " default_conflict_methods=" << default_conflict_methods_.size()
6846 << " overriding_default_conflict_methods="
6847 << overriding_default_conflict_methods_.size();
6848 }
6849
6850 ClassLinker* class_linker_;
6851 Handle<mirror::Class> klass_;
6852 size_t method_alignment_;
6853 size_t method_size_;
6854 Thread* const self_;
6855
6856 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
6857 // the virtual methods array.
6858 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
6859 // during cross compilation.
6860 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
6861 ArenaStack stack_;
6862 ScopedArenaAllocator allocator_;
6863
6864 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
6865 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
6866 ScopedArenaVector<ArtMethod*> miranda_methods_;
6867 ScopedArenaVector<ArtMethod*> default_methods_;
6868 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
6869
6870 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
6871};
6872
6873ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
6874 ArtMethod* interface_method,
6875 MethodNameAndSignatureComparator& interface_name_comparator,
6876 ArtMethod* vtable_impl) {
6877 ArtMethod* current_method = nullptr;
6878 switch (class_linker_->FindDefaultMethodImplementation(self_,
6879 interface_method,
6880 klass_,
6881 /*out*/&current_method)) {
6882 case DefaultMethodSearchResult::kDefaultConflict: {
6883 // Default method conflict.
6884 DCHECK(current_method == nullptr);
6885 ArtMethod* default_conflict_method = nullptr;
6886 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
6887 // We can reuse the method from the superclass, don't bother adding it to virtuals.
6888 default_conflict_method = vtable_impl;
6889 } else {
6890 // See if we already have a conflict method for this method.
6891 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
6892 interface_name_comparator,
6893 default_conflict_methods_,
6894 overriding_default_conflict_methods_);
6895 if (LIKELY(preexisting_conflict != nullptr)) {
6896 // We already have another conflict we can reuse.
6897 default_conflict_method = preexisting_conflict;
6898 } else {
6899 // Note that we do this even if we are an interface since we need to create this and
6900 // cannot reuse another classes.
6901 // Create a new conflict method for this to use.
6902 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6903 new(default_conflict_method) ArtMethod(interface_method,
6904 class_linker_->GetImagePointerSize());
6905 if (vtable_impl == nullptr) {
6906 // Save the conflict method. We need to add it to the vtable.
6907 default_conflict_methods_.push_back(default_conflict_method);
6908 } else {
6909 // Save the conflict method but it is already in the vtable.
6910 overriding_default_conflict_methods_.push_back(default_conflict_method);
6911 }
6912 }
6913 }
6914 current_method = default_conflict_method;
6915 break;
6916 } // case kDefaultConflict
6917 case DefaultMethodSearchResult::kDefaultFound: {
6918 DCHECK(current_method != nullptr);
6919 // Found a default method.
6920 if (vtable_impl != nullptr &&
6921 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
6922 // We found a default method but it was the same one we already have from our
6923 // superclass. Don't bother adding it to our vtable again.
6924 current_method = vtable_impl;
6925 } else if (LIKELY(FillTables())) {
6926 // Interfaces don't need to copy default methods since they don't have vtables.
6927 // Only record this default method if it is new to save space.
6928 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
6929 // would make lookup for interface super much faster. (We would only need to scan
6930 // the iftable to find if there is a NSME or AME.)
6931 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
6932 default_methods_,
6933 overriding_default_methods_);
6934 if (old == nullptr) {
6935 // We found a default method implementation and there were no conflicts.
6936 if (vtable_impl == nullptr) {
6937 // Save the default method. We need to add it to the vtable.
6938 default_methods_.push_back(current_method);
6939 } else {
6940 // Save the default method but it is already in the vtable.
6941 overriding_default_methods_.push_back(current_method);
6942 }
6943 } else {
6944 CHECK(old == current_method) << "Multiple default implementations selected!";
6945 }
6946 }
6947 break;
6948 } // case kDefaultFound
6949 case DefaultMethodSearchResult::kAbstractFound: {
6950 DCHECK(current_method == nullptr);
6951 // Abstract method masks all defaults.
6952 if (vtable_impl != nullptr &&
6953 vtable_impl->IsAbstract() &&
6954 !vtable_impl->IsDefaultConflicting()) {
6955 // We need to make this an abstract method but the version in the vtable already is so
6956 // don't do anything.
6957 current_method = vtable_impl;
6958 }
6959 break;
6960 } // case kAbstractFound
6961 }
6962 return current_method;
6963}
6964
6965ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
6966 ArtMethod* interface_method,
6967 MethodNameAndSignatureComparator& interface_name_comparator) {
6968 // Find out if there is already a miranda method we can use.
6969 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
6970 miranda_methods_);
6971 if (miranda_method == nullptr) {
6972 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
6973 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
6974 CHECK(miranda_method != nullptr);
6975 // Point the interface table at a phantom slot.
6976 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
6977 miranda_methods_.push_back(miranda_method);
6978 }
6979 return miranda_method;
6980}
6981
6982void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
6983 LogNewVirtuals();
6984
6985 const size_t old_method_count = klass_->NumMethods();
6986 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
6987 DCHECK_NE(old_method_count, new_method_count);
6988
6989 // Attempt to realloc to save RAM if possible.
6990 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
6991 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
6992 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
6993 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
6994 // CopyFrom has internal read barriers.
6995 //
6996 // TODO We should maybe move some of this into mirror::Class or at least into another method.
6997 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
6998 method_size_,
6999 method_alignment_);
7000 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7001 method_size_,
7002 method_alignment_);
7003 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7004 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007005 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007006 self_, old_methods, old_methods_ptr_size, new_size));
7007 CHECK(methods != nullptr); // Native allocation failure aborts.
7008
7009 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7010 if (methods != old_methods) {
7011 // Maps from heap allocated miranda method to linear alloc miranda method.
7012 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7013 // Copy over the old methods.
7014 for (auto& m : klass_->GetMethods(pointer_size)) {
7015 move_table_.emplace(&m, &*out);
7016 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7017 // barriers when it copies.
7018 out->CopyFrom(&m, pointer_size);
7019 ++out;
7020 }
7021 }
7022 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7023 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7024 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007025 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7026 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007027 ArtMethod& new_method = *out;
7028 new_method.CopyFrom(mir_method, pointer_size);
7029 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7030 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7031 << "Miranda method should be abstract!";
7032 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007033 // Update the entry in the method array, as the array will be used for future lookups,
7034 // where thread suspension is allowed.
7035 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7036 // would not see them.
7037 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007038 ++out;
7039 }
7040 // We need to copy the default methods into our own method table since the runtime requires that
7041 // every method on a class's vtable be in that respective class's virtual method table.
7042 // NOTE This means that two classes might have the same implementation of a method from the same
7043 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7044 // default method found on a class with one found on the declaring interface directly and must
7045 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007046 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7047 &overriding_default_methods_}) {
7048 for (size_t i = 0; i < methods_vec->size(); ++i) {
7049 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007050 ArtMethod& new_method = *out;
7051 new_method.CopyFrom(def_method, pointer_size);
7052 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7053 // verified yet it shouldn't have methods that are skipping access checks.
7054 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7055 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007056 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007057 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7058 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7059 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7060 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007061 // Update the entry in the method array, as the array will be used for future lookups,
7062 // where thread suspension is allowed.
7063 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7064 // would not see them.
7065 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007066 ++out;
7067 }
7068 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007069 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7070 &overriding_default_conflict_methods_}) {
7071 for (size_t i = 0; i < methods_vec->size(); ++i) {
7072 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007073 ArtMethod& new_method = *out;
7074 new_method.CopyFrom(conf_method, pointer_size);
7075 // This is a type of default method (there are default method impls, just a conflict) so
7076 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7077 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7078 // methods that are skipping access checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007079 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007080 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
7081 constexpr uint32_t kMaskFlags = ~(kAccAbstract | kAccSkipAccessChecks);
7082 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7083 DCHECK(new_method.IsDefaultConflicting());
7084 // The actual method might or might not be marked abstract since we just copied it from a
7085 // (possibly default) interface method. We need to set it entry point to be the bridge so
7086 // that the compiler will not invoke the implementation of whatever method we copied from.
7087 EnsureThrowsInvocationError(class_linker_, &new_method);
7088 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007089 // Update the entry in the method array, as the array will be used for future lookups,
7090 // where thread suspension is allowed.
7091 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7092 // would not see them.
7093 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007094 ++out;
7095 }
7096 }
7097 methods->SetSize(new_method_count);
7098 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7099}
7100
7101ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7102 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7103 ObjPtr<mirror::PointerArray> old_vtable) {
7104 // Update the vtable to the new method structures. We can skip this for interfaces since they
7105 // do not have vtables.
7106 const size_t old_vtable_count = old_vtable->GetLength();
7107 const size_t new_vtable_count = old_vtable_count +
7108 miranda_methods_.size() +
7109 default_methods_.size() +
7110 default_conflict_methods_.size();
7111
7112 ObjPtr<mirror::PointerArray> vtable =
7113 down_cast<mirror::PointerArray*>(old_vtable->CopyOf(self_, new_vtable_count));
7114 if (UNLIKELY(vtable == nullptr)) {
7115 self_->AssertPendingOOMException();
7116 return nullptr;
7117 }
7118
7119 size_t vtable_pos = old_vtable_count;
7120 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7121 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7122 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7123 default_conflict_methods_,
7124 miranda_methods_}) {
7125 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007126 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007127 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7128 // fields are references into the dex file the method was defined in. Since the ArtMethod
7129 // does not store that information it uses declaring_class_->dex_cache_.
7130 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7131 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7132 ++vtable_pos;
7133 }
7134 }
7135 DCHECK_EQ(vtable_pos, new_vtable_count);
7136
7137 // Update old vtable methods. We use the default_translations map to figure out what each
7138 // vtable entry should be updated to, if they need to be at all.
7139 for (size_t i = 0; i < old_vtable_count; ++i) {
7140 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7141 // Try and find what we need to change this method to.
7142 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007143 if (translation_it != default_translations.end()) {
7144 if (translation_it->second.IsInConflict()) {
7145 // Find which conflict method we are to use for this method.
7146 MethodNameAndSignatureComparator old_method_comparator(
7147 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7148 // We only need to look through overriding_default_conflict_methods since this is an
7149 // overridden method we are fixing up here.
7150 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7151 old_method_comparator, overriding_default_conflict_methods_);
7152 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7153 translated_method = new_conflict_method;
7154 } else if (translation_it->second.IsAbstract()) {
7155 // Find which miranda method we are to use for this method.
7156 MethodNameAndSignatureComparator old_method_comparator(
7157 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7158 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7159 miranda_methods_);
7160 DCHECK(miranda_method != nullptr);
7161 translated_method = miranda_method;
7162 } else {
7163 // Normal default method (changed from an older default or abstract interface method).
7164 DCHECK(translation_it->second.IsTranslation());
7165 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007166 auto it = move_table_.find(translated_method);
7167 DCHECK(it != move_table_.end());
7168 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007169 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007170 } else {
7171 auto it = move_table_.find(translated_method);
7172 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007173 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007174
7175 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007176 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007177 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007178 if (kIsDebugBuild) {
7179 auto* methods = klass_->GetMethodsPtr();
7180 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007181 reinterpret_cast<uintptr_t>(translated_method));
7182 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007183 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7184 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007185 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007186 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007187 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007188 }
7189 }
7190 klass_->SetVTable(vtable.Ptr());
7191 return vtable;
7192}
7193
7194void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7195 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7196 const size_t ifcount = klass_->GetIfTableCount();
7197 // Go fix up all the stale iftable pointers.
7198 for (size_t i = 0; i < ifcount; ++i) {
7199 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7200 auto* method_array = iftable->GetMethodArray(i);
7201 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7202 DCHECK(m != nullptr) << klass_->PrettyClass();
7203 auto it = move_table_.find(m);
7204 if (it != move_table_.end()) {
7205 auto* new_m = it->second;
7206 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7207 method_array->SetElementPtrSize(j, new_m, pointer_size);
7208 }
7209 }
7210 }
7211}
7212
7213void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7214 // Fix up IMT next.
7215 for (size_t i = 0; i < ImTable::kSize; ++i) {
7216 auto it = move_table_.find(out_imt[i]);
7217 if (it != move_table_.end()) {
7218 out_imt[i] = it->second;
7219 }
7220 }
7221}
7222
Alex Light705ad492015-09-21 11:36:30 -07007223// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007224bool ClassLinker::LinkInterfaceMethods(
7225 Thread* self,
7226 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007227 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007228 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007229 ArtMethod** out_imt) {
7230 StackHandleScope<3> hs(self);
7231 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007232
7233 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007234 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007235 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007236 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007237 const size_t ifcount = klass->GetIfTableCount();
7238
Vladimir Marko921094a2017-01-12 18:37:06 +00007239 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007240
7241 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7242 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007243 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007244 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007245 const bool extend_super_iftable = has_superclass;
7246 if (has_superclass && fill_tables) {
7247 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007248 unimplemented_method,
7249 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007250 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007251 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007252 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007253 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7254 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007255 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007256 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7257 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007258 }
7259 }
7260
Vladimir Marko921094a2017-01-12 18:37:06 +00007261 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7262
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007263 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007264 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007265 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7266 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7267 // they will already be null. This has the additional benefit that the declarer of a miranda
7268 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007269 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007270 --i;
Alex Light9139e002015-10-09 15:59:48 -07007271 DCHECK_LT(i, ifcount);
7272
Alex Light705ad492015-09-21 11:36:30 -07007273 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007274 if (num_methods > 0) {
7275 StackHandleScope<2> hs2(self);
7276 const bool is_super = i < super_ifcount;
7277 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007278 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7279 // conflict methods. Just set this as nullptr in those cases.
7280 Handle<mirror::PointerArray> method_array(fill_tables
7281 ? hs2.NewHandle(iftable->GetMethodArray(i))
7282 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007283
Alex Lighte64300b2015-12-15 15:02:47 -08007284 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007285 ScopedNullHandle<mirror::PointerArray> null_handle;
7286 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007287 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007288
Alex Light9139e002015-10-09 15:59:48 -07007289 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7290 // and confusing. Default methods should always look through all the superclasses
7291 // because they are the last choice of an implementation. We get around this by looking
7292 // at the super-classes iftable methods (copied into method_array previously) when we are
7293 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007294 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007295 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007296 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007297 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007298 using_virtuals = true;
7299 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7300 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007301 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007302 // For a new interface, however, we need the whole vtable in case a new
7303 // interface method is implemented in the whole superclass.
7304 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007305 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007306 input_vtable_array = vtable;
7307 input_array_length = input_vtable_array->GetLength();
7308 }
Alex Lighte64300b2015-12-15 15:02:47 -08007309
Alex Lighteb7c1442015-08-31 13:17:42 -07007310 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007311 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007312 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007313 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007314 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Andreas Gampe75a7db62016-09-26 12:04:26 -07007315 uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Alex Lighteb7c1442015-08-31 13:17:42 -07007316 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007317 // For each method listed in the interface's method list, find the
7318 // matching method in our class's method list. We want to favor the
7319 // subclass over the superclass, which just requires walking
7320 // back from the end of the vtable. (This only matters if the
7321 // superclass defines a private method and this class redefines
7322 // it -- otherwise it would use the same vtable slot. In .dex files
7323 // those don't end up in the virtual method table, so it shouldn't
7324 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007325 //
7326 // To find defaults we need to do the same but also go over interfaces.
7327 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007328 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007329 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007330 ArtMethod* vtable_method = using_virtuals ?
7331 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007332 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7333 ArtMethod* vtable_method_for_name_comparison =
7334 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007335 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007336 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007337 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007338 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7339 // allocations.
7340 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007341 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007342 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007343 vtable_method->PrettyMethod().c_str(),
7344 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007345 return false;
Alex Light9139e002015-10-09 15:59:48 -07007346 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007347 // We might have a newer, better, default method for this, so we just skip it. If we
7348 // are still using this we will select it again when scanning for default methods. To
7349 // obviate the need to copy the method again we will make a note that we already found
7350 // a default here.
7351 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007352 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007353 break;
7354 } else {
7355 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007356 if (LIKELY(fill_tables)) {
7357 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7358 // Place method in imt if entry is empty, place conflict otherwise.
7359 SetIMTRef(unimplemented_method,
7360 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007361 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007362 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007363 /*out*/imt_ptr);
7364 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007365 break;
7366 }
7367 }
Alex Light9139e002015-10-09 15:59:48 -07007368 }
7369 // Continue on to the next method if we are done.
7370 if (LIKELY(found_impl)) {
7371 continue;
7372 } else if (LIKELY(super_interface)) {
7373 // Don't look for a default implementation when the super-method is implemented directly
7374 // by the class.
7375 //
7376 // See if we can use the superclasses method and skip searching everything else.
7377 // Note: !found_impl && super_interface
7378 CHECK(extend_super_iftable);
7379 // If this is a super_interface method it is possible we shouldn't override it because a
7380 // superclass could have implemented it directly. We get the method the superclass used
7381 // to implement this to know if we can override it with a default method. Doing this is
7382 // safe since we know that the super_iftable is filled in so we can simply pull it from
7383 // there. We don't bother if this is not a super-classes interface since in that case we
7384 // have scanned the entire vtable anyway and would have found it.
7385 // TODO This is rather dirty but it is faster than searching through the entire vtable
7386 // every time.
7387 ArtMethod* supers_method =
7388 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7389 DCHECK(supers_method != nullptr);
7390 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007391 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007392 // The method is not overridable by a default method (i.e. it is directly implemented
7393 // in some class). Therefore move onto the next interface method.
7394 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007395 } else {
7396 // If the super-classes method is override-able by a default method we need to keep
7397 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7398 // 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 -07007399 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7400 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7401 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007402 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007403 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7404 << " and not 'nullptr' or "
7405 << supers_method->PrettyMethod()
7406 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007407 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007408 }
7409 }
7410 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007411 ArtMethod* current_method = helper.FindMethod(interface_method,
7412 interface_name_comparator,
7413 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007414 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007415 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007416 // We could not find an implementation for this method and since it is a brand new
7417 // interface we searched the entire vtable (and all default methods) for an
7418 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007419 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7420 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007421 }
7422
7423 if (current_method != nullptr) {
7424 // We found a default method implementation. Record it in the iftable and IMT.
7425 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7426 SetIMTRef(unimplemented_method,
7427 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007428 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007429 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007430 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007431 }
7432 }
Alex Light705ad492015-09-21 11:36:30 -07007433 } // For each method in interface end.
7434 } // if (num_methods > 0)
7435 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007436 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007437 if (helper.HasNewVirtuals()) {
7438 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7439 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7440 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7441
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007442 // 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 -07007443 // suspension assert.
7444 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007445
Alex Light705ad492015-09-21 11:36:30 -07007446 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007447 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007448 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007449 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07007450 return false;
7451 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007452 helper.UpdateIfTable(iftable);
7453 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007454 }
Alex Light705ad492015-09-21 11:36:30 -07007455
Vladimir Marko921094a2017-01-12 18:37:06 +00007456 helper.CheckNoStaleMethodsInDexCache();
7457 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007458 } else {
7459 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007460 }
Alex Light705ad492015-09-21 11:36:30 -07007461 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007462 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007463 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007464 return true;
7465}
7466
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007467bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007468 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007469 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007470}
7471
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007472bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007473 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007474 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007475}
7476
Brian Carlstromdbc05252011-09-09 01:59:59 -07007477struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08007478 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07007479 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007480 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007481 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007482 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07007483 // 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 -07007484 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7485 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08007486 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00007487 if (type1 == Primitive::kPrimNot) {
7488 // Reference always goes first.
7489 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08007490 }
Vladimir Markod5777482014-11-12 17:02:02 +00007491 if (type2 == Primitive::kPrimNot) {
7492 // Reference always goes first.
7493 return false;
7494 }
7495 size_t size1 = Primitive::ComponentSize(type1);
7496 size_t size2 = Primitive::ComponentSize(type2);
7497 if (size1 != size2) {
7498 // Larger primitive types go first.
7499 return size1 > size2;
7500 }
7501 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7502 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007503 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007504 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7505 // by name and for equal names by type id index.
7506 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7507 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07007508 }
7509};
7510
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007511bool ClassLinker::LinkFields(Thread* self,
7512 Handle<mirror::Class> klass,
7513 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007514 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07007515 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07007516 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007517 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7518 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007519
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007520 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07007521 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007522 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007523 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007524 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007525 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007526 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07007527 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007528 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007529 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007530 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007531 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007532
David Sehr709b0702016-10-13 09:12:37 -07007533 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007534
Brian Carlstromdbc05252011-09-09 01:59:59 -07007535 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07007536 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08007537 //
7538 // The overall sort order order is:
7539 // 1) All object reference fields, sorted alphabetically.
7540 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7541 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7542 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7543 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7544 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7545 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7546 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7547 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7548 //
7549 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7550 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007551 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07007552 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07007553 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07007554 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007555 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007556 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07007557 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7558 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07007559
Fred Shih381e4ca2014-08-25 17:24:27 -07007560 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07007561 size_t current_field = 0;
7562 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07007563 FieldGaps gaps;
7564
Brian Carlstromdbc05252011-09-09 01:59:59 -07007565 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007566 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007567 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07007568 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007569 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07007570 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007571 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007572 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7573 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07007574 MemberOffset old_offset = field_offset;
7575 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7576 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7577 }
Roland Levillain14d90572015-07-16 10:52:26 +01007578 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007579 grouped_and_sorted_fields.pop_front();
7580 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007581 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00007582 field_offset = MemberOffset(field_offset.Uint32Value() +
7583 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007584 }
Fred Shih381e4ca2014-08-25 17:24:27 -07007585 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7586 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00007587 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7588 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7589 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7590 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07007591 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
7592 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07007593 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007594
Elliott Hughesadb460d2011-10-05 17:02:34 -07007595 // 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 -07007596 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07007597 // We know there are no non-reference fields in the Reference classes, and we know
7598 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07007599 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007600 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07007601 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07007602 --num_reference_fields;
7603 }
7604
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007605 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007606 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007607 if (is_static) {
7608 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007609 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007610 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007611 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007612 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007613 if (num_reference_fields == 0 || super_class == nullptr) {
7614 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007615 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007616 if (super_class == nullptr ||
7617 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
7618 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007619 }
7620 }
7621 if (kIsDebugBuild) {
7622 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
7623 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007624 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007625 while (cur_super != nullptr) {
7626 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
7627 cur_super = cur_super->GetSuperClass();
7628 }
7629 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07007630 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007631 } else {
7632 // Check that there is at least num_reference_fields other than Object.class.
7633 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07007634 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007635 }
7636 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07007637 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007638 std::string temp;
7639 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
7640 size_t previous_size = klass->GetObjectSize();
7641 if (previous_size != 0) {
7642 // Make sure that we didn't originally have an incorrect size.
7643 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07007644 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007645 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007646 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007647 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007648
7649 if (kIsDebugBuild) {
7650 // Make sure that the fields array is ordered by name but all reference
7651 // offsets are at the beginning as far as alignment allows.
7652 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07007653 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00007654 : klass->GetFirstReferenceInstanceFieldOffset();
7655 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
7656 num_reference_fields *
7657 sizeof(mirror::HeapReference<mirror::Object>));
7658 MemberOffset current_ref_offset = start_ref_offset;
7659 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007660 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007661 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07007662 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
7663 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007664 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007665 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007666 // NOTE: The field names can be the same. This is not possible in the Java language
7667 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007668 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00007669 }
7670 Primitive::Type type = field->GetTypeAsPrimitiveType();
7671 bool is_primitive = type != Primitive::kPrimNot;
7672 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
7673 strcmp("referent", field->GetName()) == 0) {
7674 is_primitive = true; // We lied above, so we have to expect a lie here.
7675 }
7676 MemberOffset offset = field->GetOffsetDuringLinking();
7677 if (is_primitive) {
7678 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
7679 // Shuffled before references.
7680 size_t type_size = Primitive::ComponentSize(type);
7681 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
7682 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
7683 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
7684 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
7685 }
7686 } else {
7687 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
7688 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
7689 sizeof(mirror::HeapReference<mirror::Object>));
7690 }
7691 }
7692 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
7693 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007694 return true;
7695}
7696
Vladimir Marko76649e82014-11-10 18:32:59 +00007697// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007698void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007699 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007700 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007701 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007702 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007703 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007704 // Compute reference offsets unless our superclass overflowed.
7705 if (reference_offsets != mirror::Class::kClassWalkSuper) {
7706 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007707 if (num_reference_fields != 0u) {
7708 // All of the fields that contain object references are guaranteed be grouped in memory
7709 // starting at an appropriately aligned address after super class object data.
7710 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
7711 sizeof(mirror::HeapReference<mirror::Object>));
7712 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007713 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00007714 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007715 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007716 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00007717 reference_offsets |= (0xffffffffu << start_bit) &
7718 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007719 }
7720 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07007721 }
7722 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07007723 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007724}
7725
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007726ObjPtr<mirror::String> ClassLinker::ResolveString(dex::StringIndex string_idx,
Vladimir Marko28e012a2017-12-07 11:22:59 +00007727 Handle<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007728 DCHECK(dex_cache != nullptr);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007729 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007730 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007731 if (resolved != nullptr) {
Vladimir Marko28e012a2017-12-07 11:22:59 +00007732 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007733 }
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007734 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07007735 uint32_t utf16_length;
7736 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007737 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007738 if (string != nullptr) {
7739 dex_cache->SetResolvedString(string_idx, string);
7740 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00007741 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007742}
7743
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007744ObjPtr<mirror::String> ClassLinker::LookupString(dex::StringIndex string_idx,
Vladimir Marko28e012a2017-12-07 11:22:59 +00007745 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007746 DCHECK(dex_cache != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007747 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007748 if (resolved != nullptr) {
Vladimir Marko28e012a2017-12-07 11:22:59 +00007749 return resolved;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007750 }
Vladimir Markoa64b52d2017-12-08 16:27:49 +00007751 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007752 uint32_t utf16_length;
7753 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007754 ObjPtr<mirror::String> string =
7755 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007756 if (string != nullptr) {
7757 dex_cache->SetResolvedString(string_idx, string);
7758 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00007759 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007760}
7761
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007762ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
7763 ObjPtr<mirror::DexCache> dex_cache,
7764 ObjPtr<mirror::ClassLoader> class_loader) {
7765 const DexFile& dex_file = *dex_cache->GetDexFile();
7766 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
7767 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
7768 ObjPtr<mirror::Class> type = nullptr;
7769 if (descriptor[1] == '\0') {
7770 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
7771 // for primitive classes that aren't backed by dex files.
7772 type = FindPrimitiveClass(descriptor[0]);
7773 } else {
7774 Thread* const self = Thread::Current();
7775 DCHECK(self != nullptr);
7776 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
7777 // Find the class in the loaded classes table.
7778 type = LookupClass(self, descriptor, hash, class_loader.Ptr());
7779 }
7780 if (type != nullptr) {
7781 if (type->IsResolved()) {
7782 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07007783 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007784 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007785 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07007786 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007787 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07007788}
7789
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007790ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
7791 Handle<mirror::DexCache> dex_cache,
7792 Handle<mirror::ClassLoader> class_loader) {
7793 Thread* self = Thread::Current();
7794 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
7795 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
7796 if (resolved != nullptr) {
7797 // TODO: we used to throw here if resolved's class loader was not the
7798 // boot class loader. This was to permit different classes with the
7799 // same name to be loaded simultaneously by different loaders
7800 dex_cache->SetResolvedType(type_idx, resolved);
7801 } else {
7802 CHECK(self->IsExceptionPending())
7803 << "Expected pending exception for failed resolution of: " << descriptor;
7804 // Convert a ClassNotFoundException to a NoClassDefFoundError.
7805 StackHandleScope<1> hs(self);
7806 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
7807 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
7808 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
7809 self->ClearException();
7810 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
7811 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007812 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007813 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00007814 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007815 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00007816 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007817}
7818
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007819std::string DescribeSpace(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
7820 std::ostringstream oss;
7821 gc::Heap* heap = Runtime::Current()->GetHeap();
7822 gc::space::ContinuousSpace* cs = heap->FindContinuousSpaceFromAddress(klass.Ptr());
7823 if (cs != nullptr) {
7824 if (cs->IsImageSpace()) {
7825 oss << "image;" << cs->GetName() << ";" << cs->AsImageSpace()->GetImageFilename();
7826 } else {
7827 oss << "continuous;" << cs->GetName();
7828 }
7829 } else {
7830 gc::space::DiscontinuousSpace* ds =
7831 heap->FindDiscontinuousSpaceFromObject(klass, /* fail_ok */ true);
7832 if (ds != nullptr) {
7833 oss << "discontinuous;" << ds->GetName();
7834 } else {
7835 oss << "invalid";
7836 }
7837 }
7838 return oss.str();
7839}
7840
7841std::string DescribeLoaders(ObjPtr<mirror::ClassLoader> loader, const char* class_descriptor)
7842 REQUIRES_SHARED(Locks::mutator_lock_) {
7843 std::ostringstream oss;
7844 uint32_t hash = ComputeModifiedUtf8Hash(class_descriptor);
7845 ObjPtr<mirror::Class> path_class_loader =
7846 WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_PathClassLoader);
7847 ObjPtr<mirror::Class> dex_class_loader =
7848 WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_DexClassLoader);
7849 ObjPtr<mirror::Class> delegate_last_class_loader =
7850 WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_DelegateLastClassLoader);
7851
7852 // Print the class loader chain.
7853 bool found_class = false;
7854 const char* loader_separator = "";
7855 if (loader == nullptr) {
7856 oss << "BootClassLoader"; // This would be unexpected.
7857 }
7858 for (; loader != nullptr; loader = loader->GetParent()) {
7859 oss << loader_separator << loader->GetClass()->PrettyDescriptor();
7860 loader_separator = ";";
7861 // If we didn't find the interface yet, try to find it in the current class loader.
7862 if (!found_class) {
7863 ClassTable* table = Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(loader);
7864 ObjPtr<mirror::Class> klass =
7865 (table != nullptr) ? table->Lookup(class_descriptor, hash) : nullptr;
7866 if (klass != nullptr) {
7867 found_class = true;
7868 oss << "[hit:" << DescribeSpace(klass) << "]";
7869 }
7870 }
7871
7872 // For PathClassLoader, DexClassLoader or DelegateLastClassLoader
7873 // also dump the dex file locations.
7874 if (loader->GetClass() == path_class_loader ||
7875 loader->GetClass() == dex_class_loader ||
7876 loader->GetClass() == delegate_last_class_loader) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08007877 oss << "(";
7878 ScopedObjectAccessUnchecked soa(Thread::Current());
7879 StackHandleScope<1> hs(soa.Self());
7880 Handle<mirror::ClassLoader> handle(hs.NewHandle(loader));
7881 const char* path_separator = "";
7882 VisitClassLoaderDexFiles(soa,
7883 handle,
7884 [&](const DexFile* dex_file) {
7885 oss << path_separator << dex_file->GetLocation();
7886 path_separator = ":";
7887 return true; // Continue with the next DexFile.
7888 });
7889 oss << ")";
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007890 }
7891 }
7892
7893 return oss.str();
7894}
7895
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007896ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
7897 ObjPtr<mirror::DexCache> dex_cache,
7898 ObjPtr<mirror::ClassLoader> class_loader,
7899 uint32_t method_idx) {
7900 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
7901 // functions can optimize the search if the dex_cache is the same as the DexCache
7902 // of the class, with fall-back to name and signature search otherwise.
7903 ArtMethod* resolved = nullptr;
7904 if (klass->IsInterface()) {
7905 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
7906 } else {
7907 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
7908 }
7909 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
7910 if (resolved != nullptr) {
7911 // In case of jmvti, the dex file gets verified before being registered, so first
7912 // check if it's registered before checking class tables.
7913 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007914 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
7915 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007916 << "DexFile referrer: " << dex_file.GetLocation()
7917 << " ClassLoader: " << DescribeLoaders(class_loader, "");
7918 // Be a good citizen and update the dex cache to speed subsequent calls.
7919 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007920 // Disable the following invariant check as the verifier breaks it. b/73760543
7921 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
7922 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
7923 // << "Method: " << resolved->PrettyMethod() << ", "
7924 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
7925 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007926 }
7927 return resolved;
7928}
7929
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007930template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00007931ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07007932 Handle<mirror::DexCache> dex_cache,
7933 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007934 ArtMethod* referrer,
7935 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007936 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01007937 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07007938 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01007939 PointerSize pointer_size = image_pointer_size_;
7940 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007941 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007942 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
7943 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01007944 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
7945 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07007946 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007947 return resolved;
7948 }
Vladimir Marko89011192017-12-11 13:45:05 +00007949 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007950 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01007951 ObjPtr<mirror::Class> klass = nullptr;
7952 if (valid_dex_cache_method) {
7953 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
7954 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007955 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007956 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00007957 // We normaly should not end up here. However the verifier currently doesn't guarantee
7958 // the invariant of having the klass in the class table. b/73760543
7959 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00007960 }
Vladimir Markoba118822017-06-12 15:41:56 +01007961 } else {
7962 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00007963 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01007964 if (klass == nullptr) {
7965 DCHECK(Thread::Current()->IsExceptionPending());
7966 return nullptr;
7967 }
7968 }
7969
7970 // Check if the invoke type matches the class type.
7971 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
7972 CheckInvokeClassMismatch</* kThrow */ true>(
7973 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07007974 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007975 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007976 }
Vladimir Markoba118822017-06-12 15:41:56 +01007977
7978 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00007979 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007980 }
Vladimir Markoba118822017-06-12 15:41:56 +01007981
7982 // Note: We can check for IllegalAccessError only if we have a referrer.
7983 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
7984 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
7985 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
7986 if (!referring_class->CheckResolvedMethodAccess(methods_class,
7987 resolved,
7988 dex_cache.Get(),
7989 method_idx,
7990 type)) {
7991 DCHECK(Thread::Current()->IsExceptionPending());
7992 return nullptr;
7993 }
7994 }
7995
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007996 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01007997 if (LIKELY(resolved != nullptr) &&
7998 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
7999 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008000 return resolved;
8001 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008002 // If we had a method, or if we can find one with another lookup type,
8003 // it's an incompatible-class-change error.
8004 if (resolved == nullptr) {
8005 if (klass->IsInterface()) {
8006 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, pointer_size);
8007 } else {
8008 // If there was an interface method with the same signature,
8009 // we would have found it also in the "copied" methods.
8010 DCHECK(klass->FindInterfaceMethod(dex_cache.Get(), method_idx, pointer_size) == nullptr);
8011 }
8012 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008013 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008014 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008015 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008016 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008017 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8018 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008019 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008020 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008021 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008022 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008023 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008024}
8025
Vladimir Marko89011192017-12-11 13:45:05 +00008026ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008027 Handle<mirror::DexCache> dex_cache,
8028 Handle<mirror::ClassLoader> class_loader) {
8029 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008030 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008031 if (resolved != nullptr) {
8032 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008033 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8034 return resolved;
8035 }
8036 // Fail, get the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008037 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
8038 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008039 if (klass == nullptr) {
8040 Thread::Current()->AssertPendingException();
8041 return nullptr;
8042 }
8043 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008044 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8045 } else {
8046 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008047 }
8048
8049 return resolved;
8050}
8051
Vladimir Markof44d36c2017-03-14 14:18:46 +00008052ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8053 ObjPtr<mirror::DexCache> dex_cache,
8054 ObjPtr<mirror::ClassLoader> class_loader,
8055 bool is_static) {
8056 const DexFile& dex_file = *dex_cache->GetDexFile();
8057 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8058 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8059 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008060 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008061 }
8062 if (klass == nullptr) {
8063 // The class has not been resolved yet, so the field is also unresolved.
8064 return nullptr;
8065 }
8066 DCHECK(klass->IsResolved());
8067 Thread* self = is_static ? Thread::Current() : nullptr;
8068
8069 // First try to find a field declared directly by `klass` by the field index.
8070 ArtField* resolved_field = is_static
8071 ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8072 : klass->FindInstanceField(dex_cache, field_idx);
8073
8074 if (resolved_field == nullptr) {
8075 // If not found in `klass` by field index, search the class hierarchy using the name and type.
8076 const char* name = dex_file.GetFieldName(field_id);
8077 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8078 resolved_field = is_static
8079 ? mirror::Class::FindStaticField(self, klass, name, type)
8080 : klass->FindInstanceField(name, type);
8081 }
8082
8083 if (resolved_field != nullptr) {
8084 dex_cache->SetResolvedField(field_idx, resolved_field, image_pointer_size_);
8085 }
8086 return resolved_field;
8087}
8088
Vladimir Markoe11dd502017-12-08 14:09:45 +00008089ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008090 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008091 Handle<mirror::ClassLoader> class_loader,
8092 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008093 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008094 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008095 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008096 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008097 return resolved;
8098 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008099 const DexFile& dex_file = *dex_cache->GetDexFile();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008100 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07008101 Thread* const self = Thread::Current();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008102 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008103 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008104 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008105 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008106 }
8107
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008108 if (is_static) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008109 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008110 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07008111 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008112 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008113
Andreas Gampe58a5af82014-07-31 16:23:49 -07008114 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008115 const char* name = dex_file.GetFieldName(field_id);
8116 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8117 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07008118 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008119 } else {
8120 resolved = klass->FindInstanceField(name, type);
8121 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07008122 if (resolved == nullptr) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008123 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008124 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008125 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008126 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07008127 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08008128 return resolved;
8129}
8130
Vladimir Markoe11dd502017-12-08 14:09:45 +00008131ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008132 Handle<mirror::DexCache> dex_cache,
8133 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008134 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008135 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008136 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008137 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008138 return resolved;
8139 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008140 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersb067ac22011-12-13 18:05:09 -08008141 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07008142 Thread* self = Thread::Current();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008143 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008144 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008145 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008146 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008147 }
8148
Vladimir Markof44d36c2017-03-14 14:18:46 +00008149 StringPiece name(dex_file.GetFieldName(field_id));
8150 StringPiece type(dex_file.GetFieldTypeDescriptor(field_id));
Mathieu Chartierf8322842014-05-16 10:59:25 -07008151 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008152 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008153 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08008154 } else {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008155 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008156 }
8157 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008158}
8159
Vladimir Markoaf940202017-12-08 15:01:18 +00008160ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8161 Thread* self,
8162 uint32_t proto_idx,
8163 Handle<mirror::DexCache> dex_cache,
8164 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008165 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008166 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008167
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008168 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008169 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008170 return resolved.Ptr();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008171 }
8172
Narayan Kamath25352fc2016-08-03 12:46:58 +01008173 StackHandleScope<4> hs(self);
8174
8175 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008176 const DexFile& dex_file = *dex_cache->GetDexFile();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008177 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
8178 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008179 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008180 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008181 DCHECK(self->IsExceptionPending());
8182 return nullptr;
8183 }
8184
8185 // Then resolve the argument types.
8186 //
8187 // TODO: Is there a better way to figure out the number of method arguments
8188 // other than by looking at the shorty ?
8189 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8190
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008191 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008192 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008193 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8194 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008195 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008196 DCHECK(self->IsExceptionPending());
8197 return nullptr;
8198 }
8199
8200 DexFileParameterIterator it(dex_file, proto_id);
8201 int32_t i = 0;
8202 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8203 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008204 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008205 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008206 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008207 DCHECK(self->IsExceptionPending());
8208 return nullptr;
8209 }
8210
8211 method_params->Set(i++, param_class.Get());
8212 }
8213
8214 DCHECK(!it.HasNext());
8215
8216 Handle<mirror::MethodType> type = hs.NewHandle(
8217 mirror::MethodType::Create(self, return_type, method_params));
8218 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8219
8220 return type.Get();
8221}
8222
Vladimir Markoaf940202017-12-08 15:01:18 +00008223ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
8224 uint32_t proto_idx,
8225 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008226 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008227 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8228 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008229 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008230}
8231
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008232mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8233 Thread* self,
8234 const DexFile::MethodHandleItem& method_handle,
8235 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008236 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008237 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8238 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008239 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008240 bool is_static;
8241 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008242 switch (handle_type) {
8243 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008244 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008245 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008246 is_static = true;
8247 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008248 break;
8249 }
8250 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008251 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008252 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008253 is_static = true;
8254 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008255 break;
8256 }
8257 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008258 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008259 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008260 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008261 num_params = 2;
8262 break;
8263 }
8264 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008265 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008266 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008267 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008268 num_params = 1;
8269 break;
8270 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008271 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008272 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008273 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008274 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008275 case DexFile::MethodHandleType::kInvokeInterface:
8276 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008277 }
8278
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008279 ArtField* target_field =
8280 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8281 if (LIKELY(target_field != nullptr)) {
8282 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8283 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8284 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8285 ThrowIllegalAccessErrorField(referring_class, target_field);
8286 return nullptr;
8287 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008288 if (UNLIKELY(is_put && target_field->IsFinal())) {
8289 ThrowIllegalAccessErrorField(referring_class, target_field);
8290 return nullptr;
8291 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008292 } else {
8293 DCHECK(Thread::Current()->IsExceptionPending());
8294 return nullptr;
8295 }
8296
8297 StackHandleScope<4> hs(self);
Orion Hodsonc069a302017-01-18 09:23:12 +00008298 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8299 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8300 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8301 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008302 if (UNLIKELY(method_params.Get() == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008303 DCHECK(self->IsExceptionPending());
8304 return nullptr;
8305 }
8306
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008307 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008308 Handle<mirror::Class> return_type;
8309 switch (handle_type) {
8310 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008311 method_params->Set(0, target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008312 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8313 break;
8314 }
8315 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008316 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008317 break;
8318 }
8319 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008320 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008321 method_params->Set(1, target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008322 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8323 break;
8324 }
8325 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008326 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008327 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008328 break;
8329 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008330 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008331 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008332 case DexFile::MethodHandleType::kInvokeConstructor:
8333 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008334 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008335 UNREACHABLE();
8336 }
8337
8338 for (int32_t i = 0; i < num_params; ++i) {
8339 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8340 DCHECK(self->IsExceptionPending());
8341 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008342 }
8343 }
8344
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008345 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008346 DCHECK(self->IsExceptionPending());
8347 return nullptr;
8348 }
8349
8350 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008351 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8352 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008353 DCHECK(self->IsExceptionPending());
8354 return nullptr;
8355 }
Orion Hodson631827d2017-04-10 14:53:47 +01008356
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008357 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8358 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8359}
8360
8361mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8362 Thread* self,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008363 const DexFile::MethodHandleItem& method_handle,
8364 ArtMethod* referrer) {
8365 DexFile::MethodHandleType handle_type =
8366 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8367 mirror::MethodHandle::Kind kind;
8368 uint32_t receiver_count = 0;
8369 ArtMethod* target_method = nullptr;
8370 switch (handle_type) {
8371 case DexFile::MethodHandleType::kStaticPut:
8372 case DexFile::MethodHandleType::kStaticGet:
8373 case DexFile::MethodHandleType::kInstancePut:
8374 case DexFile::MethodHandleType::kInstanceGet:
8375 UNREACHABLE();
8376 case DexFile::MethodHandleType::kInvokeStatic: {
8377 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8378 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008379 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8380 method_handle.field_or_method_idx_,
8381 referrer,
8382 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008383 break;
8384 }
8385 case DexFile::MethodHandleType::kInvokeInstance: {
8386 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8387 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008388 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8389 method_handle.field_or_method_idx_,
8390 referrer,
8391 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008392 break;
8393 }
8394 case DexFile::MethodHandleType::kInvokeConstructor: {
8395 // Constructors are currently implemented as a transform. They
8396 // are special cased later in this method.
8397 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8398 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008399 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8400 method_handle.field_or_method_idx_,
8401 referrer,
8402 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008403 break;
8404 }
8405 case DexFile::MethodHandleType::kInvokeDirect: {
8406 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8407 receiver_count = 1;
8408 StackHandleScope<2> hs(self);
8409 // A constant method handle with type kInvokeDirect can refer to
8410 // a method that is private or to a method in a super class. To
8411 // disambiguate the two options, we resolve the method ignoring
8412 // the invocation type to determine if the method is private. We
8413 // then resolve again specifying the intended invocation type to
8414 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00008415 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008416 hs.NewHandle(referrer->GetDexCache()),
8417 hs.NewHandle(referrer->GetClassLoader()));
8418 if (UNLIKELY(target_method == nullptr)) {
8419 break;
8420 }
8421
8422 if (target_method->IsPrivate()) {
8423 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01008424 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8425 method_handle.field_or_method_idx_,
8426 referrer,
8427 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008428 } else {
8429 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01008430 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8431 method_handle.field_or_method_idx_,
8432 referrer,
8433 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008434 if (UNLIKELY(target_method == nullptr)) {
8435 break;
8436 }
8437 // Find the method specified in the parent in referring class
8438 // so invoke-super invokes the method in the parent of the
8439 // referrer.
8440 target_method =
8441 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
8442 kRuntimePointerSize);
8443 }
8444 break;
8445 }
8446 case DexFile::MethodHandleType::kInvokeInterface: {
8447 kind = mirror::MethodHandle::Kind::kInvokeInterface;
8448 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008449 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8450 method_handle.field_or_method_idx_,
8451 referrer,
8452 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008453 break;
8454 }
Orion Hodson631827d2017-04-10 14:53:47 +01008455 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008456
8457 if (UNLIKELY(target_method == nullptr)) {
8458 DCHECK(Thread::Current()->IsExceptionPending());
8459 return nullptr;
8460 }
8461
8462 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
8463 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8464 uint32_t access_flags = target_method->GetAccessFlags();
8465 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
8466 ThrowIllegalAccessErrorMethod(referring_class, target_method);
8467 return nullptr;
8468 }
8469
8470 // Calculate the number of parameters from the method shorty. We add the
8471 // receiver count (0 or 1) and deduct one for the return value.
8472 uint32_t shorty_length;
8473 target_method->GetShorty(&shorty_length);
8474 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
8475
8476 StackHandleScope<7> hs(self);
8477 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8478 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8479 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8480 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
8481 if (method_params.Get() == nullptr) {
8482 DCHECK(self->IsExceptionPending());
8483 return nullptr;
8484 }
8485
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008486 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008487 if (receiver_count != 0) {
8488 // Insert receiver
8489 method_params->Set(index++, target_method->GetDeclaringClass());
8490 }
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008491 DexFileParameterIterator it(*target_method->GetDexFile(), target_method->GetPrototype());
8492 Handle<mirror::DexCache> target_method_dex_cache(hs.NewHandle(target_method->GetDexCache()));
8493 Handle<mirror::ClassLoader> target_method_class_loader(hs.NewHandle(target_method->GetClassLoader()));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008494 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008495 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008496 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008497 ObjPtr<mirror::Class> klass = ResolveType(type_idx,
8498 target_method_dex_cache,
8499 target_method_class_loader);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008500 if (nullptr == klass) {
8501 DCHECK(self->IsExceptionPending());
8502 return nullptr;
8503 }
8504 method_params->Set(index++, klass);
8505 it.Next();
8506 }
8507
Vladimir Markob45528c2017-07-27 14:14:28 +01008508 Handle<mirror::Class> return_type = hs.NewHandle(target_method->ResolveReturnType());
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008509 if (UNLIKELY(return_type.IsNull())) {
8510 DCHECK(self->IsExceptionPending());
8511 return nullptr;
8512 }
8513
8514 Handle<mirror::MethodType>
8515 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8516 if (UNLIKELY(method_type.IsNull())) {
8517 DCHECK(self->IsExceptionPending());
8518 return nullptr;
8519 }
8520
8521 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
8522 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
8523 Handle<mirror::MethodHandlesLookup> lookup =
8524 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
8525 return lookup->FindConstructor(self, constructor_class, method_type);
8526 }
8527
8528 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
8529 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8530}
8531
Vladimir Markoaf940202017-12-08 15:01:18 +00008532ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
8533 uint32_t method_handle_idx,
8534 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008535 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008536 const DexFile* const dex_file = referrer->GetDexFile();
8537 const DexFile::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
8538 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
8539 case DexFile::MethodHandleType::kStaticPut:
8540 case DexFile::MethodHandleType::kStaticGet:
8541 case DexFile::MethodHandleType::kInstancePut:
8542 case DexFile::MethodHandleType::kInstanceGet:
8543 return ResolveMethodHandleForField(self, method_handle, referrer);
8544 case DexFile::MethodHandleType::kInvokeStatic:
8545 case DexFile::MethodHandleType::kInvokeInstance:
8546 case DexFile::MethodHandleType::kInvokeConstructor:
8547 case DexFile::MethodHandleType::kInvokeDirect:
8548 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00008549 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008550 }
Orion Hodsonc069a302017-01-18 09:23:12 +00008551}
8552
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008553bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
8554 return (entry_point == GetQuickResolutionStub()) ||
8555 (quick_resolution_trampoline_ == entry_point);
8556}
8557
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008558bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
8559 return (entry_point == GetQuickToInterpreterBridge()) ||
8560 (quick_to_interpreter_bridge_trampoline_ == entry_point);
8561}
8562
8563bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
8564 return (entry_point == GetQuickGenericJniStub()) ||
8565 (quick_generic_jni_trampoline_ == entry_point);
8566}
8567
David Sehra49e0532017-08-25 08:05:29 -07008568bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
8569 return entry_point == GetJniDlsymLookupStub();
8570}
8571
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008572const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
8573 return GetQuickGenericJniStub();
8574}
8575
Mathieu Chartiere401d142015-04-22 13:56:20 -07008576void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008577 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008578 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
8579 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02008580 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008581 }
8582}
8583
Alex Lightdb01a092017-04-03 15:39:55 -07008584void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
8585 DCHECK(method->IsObsolete());
8586 // We cannot mess with the entrypoints of native methods because they are used to determine how
8587 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
8588 if (!method->IsNative()) {
8589 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
8590 }
8591}
8592
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008593void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07008594 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07008595 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008596 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
8597 << NumNonZygoteClasses() << "\n";
8598}
8599
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008600class CountClassesVisitor : public ClassLoaderVisitor {
8601 public:
8602 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
8603
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008604 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07008605 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008606 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07008607 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00008608 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
8609 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07008610 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008611 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008612
8613 size_t num_zygote_classes;
8614 size_t num_non_zygote_classes;
8615};
8616
8617size_t ClassLinker::NumZygoteClasses() const {
8618 CountClassesVisitor visitor;
8619 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008620 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008621}
8622
8623size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008624 CountClassesVisitor visitor;
8625 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008626 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07008627}
8628
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008629size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07008630 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08008631 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008632 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07008633}
8634
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008635pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07008636 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008637}
8638
8639pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08008640 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07008641}
8642
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008643void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008644 DCHECK(!init_done_);
8645
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008646 DCHECK(klass != nullptr);
8647 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008648
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07008649 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008650 DCHECK(class_roots != nullptr);
8651 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07008652 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008653}
8654
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008655const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
8656 static const char* class_roots_descriptors[] = {
8657 "Ljava/lang/Class;",
8658 "Ljava/lang/Object;",
8659 "[Ljava/lang/Class;",
8660 "[Ljava/lang/Object;",
8661 "Ljava/lang/String;",
8662 "Ljava/lang/DexCache;",
8663 "Ljava/lang/ref/Reference;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008664 "Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008665 "Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008666 "Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008667 "Ljava/lang/reflect/Proxy;",
8668 "[Ljava/lang/String;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008669 "[Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008670 "[Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008671 "[Ljava/lang/reflect/Method;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008672 "Ljava/lang/invoke/CallSite;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008673 "Ljava/lang/invoke/MethodHandleImpl;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008674 "Ljava/lang/invoke/MethodHandles$Lookup;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008675 "Ljava/lang/invoke/MethodType;",
Orion Hodson005ac512017-10-24 15:43:43 +01008676 "Ljava/lang/invoke/VarHandle;",
8677 "Ljava/lang/invoke/FieldVarHandle;",
8678 "Ljava/lang/invoke/ArrayElementVarHandle;",
8679 "Ljava/lang/invoke/ByteArrayViewVarHandle;",
8680 "Ljava/lang/invoke/ByteBufferViewVarHandle;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008681 "Ljava/lang/ClassLoader;",
8682 "Ljava/lang/Throwable;",
8683 "Ljava/lang/ClassNotFoundException;",
8684 "Ljava/lang/StackTraceElement;",
Narayan Kamath000e1882016-10-24 17:14:25 +01008685 "Ldalvik/system/EmulatedStackFrame;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008686 "Z",
8687 "B",
8688 "C",
8689 "D",
8690 "F",
8691 "I",
8692 "J",
8693 "S",
8694 "V",
8695 "[Z",
8696 "[B",
8697 "[C",
8698 "[D",
8699 "[F",
8700 "[I",
8701 "[J",
8702 "[S",
8703 "[Ljava/lang/StackTraceElement;",
Alex Lightd6251582016-10-31 11:12:30 -07008704 "Ldalvik/system/ClassExt;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008705 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08008706 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
8707 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008708
8709 const char* descriptor = class_roots_descriptors[class_root];
8710 CHECK(descriptor != nullptr);
8711 return descriptor;
8712}
8713
Calin Juravle7865ac72017-06-28 11:03:12 -07008714jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
Andreas Gampe473191c2017-12-28 16:55:31 -08008715 const std::vector<const DexFile*>& dex_files,
8716 jclass loader_class,
8717 jobject parent_loader) {
Calin Juravle7865ac72017-06-28 11:03:12 -07008718 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
8719 WellKnownClasses::dalvik_system_PathClassLoader) ||
8720 self->GetJniEnv()->IsSameObject(loader_class,
8721 WellKnownClasses::dalvik_system_DelegateLastClassLoader));
8722
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008723 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
8724 // We could move the jobject to the callers, but all call-sites do this...
8725 ScopedObjectAccessUnchecked soa(self);
8726
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008727 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Vladimir Marko19a4d372016-12-08 14:41:46 +00008728 StackHandleScope<6> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008729
Mathieu Chartierc7853442015-03-27 14:35:38 -07008730 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008731 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008732
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008733 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008734 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008735 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008736 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07008737 mirror::ObjectArray<mirror::Object>::Alloc(self,
8738 dex_elements_class.Get(),
8739 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008740 Handle<mirror::Class> h_dex_element_class =
8741 hs.NewHandle(dex_elements_class->GetComponentType());
8742
Mathieu Chartierc7853442015-03-27 14:35:38 -07008743 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008744 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008745 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008746
Andreas Gampe08883de2016-11-08 13:20:52 -08008747 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00008748 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008749
Andreas Gampe08883de2016-11-08 13:20:52 -08008750 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00008751 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008752
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008753 // Fill the elements array.
8754 int32_t index = 0;
8755 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008756 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008757
Calin Juravle7865ac72017-06-28 11:03:12 -07008758 // CreateWellKnownClassLoader is only used by gtests and compiler.
8759 // 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 -07008760 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
8761 self,
8762 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008763 DCHECK(h_long_array != nullptr);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008764 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008765
Mathieu Chartier3738e982017-05-12 16:07:28 -07008766 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
8767 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008768 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008769 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008770 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008771 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008772
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008773 Handle<mirror::String> h_file_name = hs2.NewHandle(
8774 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008775 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008776 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
8777
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008778 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008779 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008780 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008781
8782 h_dex_elements->Set(index, h_element.Get());
8783 index++;
8784 }
8785 DCHECK_EQ(index, h_dex_elements->GetLength());
8786
8787 // Create DexPathList.
8788 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008789 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008790 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008791 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008792 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08008793 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
8794 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
8795 // elements.
8796 {
8797 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
8798 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
8799 DCHECK(native_lib_dirs != nullptr);
8800 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
8801 DCHECK(list_class != nullptr);
8802 {
8803 StackHandleScope<1> h_list_scope(self);
8804 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
8805 bool list_init = EnsureInitialized(self, h_list_class, true, true);
8806 DCHECK(list_init);
8807 list_class = h_list_class.Get();
8808 }
8809 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
8810 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
8811 // is fine for testing. While it violates a Java-code invariant (the elementData field is
8812 // normally never null), as long as one does not try to add elements, this will still
8813 // work.
8814 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
8815 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008816
Calin Juravle7865ac72017-06-28 11:03:12 -07008817 // Create the class loader..
8818 Handle<mirror::Class> h_loader_class = hs.NewHandle(soa.Decode<mirror::Class>(loader_class));
8819 Handle<mirror::Object> h_class_loader = hs.NewHandle(h_loader_class->AllocObject(self));
8820 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008821 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008822 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008823 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008824 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008825 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008826
8827 // Make a pretend boot-classpath.
8828 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07008829 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00008830 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07008831 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00008832 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07008833 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01008834 DCHECK(parent_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07008835
8836 ObjPtr<mirror::Object> parent = (parent_loader != nullptr)
8837 ? soa.Decode<mirror::ClassLoader>(parent_loader)
8838 : soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
8839 parent_field->SetObject<false>(h_class_loader.Get(), parent);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008840
8841 // Make it a global ref and return.
8842 ScopedLocalRef<jobject> local_ref(
Calin Juravle7865ac72017-06-28 11:03:12 -07008843 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_class_loader.Get()));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008844 return soa.Env()->NewGlobalRef(local_ref.get());
8845}
8846
Calin Juravle7865ac72017-06-28 11:03:12 -07008847jobject ClassLinker::CreatePathClassLoader(Thread* self,
8848 const std::vector<const DexFile*>& dex_files) {
8849 return CreateWellKnownClassLoader(self,
8850 dex_files,
8851 WellKnownClasses::dalvik_system_PathClassLoader,
8852 nullptr);
8853}
8854
Andreas Gampe8ac75952015-06-02 21:01:45 -07008855void ClassLinker::DropFindArrayClassCache() {
8856 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
8857 find_array_class_cache_next_victim_ = 0;
8858}
8859
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008860void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008861 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008862 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07008863 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008864 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
8865 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008866 if (class_loader != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008867 visitor->Visit(class_loader.Ptr());
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008868 }
8869 }
8870}
8871
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008872void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
8873 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008874 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07008875 Thread* const self = Thread::Current();
8876 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008877 ClassTable* const table = ClassTableForClassLoader(class_loader.Ptr());
Mathieu Chartier00310e02015-10-17 12:46:42 -07008878 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07008879 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008880 // It was not already inserted, perform the write barrier to let the GC know the class loader's
8881 // class table was modified.
8882 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
8883 }
8884}
8885
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008886void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008887 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07008888 std::vector<ClassLoaderData> to_delete;
8889 // Do the delete outside the lock to avoid lock violation in jit code cache.
8890 {
8891 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8892 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
8893 const ClassLoaderData& data = *it;
8894 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008895 ObjPtr<mirror::ClassLoader> class_loader =
8896 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07008897 if (class_loader != nullptr) {
8898 ++it;
8899 } else {
8900 VLOG(class_linker) << "Freeing class loader";
8901 to_delete.push_back(data);
8902 it = class_loaders_.erase(it);
8903 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008904 }
8905 }
Mathieu Chartier65975772016-08-05 10:46:36 -07008906 for (ClassLoaderData& data : to_delete) {
8907 DeleteClassLoader(self, data);
8908 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008909}
8910
Vladimir Marko21300532017-01-24 18:06:55 +00008911class GetResolvedClassesVisitor : public ClassVisitor {
8912 public:
8913 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
8914 : result_(result),
8915 ignore_boot_classes_(ignore_boot_classes),
8916 last_resolved_classes_(result->end()),
8917 last_dex_file_(nullptr),
8918 vlog_is_on_(VLOG_IS_ON(class_linker)),
8919 extra_stats_(),
8920 last_extra_stats_(extra_stats_.end()) { }
8921
8922 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
8923 if (!klass->IsProxyClass() &&
8924 !klass->IsArrayClass() &&
8925 klass->IsResolved() &&
8926 !klass->IsErroneousResolved() &&
8927 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
8928 const DexFile& dex_file = klass->GetDexFile();
8929 if (&dex_file != last_dex_file_) {
8930 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07008931 DexCacheResolvedClasses resolved_classes(
8932 dex_file.GetLocation(),
8933 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
8934 dex_file.GetLocationChecksum(),
8935 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00008936 last_resolved_classes_ = result_->find(resolved_classes);
8937 if (last_resolved_classes_ == result_->end()) {
8938 last_resolved_classes_ = result_->insert(resolved_classes).first;
8939 }
8940 }
8941 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
8942 if (UNLIKELY(vlog_is_on_) && added) {
8943 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
8944 if (last_extra_stats_ == extra_stats_.end() ||
8945 last_extra_stats_->first != resolved_classes) {
8946 last_extra_stats_ = extra_stats_.find(resolved_classes);
8947 if (last_extra_stats_ == extra_stats_.end()) {
8948 last_extra_stats_ =
8949 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
8950 }
8951 }
8952 }
8953 }
8954 return true;
8955 }
8956
8957 void PrintStatistics() const {
8958 if (vlog_is_on_) {
8959 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
8960 auto it = extra_stats_.find(std::addressof(resolved_classes));
8961 DCHECK(it != extra_stats_.end());
8962 const ExtraStats& extra_stats = it->second;
8963 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
8964 << " has " << resolved_classes.GetClasses().size() << " / "
8965 << extra_stats.number_of_class_defs_ << " resolved classes";
8966 }
8967 }
8968 }
8969
8970 private:
8971 struct ExtraStats {
8972 explicit ExtraStats(uint32_t number_of_class_defs)
8973 : number_of_class_defs_(number_of_class_defs) {}
8974 uint32_t number_of_class_defs_;
8975 };
8976
8977 std::set<DexCacheResolvedClasses>* result_;
8978 bool ignore_boot_classes_;
8979 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
8980 const DexFile* last_dex_file_;
8981
8982 // Statistics.
8983 bool vlog_is_on_;
8984 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
8985 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
8986};
8987
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008988std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08008989 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008990 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07008991 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008992 std::set<DexCacheResolvedClasses> ret;
8993 VLOG(class_linker) << "Collecting resolved classes";
8994 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00008995 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
8996 VisitClasses(&visitor);
8997 if (VLOG_IS_ON(class_linker)) {
8998 visitor.PrintStatistics();
8999 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009000 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009001 return ret;
9002}
9003
Mathieu Chartier65975772016-08-05 10:46:36 -07009004class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9005 public:
9006 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9007 : method_(method),
9008 pointer_size_(pointer_size) {}
9009
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009010 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier65975772016-08-05 10:46:36 -07009011 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9012 holder_ = klass;
9013 }
9014 // Return false to stop searching if holder_ is not null.
9015 return holder_ == nullptr;
9016 }
9017
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009018 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009019 const ArtMethod* const method_;
9020 const PointerSize pointer_size_;
9021};
9022
9023mirror::Class* ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
9024 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9025 CHECK(method->IsCopied());
9026 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9027 VisitClasses(&visitor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009028 return visitor.holder_.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07009029}
9030
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009031mirror::IfTable* ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9032 return down_cast<mirror::IfTable*>(
9033 mirror::IfTable::Alloc(self,
9034 GetClassRoot(kObjectArrayClass),
9035 ifcount * mirror::IfTable::kMax));
9036}
9037
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009038// Instantiate ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009039template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009040 uint32_t method_idx,
9041 Handle<mirror::DexCache> dex_cache,
9042 Handle<mirror::ClassLoader> class_loader,
9043 ArtMethod* referrer,
9044 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009045template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009046 uint32_t method_idx,
9047 Handle<mirror::DexCache> dex_cache,
9048 Handle<mirror::ClassLoader> class_loader,
9049 ArtMethod* referrer,
9050 InvokeType type);
9051
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009052} // namespace art