blob: cffdfd34101f5255bfc174be5c12ed0fb5c85507 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Alex Lighteb7c1442015-08-31 13:17:42 -070019#include <algorithm>
Brian Carlstromdbc05252011-09-09 01:59:59 -070020#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070021#include <iostream>
Vladimir Marko21300532017-01-24 18:06:55 +000022#include <map>
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070024#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070025#include <string>
Alex Lighteb7c1442015-08-31 13:17:42 -070026#include <tuple>
Andreas Gampea696c0a2014-12-10 20:51:45 -080027#include <unistd.h>
Alex Lighteb7c1442015-08-31 13:17:42 -070028#include <unordered_map>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070029#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070030#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070031
Andreas Gampe46ee31b2016-12-14 10:11:49 -080032#include "android-base/stringprintf.h"
33
Mathieu Chartierc7853442015-03-27 14:35:38 -070034#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070035#include "art_method-inl.h"
36#include "base/arena_allocator.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080037#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080038#include "base/logging.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070039#include "base/scoped_arena_containers.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010040#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080041#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080042#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010043#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080044#include "base/unix_file/fd_file.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070045#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070046#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080047#include "class_linker-inl.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070048#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000049#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080050#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070051#include "dex_file-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070052#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070053#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070054#include "experimental_flags.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070055#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070056#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080057#include "gc/accounting/heap_bitmap-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070058#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070059#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070060#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000061#include "gc/space/space-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070062#include "handle_scope-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080063#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070064#include "imt_conflict_table.h"
65#include "imtable-inl.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070066#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070067#include "interpreter/interpreter.h"
Andreas Gampec15a2f42017-04-21 12:09:39 -070068#include "java_vm_ext.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080069#include "jit/jit.h"
70#include "jit/jit_code_cache.h"
Calin Juravle33083d62017-01-18 15:29:12 -080071#include "jit/profile_compilation_info.h"
Andreas Gampe08883de2016-11-08 13:20:52 -080072#include "jni_internal.h"
Ian Rogers0571d352011-11-03 19:51:38 -070073#include "leb128.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070074#include "linear_alloc.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000075#include "mirror/call_site.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080076#include "mirror/class.h"
77#include "mirror/class-inl.h"
Alex Lightd6251582016-10-31 11:12:30 -070078#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080079#include "mirror/class_loader.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070080#include "mirror/dex_cache.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070081#include "mirror/dex_cache-inl.h"
Narayan Kamath000e1882016-10-24 17:14:25 +010082#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070083#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080084#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070085#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +010086#include "mirror/method_type.h"
87#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000088#include "mirror/method_handles_lookup.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080089#include "mirror/object-inl.h"
90#include "mirror/object_array-inl.h"
91#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070092#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080093#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070094#include "mirror/string-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070095#include "native/dalvik_system_DexFile.h"
96#include "oat.h"
97#include "oat_file.h"
98#include "oat_file-inl.h"
99#include "oat_file_assistant.h"
100#include "oat_file_manager.h"
101#include "object_lock.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800102#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700103#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800104#include "runtime_callbacks.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700105#include "ScopedLocalRef.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700106#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700107#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700108#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700109#include "trace.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700110#include "utils.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100111#include "utils/dex_cache_arrays_layout-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800112#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700113#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700114
115namespace art {
116
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800117using android::base::StringPrintf;
118
Mathieu Chartierc7853442015-03-27 14:35:38 -0700119static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700120static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700121
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700122static void ThrowNoClassDefFoundError(const char* fmt, ...)
123 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700124 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700125static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700126 va_list args;
127 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800128 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000129 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800130 va_end(args);
131}
132
Andreas Gampe99babb62015-11-02 16:20:00 -0800133static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700134 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700135 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700136 StackHandleScope<1> hs(self);
137 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700138 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700139 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700140
141 if (exception_class == nullptr) {
142 // No exc class ~ no <init>-with-string.
143 CHECK(self->IsExceptionPending());
144 self->ClearException();
145 return false;
146 }
147
Mathieu Chartiere401d142015-04-22 13:56:20 -0700148 ArtMethod* exception_init_method = exception_class->FindDeclaredDirectMethod(
Andreas Gampe99babb62015-11-02 16:20:00 -0800149 "<init>", "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700150 return exception_init_method != nullptr;
151}
152
Alex Lightd6251582016-10-31 11:12:30 -0700153static mirror::Object* GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700154 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700155 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
156 if (ext == nullptr) {
157 return nullptr;
158 } else {
159 return ext->GetVerifyError();
160 }
161}
162
163// Helper for ThrowEarlierClassFailure. Throws the stored error.
164static void HandleEarlierVerifyError(Thread* self,
165 ClassLinker* class_linker,
166 ObjPtr<mirror::Class> c)
167 REQUIRES_SHARED(Locks::mutator_lock_) {
168 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800169 DCHECK(obj != nullptr);
170 self->AssertNoPendingException();
171 if (obj->IsClass()) {
172 // Previous error has been stored as class. Create a new exception of that type.
173
174 // It's possible the exception doesn't have a <init>(String).
175 std::string temp;
176 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
177
178 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700179 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800180 } else {
181 self->ThrowNewException(descriptor, nullptr);
182 }
183 } else {
184 // Previous error has been stored as an instance. Just rethrow.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700185 ObjPtr<mirror::Class> throwable_class =
Andreas Gampe99babb62015-11-02 16:20:00 -0800186 self->DecodeJObject(WellKnownClasses::java_lang_Throwable)->AsClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700187 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800188 CHECK(throwable_class->IsAssignableFrom(error_class));
189 self->SetException(obj->AsThrowable());
190 }
191 self->AssertPendingException();
192}
193
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700194void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c, bool wrap_in_no_class_def) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700195 // The class failed to initialize on a previous attempt, so we want to throw
196 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
197 // failed in verification, in which case v2 5.4.1 says we need to re-throw
198 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800199 Runtime* const runtime = Runtime::Current();
200 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700201 std::string extra;
Alex Lightd6251582016-10-31 11:12:30 -0700202 if (GetVerifyError(c) != nullptr) {
203 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
Andreas Gampe369c8512016-01-28 15:31:39 -0800204 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700205 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800206 } else {
207 extra = verify_error->AsThrowable()->Dump();
208 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700209 }
David Sehr709b0702016-10-13 09:12:37 -0700210 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
211 << ": " << extra;
Ian Rogers87e552d2012-08-31 15:54:48 -0700212 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700213
David Sehr709b0702016-10-13 09:12:37 -0700214 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800215 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800216 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700217 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700218 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000219 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700220 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700221 if (GetVerifyError(c) != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800222 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800223 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800224 }
Alex Lightd6251582016-10-31 11:12:30 -0700225 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
226 // might have meant to go down the earlier if statement with the original error but it got
227 // swallowed by the OOM so we end up here.
228 if (GetVerifyError(c) == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800229 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
230 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
231 // exception will be a cause.
232 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700233 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700234 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700235 }
236}
237
Brian Carlstromb23eab12014-10-08 17:55:21 -0700238static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700239 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700240 if (VLOG_IS_ON(class_linker)) {
241 std::string temp;
242 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000243 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700244 }
245}
246
247static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700248 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700249 Thread* self = Thread::Current();
250 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700251
252 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700253 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700254
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800255 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
256 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
257 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800258 std::string tmp;
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800259 LOG(kIsDebugBuild ? FATAL : WARNING) << klass->GetDescriptor(&tmp) << " failed initialization";
Andreas Gampe22f71d22016-11-21 10:10:08 -0800260 }
261
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700262 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700263 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
264 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700265
Elliott Hughesa4f94742012-05-29 16:28:38 -0700266 // We only wrap non-Error exceptions; an Error can just be used as-is.
267 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000268 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700269 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700270 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700271}
272
Fred Shih381e4ca2014-08-25 17:24:27 -0700273// Gap between two fields in object layout.
274struct FieldGap {
275 uint32_t start_offset; // The offset from the start of the object.
276 uint32_t size; // The gap size of 1, 2, or 4 bytes.
277};
278struct FieldGapsComparator {
279 explicit FieldGapsComparator() {
280 }
281 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
282 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800283 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700284 // Note that the priority queue returns the largest element, so operator()
285 // should return true if lhs is less than rhs.
286 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700287 }
288};
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700289typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
Fred Shih381e4ca2014-08-25 17:24:27 -0700290
291// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800292static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700293 DCHECK(gaps != nullptr);
294
295 uint32_t current_offset = gap_start;
296 while (current_offset != gap_end) {
297 size_t remaining = gap_end - current_offset;
298 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
299 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
300 current_offset += sizeof(uint32_t);
301 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
302 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
303 current_offset += sizeof(uint16_t);
304 } else {
305 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
306 current_offset += sizeof(uint8_t);
307 }
308 DCHECK_LE(current_offset, gap_end) << "Overran gap";
309 }
310}
311// Shuffle fields forward, making use of gaps whenever possible.
312template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000313static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700314 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700315 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700316 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700317 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700318 DCHECK(current_field_idx != nullptr);
319 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700320 DCHECK(gaps != nullptr);
321 DCHECK(field_offset != nullptr);
322
323 DCHECK(IsPowerOfTwo(n));
324 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700325 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700326 Primitive::Type type = field->GetTypeAsPrimitiveType();
327 if (Primitive::ComponentSize(type) < n) {
328 break;
329 }
330 if (!IsAligned<n>(field_offset->Uint32Value())) {
331 MemberOffset old_offset = *field_offset;
332 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
333 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
334 }
David Sehr709b0702016-10-13 09:12:37 -0700335 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700336 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700337 if (!gaps->empty() && gaps->top().size >= n) {
338 FieldGap gap = gaps->top();
339 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100340 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700341 field->SetOffset(MemberOffset(gap.start_offset));
342 if (gap.size > n) {
343 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
344 }
345 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100346 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700347 field->SetOffset(*field_offset);
348 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
349 }
350 ++(*current_field_idx);
351 }
352}
353
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800354ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampe2af99022017-04-25 08:32:59 -0700355 : boot_class_table_(new ClassTable()),
356 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800357 class_roots_(nullptr),
358 array_iftable_(nullptr),
359 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700360 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000361 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700362 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800363 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800364 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100365 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800366 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampe542451c2016-07-26 09:02:02 -0700367 image_pointer_size_(kRuntimePointerSize) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700368 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700369 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
370 "Array cache size wrong.");
371 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700372}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700373
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800374void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700375 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800376 if (c2 == nullptr) {
377 LOG(FATAL) << "Could not find class " << descriptor;
378 UNREACHABLE();
379 }
380 if (c1.Get() != c2) {
381 std::ostringstream os1, os2;
382 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
383 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
384 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
385 << ". This is most likely the result of a broken build. Make sure that "
386 << "libcore and art projects match.\n\n"
387 << os1.str() << "\n\n" << os2.str();
388 UNREACHABLE();
389 }
390}
391
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800392bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
393 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800394 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700395
Mathieu Chartiere401d142015-04-22 13:56:20 -0700396 Thread* const self = Thread::Current();
397 Runtime* const runtime = Runtime::Current();
398 gc::Heap* const heap = runtime->GetHeap();
399
Jeff Haodcdc85b2015-12-04 14:06:18 -0800400 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700401 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700402
Mathieu Chartiere401d142015-04-22 13:56:20 -0700403 // Use the pointer size from the runtime since we are probably creating the image.
404 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
405
Elliott Hughes30646832011-10-13 16:59:46 -0700406 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700407 // 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 -0800408 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700409 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700410 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700411 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700412 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800413 CHECK(java_lang_Class != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700414 mirror::Class::SetClassClass(java_lang_Class.Get());
415 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700416 if (kUseBakerReadBarrier) {
417 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800418 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700419 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700420 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800421 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700422 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700423
Elliott Hughes418d20f2011-09-22 14:00:39 -0700424 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700425 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700426 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700427 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700428 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700429
Ian Rogers23435d02012-09-24 11:23:12 -0700430 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700431 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700432 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800433 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700434 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700435 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700436 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700437
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700438 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800439 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
440 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
441 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
442 java_lang_Object.Get(),
443 java_lang_Object->GetObjectSize(),
444 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700445
Ian Rogers23435d02012-09-24 11:23:12 -0700446 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700447 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700448 AllocClass(self, java_lang_Class.Get(),
449 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700450 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700451
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700452 // Setup the char (primitive) class to be used for char[].
453 Handle<mirror::Class> char_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700454 AllocClass(self, java_lang_Class.Get(),
455 mirror::Class::PrimitiveClassSize(image_pointer_size_))));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700456 // The primitive char class won't be initialized by
457 // InitializePrimitiveClass until line 459, but strings (and
458 // internal char arrays) will be allocated before that and the
459 // component size, which is computed from the primitive type, needs
460 // to be set here.
461 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700462
Ian Rogers23435d02012-09-24 11:23:12 -0700463 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700464 Handle<mirror::Class> char_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700465 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700466 char_array_class->SetComponentType(char_class.Get());
467 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700468
Ian Rogers23435d02012-09-24 11:23:12 -0700469 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700470 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700471 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700472 java_lang_String->SetStringClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700473 mirror::String::SetClass(java_lang_String.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700474 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400475
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700476 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700477 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700478 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700479 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
480 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700481 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700482
Ian Rogers23435d02012-09-24 11:23:12 -0700483 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700484 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700485 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
486 kClassRootsMax));
487 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700488 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
489 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
490 SetClassRoot(kClassArrayClass, class_array_class.Get());
491 SetClassRoot(kObjectArrayClass, object_array_class.Get());
492 SetClassRoot(kCharArrayClass, char_array_class.Get());
493 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700494 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700495
Mathieu Chartier6beced42016-11-15 15:51:31 -0800496 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
497 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
498
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700499 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700500 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
501 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
502 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
503 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
504 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
505 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
506 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
507 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700508
Ian Rogers23435d02012-09-24 11:23:12 -0700509 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700510 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700511
Ian Rogers23435d02012-09-24 11:23:12 -0700512 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700513 Handle<mirror::Class> int_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700514 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700515 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700516 mirror::IntArray::SetArrayClass(int_array_class.Get());
517 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700518
Mathieu Chartierc7853442015-03-27 14:35:38 -0700519 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
520 Handle<mirror::Class> long_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700521 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700522 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
523 mirror::LongArray::SetArrayClass(long_array_class.Get());
524 SetClassRoot(kLongArrayClass, long_array_class.Get());
525
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700526 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700527
Ian Rogers52813c92012-10-11 11:50:38 -0700528 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700529 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700530 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700531 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100532 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700533 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700534 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700535
Alex Lightd6251582016-10-31 11:12:30 -0700536
537 // Setup dalvik.system.ClassExt
538 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
539 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
540 SetClassRoot(kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
541 mirror::ClassExt::SetClass(dalvik_system_ClassExt.Get());
542 mirror::Class::SetStatus(dalvik_system_ClassExt, mirror::Class::kStatusResolved, self);
543
Mathieu Chartier66f19252012-09-18 08:57:04 -0700544 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700545 Handle<mirror::Class> object_array_string(hs.NewHandle(
546 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700547 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700548 object_array_string->SetComponentType(java_lang_String.Get());
549 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700550
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000551 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700552 // Create runtime resolution and imt conflict methods.
553 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000554 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
555 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700556
Ian Rogers23435d02012-09-24 11:23:12 -0700557 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
558 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
559 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800560 if (boot_class_path.empty()) {
561 *error_msg = "Boot classpath is empty.";
562 return false;
563 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800564 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800565 if (dex_file.get() == nullptr) {
566 *error_msg = "Null dex file.";
567 return false;
568 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700569 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800570 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700571 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700572
573 // now we can use FindSystemClass
574
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700575 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700576 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
577 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700578
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700579 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
580 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700581 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800582 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700583 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700584 quick_resolution_trampoline_ = GetQuickResolutionStub();
585 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
586 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700587 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700588
Alex Lightd6251582016-10-31 11:12:30 -0700589 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700590 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800591 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700592 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700593 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800594 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700595 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800596 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700597 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Alex Lightd6251582016-10-31 11:12:30 -0700598 mirror::Class::SetStatus(dalvik_system_ClassExt, mirror::Class::kStatusNotReady, self);
599 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
600 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700601
Ian Rogers23435d02012-09-24 11:23:12 -0700602 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800603 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800604 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700605
Ian Rogers98379392014-02-24 16:53:16 -0800606 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800607 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700608
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800609 CheckSystemClass(self, char_array_class, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700610
Ian Rogers98379392014-02-24 16:53:16 -0800611 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800612 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700613
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800614 CheckSystemClass(self, int_array_class, "[I");
615 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700616
Ian Rogers98379392014-02-24 16:53:16 -0800617 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800618 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700619
Ian Rogers98379392014-02-24 16:53:16 -0800620 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800621 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700622
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800623 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
624 // in class_table_.
625 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700626
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800627 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
628 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700629
Ian Rogers23435d02012-09-24 11:23:12 -0700630 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700631 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800632 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700633 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800634 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700635 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
636 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700637 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
638 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700639
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700640 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
641 // suspension.
642 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000643 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700644 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000645 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700646 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000647 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700648 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000649 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700650
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700651 CHECK_EQ(object_array_string.Get(),
652 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700653
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800654 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700655
Ian Rogers23435d02012-09-24 11:23:12 -0700656 // Create java.lang.reflect.Proxy root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700657 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700658
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700659 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700660 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
661 CHECK(class_root != nullptr);
662 SetClassRoot(kJavaLangReflectField, class_root);
663 mirror::Field::SetClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700664
665 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700666 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
667 CHECK(class_root != nullptr);
668 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
669 mirror::Field::SetArrayClass(class_root);
670
671 // Create java.lang.reflect.Constructor.class root and array root.
672 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
673 CHECK(class_root != nullptr);
674 SetClassRoot(kJavaLangReflectConstructor, class_root);
675 mirror::Constructor::SetClass(class_root);
676 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
677 CHECK(class_root != nullptr);
678 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
679 mirror::Constructor::SetArrayClass(class_root);
680
681 // Create java.lang.reflect.Method.class root and array root.
682 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
683 CHECK(class_root != nullptr);
684 SetClassRoot(kJavaLangReflectMethod, class_root);
685 mirror::Method::SetClass(class_root);
686 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
687 CHECK(class_root != nullptr);
688 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
689 mirror::Method::SetArrayClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700690
Narayan Kamathafa48272016-08-03 12:46:58 +0100691 // Create java.lang.invoke.MethodType.class root
692 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
693 CHECK(class_root != nullptr);
694 SetClassRoot(kJavaLangInvokeMethodType, class_root);
695 mirror::MethodType::SetClass(class_root);
696
697 // Create java.lang.invoke.MethodHandleImpl.class root
698 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
699 CHECK(class_root != nullptr);
700 SetClassRoot(kJavaLangInvokeMethodHandleImpl, class_root);
701 mirror::MethodHandleImpl::SetClass(class_root);
702
Orion Hodsonc069a302017-01-18 09:23:12 +0000703 // Create java.lang.invoke.MethodHandles.Lookup.class root
704 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
705 CHECK(class_root != nullptr);
706 SetClassRoot(kJavaLangInvokeMethodHandlesLookup, class_root);
707 mirror::MethodHandlesLookup::SetClass(class_root);
708
709 // Create java.lang.invoke.CallSite.class root
710 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
711 CHECK(class_root != nullptr);
712 SetClassRoot(kJavaLangInvokeCallSite, class_root);
713 mirror::CallSite::SetClass(class_root);
714
Narayan Kamath000e1882016-10-24 17:14:25 +0100715 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
716 CHECK(class_root != nullptr);
717 SetClassRoot(kDalvikSystemEmulatedStackFrame, class_root);
718 mirror::EmulatedStackFrame::SetClass(class_root);
719
Brian Carlstrom1f870082011-08-23 16:02:11 -0700720 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700721 // finish initializing Reference class
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700722 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800723 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700724 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700725 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
726 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700727 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700728 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700729 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700730 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700731 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700732 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700733 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700734 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700735 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700736 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700737 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700738 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700739
Ian Rogers23435d02012-09-24 11:23:12 -0700740 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700741 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700742 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700743 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
744 SetClassRoot(kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700745
jeffhao8cd6dda2012-02-22 10:15:34 -0800746 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700747 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800748 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800749 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700750 SetClassRoot(kJavaLangClassNotFoundException,
751 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800752 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700753 SetClassRoot(kJavaLangStackTraceElementArrayClass,
754 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800755 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700756
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700757 // Create conflict tables that depend on the class linker.
758 runtime->FixupConflictTables();
759
Ian Rogers98379392014-02-24 16:53:16 -0800760 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700761
Brian Carlstroma004aa92012-02-08 18:05:09 -0800762 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800763
764 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700765}
766
Ian Rogers98379392014-02-24 16:53:16 -0800767void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800768 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700769
770 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700771 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700772 // as the types of the field can't be resolved prior to the runtime being
773 // fully initialized
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700774 StackHandleScope<2> hs(self);
775 Handle<mirror::Class> java_lang_ref_Reference = hs.NewHandle(GetClassRoot(kJavaLangRefReference));
776 Handle<mirror::Class> java_lang_ref_FinalizerReference =
777 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800778
Mathieu Chartierc7853442015-03-27 14:35:38 -0700779 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700780 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
781 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700782
Mathieu Chartierc7853442015-03-27 14:35:38 -0700783 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700784 CHECK_STREQ(queue->GetName(), "queue");
785 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700786
Mathieu Chartierc7853442015-03-27 14:35:38 -0700787 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700788 CHECK_STREQ(queueNext->GetName(), "queueNext");
789 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700790
Mathieu Chartierc7853442015-03-27 14:35:38 -0700791 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700792 CHECK_STREQ(referent->GetName(), "referent");
793 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700794
Mathieu Chartierc7853442015-03-27 14:35:38 -0700795 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700796 CHECK_STREQ(zombie->GetName(), "zombie");
797 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700798
Brian Carlstroma663ea52011-08-19 23:33:41 -0700799 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700800 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700801 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700802 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700803 CHECK(klass != nullptr);
804 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700805 // note SetClassRoot does additional validation.
806 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700807 }
808
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700809 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700810
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700811 // disable the slow paths in FindClass and CreatePrimitiveClass now
812 // that Object, Class, and Object[] are setup
813 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700814
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800815 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700816}
817
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700818void ClassLinker::RunRootClinits() {
819 Thread* self = Thread::Current();
820 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700821 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700822 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700823 StackHandleScope<1> hs(self);
824 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700825 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700826 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700827 }
828 }
829}
830
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200831// Set image methods' entry point to interpreter.
832class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
833 public:
Andreas Gampe542451c2016-07-26 09:02:02 -0700834 explicit SetInterpreterEntrypointArtMethodVisitor(PointerSize image_pointer_size)
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200835 : image_pointer_size_(image_pointer_size) {}
836
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700837 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200838 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
839 CHECK(method->GetDeclaringClass() != nullptr);
840 }
841 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
842 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
843 image_pointer_size_);
844 }
845 }
846
847 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700848 const PointerSize image_pointer_size_;
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200849
850 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
851};
852
Jeff Haodcdc85b2015-12-04 14:06:18 -0800853struct TrampolineCheckData {
854 const void* quick_resolution_trampoline;
855 const void* quick_imt_conflict_trampoline;
856 const void* quick_generic_jni_trampoline;
857 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700858 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800859 ArtMethod* m;
860 bool error;
861};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800862
Jeff Haodcdc85b2015-12-04 14:06:18 -0800863static void CheckTrampolines(mirror::Object* obj, void* arg) NO_THREAD_SAFETY_ANALYSIS {
864 if (obj->IsClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700865 ObjPtr<mirror::Class> klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800866 TrampolineCheckData* d = reinterpret_cast<TrampolineCheckData*>(arg);
867 for (ArtMethod& m : klass->GetMethods(d->pointer_size)) {
868 const void* entrypoint = m.GetEntryPointFromQuickCompiledCodePtrSize(d->pointer_size);
869 if (entrypoint == d->quick_resolution_trampoline ||
870 entrypoint == d->quick_imt_conflict_trampoline ||
871 entrypoint == d->quick_generic_jni_trampoline ||
872 entrypoint == d->quick_to_interpreter_bridge_trampoline) {
873 d->m = &m;
874 d->error = true;
875 return;
876 }
877 }
878 }
879}
880
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800881bool ClassLinker::InitFromBootImage(std::string* error_msg) {
882 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700883 CHECK(!init_done_);
884
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700885 Runtime* const runtime = Runtime::Current();
886 Thread* const self = Thread::Current();
887 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800888 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
889 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700890 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
891 if (!ValidPointerSize(pointer_size_unchecked)) {
892 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800893 return false;
894 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700895 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800896 if (!runtime->IsAotCompiler()) {
897 // Only the Aot compiler supports having an image with a different pointer size than the
898 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
899 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700900 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800901 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700902 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800903 sizeof(void*));
904 return false;
905 }
906 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800907 std::vector<const OatFile*> oat_files =
908 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
909 DCHECK(!oat_files.empty());
910 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800911 CHECK_EQ(default_oat_header.GetImageFileLocationOatDataBegin(), 0U);
912 const char* image_file_location = oat_files[0]->GetOatHeader().
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700913 GetStoreValueByKey(OatHeader::kImageLocationKey);
914 CHECK(image_file_location == nullptr || *image_file_location == 0);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800915 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
916 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
917 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
918 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
919 if (kIsDebugBuild) {
920 // Check that the other images use the same trampoline.
921 for (size_t i = 1; i < oat_files.size(); ++i) {
922 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
923 const void* ith_quick_resolution_trampoline =
924 ith_oat_header.GetQuickResolutionTrampoline();
925 const void* ith_quick_imt_conflict_trampoline =
926 ith_oat_header.GetQuickImtConflictTrampoline();
927 const void* ith_quick_generic_jni_trampoline =
928 ith_oat_header.GetQuickGenericJniTrampoline();
929 const void* ith_quick_to_interpreter_bridge_trampoline =
930 ith_oat_header.GetQuickToInterpreterBridge();
931 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
932 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
933 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
934 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
935 // Make sure that all methods in this image do not contain those trampolines as
936 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
937 TrampolineCheckData data;
938 data.error = false;
939 data.pointer_size = GetImagePointerSize();
940 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
941 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
942 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
943 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
944 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
945 spaces[i]->GetLiveBitmap()->Walk(CheckTrampolines, &data);
946 if (data.error) {
947 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -0700948 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800949 *error_msg = "Found an ArtMethod with a bad entrypoint";
950 return false;
951 }
952 }
953 }
954 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700955
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800956 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
957 down_cast<mirror::ObjectArray<mirror::Class>*>(
958 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)));
959 mirror::Class::SetClassClass(class_roots_.Read()->Get(kJavaLangClass));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700960
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700961 // Special case of setting up the String class early so that we can test arbitrary objects
962 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700963 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800964
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700965 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot(kJavaLangObject);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700966 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800967 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
968 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800969 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
970 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700971
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800972 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700973 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800974 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800975 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700976 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
977 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700978 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
979 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
980 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
981 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
Narayan Kamathafa48272016-08-03 12:46:58 +0100982 mirror::MethodType::SetClass(GetClassRoot(kJavaLangInvokeMethodType));
983 mirror::MethodHandleImpl::SetClass(GetClassRoot(kJavaLangInvokeMethodHandleImpl));
Orion Hodsonc069a302017-01-18 09:23:12 +0000984 mirror::MethodHandlesLookup::SetClass(GetClassRoot(kJavaLangInvokeMethodHandlesLookup));
985 mirror::CallSite::SetClass(GetClassRoot(kJavaLangInvokeCallSite));
Fred Shih4ee7a662014-07-11 09:59:27 -0700986 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800987 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
988 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
989 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
990 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
991 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
992 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
993 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
994 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
995 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
996 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Narayan Kamath000e1882016-10-24 17:14:25 +0100997 mirror::EmulatedStackFrame::SetClass(GetClassRoot(kDalvikSystemEmulatedStackFrame));
Alex Lightd6251582016-10-31 11:12:30 -0700998 mirror::ClassExt::SetClass(GetClassRoot(kDalvikSystemClassExt));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700999
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001000 for (gc::space::ImageSpace* image_space : spaces) {
1001 // Boot class loader, use a null handle.
1002 std::vector<std::unique_ptr<const DexFile>> dex_files;
1003 if (!AddImageSpace(image_space,
1004 ScopedNullHandle<mirror::ClassLoader>(),
1005 /*dex_elements*/nullptr,
1006 /*dex_location*/nullptr,
1007 /*out*/&dex_files,
1008 error_msg)) {
1009 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001010 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001011 // Append opened dex files at the end.
1012 boot_dex_files_.insert(boot_dex_files_.end(),
1013 std::make_move_iterator(dex_files.begin()),
1014 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001015 }
Ian Rogers98379392014-02-24 16:53:16 -08001016 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001017
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001018 VLOG(startup) << __FUNCTION__ << " exiting";
1019 return true;
1020}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001021
Jeff Hao5872d7c2016-04-27 11:07:41 -07001022bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001023 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001024 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001025 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1026 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001027}
1028
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001029static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1030 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001031 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001032 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001033 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001034 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001035 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001036 DCHECK(dex_file_field != nullptr);
1037 DCHECK(dex_file_name_field != nullptr);
1038 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001039 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001040 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001041 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001042 // Null dex file means it was probably a jar with no dex files, return a null string.
1043 *out_name = nullptr;
1044 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001045 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001046 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001047 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001048 *out_name = name_object->AsString();
1049 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001050 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001051 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001052}
1053
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001054static bool FlattenPathClassLoader(ObjPtr<mirror::ClassLoader> class_loader,
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001055 std::list<ObjPtr<mirror::String>>* out_dex_file_names,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001056 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001057 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001058 DCHECK(out_dex_file_names != nullptr);
1059 DCHECK(error_msg != nullptr);
1060 ScopedObjectAccessUnchecked soa(Thread::Current());
1061 ArtField* const dex_path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001062 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001063 ArtField* const dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001064 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001065 CHECK(dex_path_list_field != nullptr);
1066 CHECK(dex_elements_field != nullptr);
Jeff Hao5872d7c2016-04-27 11:07:41 -07001067 while (!ClassLinker::IsBootClassLoader(soa, class_loader)) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07001068 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1069 class_loader->GetClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001070 *error_msg = StringPrintf("Unknown class loader type %s",
1071 class_loader->PrettyTypeOf().c_str());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001072 // Unsupported class loader.
1073 return false;
1074 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001075 ObjPtr<mirror::Object> dex_path_list = dex_path_list_field->GetObject(class_loader);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001076 if (dex_path_list != nullptr) {
1077 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
Mathieu Chartier3398c782016-09-30 10:27:43 -07001078 ObjPtr<mirror::Object> dex_elements_obj = dex_elements_field->GetObject(dex_path_list);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001079 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1080 // at the mCookie which is a DexFile vector.
1081 if (dex_elements_obj != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001082 ObjPtr<mirror::ObjectArray<mirror::Object>> dex_elements =
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001083 dex_elements_obj->AsObjectArray<mirror::Object>();
1084 // Reverse order since we insert the parent at the front.
1085 for (int32_t i = dex_elements->GetLength() - 1; i >= 0; --i) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001086 ObjPtr<mirror::Object> element = dex_elements->GetWithoutChecks(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001087 if (element == nullptr) {
1088 *error_msg = StringPrintf("Null dex element at index %d", i);
1089 return false;
1090 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001091 ObjPtr<mirror::String> name;
1092 if (!GetDexPathListElementName(element, &name)) {
1093 *error_msg = StringPrintf("Invalid dex path list element at index %d", i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001094 return false;
1095 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001096 if (name != nullptr) {
1097 out_dex_file_names->push_front(name.Ptr());
1098 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001099 }
1100 }
1101 }
1102 class_loader = class_loader->GetParent();
1103 }
1104 return true;
1105}
1106
1107class FixupArtMethodArrayVisitor : public ArtMethodVisitor {
1108 public:
1109 explicit FixupArtMethodArrayVisitor(const ImageHeader& header) : header_(header) {}
1110
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001111 virtual void Visit(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light36121492016-02-22 13:43:29 -08001112 const bool is_copied = method->IsCopied();
Andreas Gampe542451c2016-07-26 09:02:02 -07001113 ArtMethod** resolved_methods = method->GetDexCacheResolvedMethods(kRuntimePointerSize);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001114 if (resolved_methods != nullptr) {
1115 bool in_image_space = false;
Alex Light36121492016-02-22 13:43:29 -08001116 if (kIsDebugBuild || is_copied) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001117 in_image_space = header_.GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains(
1118 reinterpret_cast<const uint8_t*>(resolved_methods) - header_.GetImageBegin());
1119 }
1120 // Must be in image space for non-miranda method.
Alex Light36121492016-02-22 13:43:29 -08001121 DCHECK(is_copied || in_image_space)
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001122 << resolved_methods << " is not in image starting at "
1123 << reinterpret_cast<void*>(header_.GetImageBegin());
Alex Light36121492016-02-22 13:43:29 -08001124 if (!is_copied || in_image_space) {
Vladimir Marko6dd14882016-10-25 11:51:35 +01001125 method->SetDexCacheResolvedMethods(method->GetDexCache()->GetResolvedMethods(),
Andreas Gampe542451c2016-07-26 09:02:02 -07001126 kRuntimePointerSize);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001127 }
1128 }
1129 }
1130
1131 private:
1132 const ImageHeader& header_;
1133};
1134
1135class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1136 public:
1137 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1138
1139 virtual void Visit(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001140 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001141 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001142 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
David Sehr709b0702016-10-13 09:12:37 -07001143 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << mirror::Class::PrettyClass(klass);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001144 }
1145 }
1146
1147 private:
1148 ClassTable* const table_;
1149};
1150
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001151class VerifyDirectInterfacesInTableClassVisitor {
1152 public:
1153 explicit VerifyDirectInterfacesInTableClassVisitor(ObjPtr<mirror::ClassLoader> class_loader)
1154 : class_loader_(class_loader), self_(Thread::Current()) { }
1155
1156 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1157 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader_) {
1158 classes_.push_back(klass);
1159 }
1160 return true;
1161 }
1162
1163 void Check() const REQUIRES_SHARED(Locks::mutator_lock_) {
1164 for (ObjPtr<mirror::Class> klass : classes_) {
1165 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1166 CHECK(klass->GetDirectInterface(self_, klass, i) != nullptr)
1167 << klass->PrettyDescriptor() << " iface #" << i;
1168 }
1169 }
1170 }
1171
1172 private:
1173 ObjPtr<mirror::ClassLoader> class_loader_;
1174 Thread* self_;
1175 std::vector<ObjPtr<mirror::Class>> classes_;
1176};
1177
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001178class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1179 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001180 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001181 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1182
1183 virtual void Visit(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001184 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001185 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked();
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001186 if (klass != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001187 CHECK(live_bitmap_->Test(klass.Ptr())) << "Image method has unmarked declaring class";
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001188 }
1189 }
1190
1191 private:
1192 gc::accounting::HeapBitmap* const live_bitmap_;
1193};
1194
Artem Udovichenkob3ac45b2016-09-09 14:02:25 +03001195// Copies data from one array to another array at the same position
1196// if pred returns false. If there is a page of continuous data in
1197// the src array for which pred consistently returns true then
1198// corresponding page in the dst array will not be touched.
1199// This should reduce number of allocated physical pages.
1200template <class T, class NullPred>
1201static void CopyNonNull(const T* src, size_t count, T* dst, const NullPred& pred) {
1202 for (size_t i = 0; i < count; ++i) {
1203 if (!pred(src[i])) {
1204 dst[i] = src[i];
1205 }
1206 }
1207}
1208
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001209template <typename T>
1210static void CopyDexCachePairs(const std::atomic<mirror::DexCachePair<T>>* src,
1211 size_t count,
1212 std::atomic<mirror::DexCachePair<T>>* dst) {
1213 DCHECK_NE(count, 0u);
1214 DCHECK(!src[0].load(std::memory_order_relaxed).object.IsNull() ||
1215 src[0].load(std::memory_order_relaxed).index != 0u);
1216 for (size_t i = 0; i < count; ++i) {
1217 DCHECK_EQ(dst[i].load(std::memory_order_relaxed).index, 0u);
1218 DCHECK(dst[i].load(std::memory_order_relaxed).object.IsNull());
1219 mirror::DexCachePair<T> source = src[i].load(std::memory_order_relaxed);
1220 if (source.index != 0u || !source.object.IsNull()) {
1221 dst[i].store(source, std::memory_order_relaxed);
1222 }
1223 }
1224}
1225
Andreas Gampe2af99022017-04-25 08:32:59 -07001226// new_class_set is the set of classes that were read from the class table section in the image.
1227// If there was no class table section, it is null.
1228// Note: using a class here to avoid having to make ClassLinker internals public.
1229class AppImageClassLoadersAndDexCachesHelper {
1230 public:
1231 static bool Update(
1232 ClassLinker* class_linker,
1233 gc::space::ImageSpace* space,
1234 Handle<mirror::ClassLoader> class_loader,
1235 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
1236 ClassTable::ClassSet* new_class_set,
1237 bool* out_forward_dex_cache_array,
1238 std::string* out_error_msg)
1239 REQUIRES(!Locks::dex_lock_)
1240 REQUIRES_SHARED(Locks::mutator_lock_);
1241};
1242
1243bool AppImageClassLoadersAndDexCachesHelper::Update(
1244 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001245 gc::space::ImageSpace* space,
1246 Handle<mirror::ClassLoader> class_loader,
1247 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Mathieu Chartier69731002016-03-02 16:08:31 -08001248 ClassTable::ClassSet* new_class_set,
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001249 bool* out_forward_dex_cache_array,
Andreas Gampe2af99022017-04-25 08:32:59 -07001250 std::string* out_error_msg)
1251 REQUIRES(!Locks::dex_lock_)
1252 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001253 DCHECK(out_forward_dex_cache_array != nullptr);
1254 DCHECK(out_error_msg != nullptr);
Andreas Gampe2af99022017-04-25 08:32:59 -07001255 PointerSize image_pointer_size = class_linker->GetImagePointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001256 Thread* const self = Thread::Current();
1257 gc::Heap* const heap = Runtime::Current()->GetHeap();
1258 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001259 {
1260 // Add image classes into the class table for the class loader, and fixup the dex caches and
1261 // class loader fields.
1262 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001263 // Dex cache array fixup is all or nothing, we must reject app images that have mixed since we
1264 // rely on clobering the dex cache arrays in the image to forward to bss.
1265 size_t num_dex_caches_with_bss_arrays = 0;
1266 const size_t num_dex_caches = dex_caches->GetLength();
1267 for (size_t i = 0; i < num_dex_caches; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001268 ObjPtr<mirror::DexCache> const dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001269 const DexFile* const dex_file = dex_cache->GetDexFile();
1270 const OatFile::OatDexFile* oat_dex_file = dex_file->GetOatDexFile();
1271 if (oat_dex_file != nullptr && oat_dex_file->GetDexCacheArrays() != nullptr) {
1272 ++num_dex_caches_with_bss_arrays;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001273 }
1274 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001275 *out_forward_dex_cache_array = num_dex_caches_with_bss_arrays != 0;
1276 if (*out_forward_dex_cache_array) {
1277 if (num_dex_caches_with_bss_arrays != num_dex_caches) {
1278 // Reject application image since we cannot forward only some of the dex cache arrays.
1279 // TODO: We could get around this by having a dedicated forwarding slot. It should be an
1280 // uncommon case.
1281 *out_error_msg = StringPrintf("Dex caches in bss does not match total: %zu vs %zu",
1282 num_dex_caches_with_bss_arrays,
1283 num_dex_caches);
1284 return false;
1285 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001286 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001287 // Only add the classes to the class loader after the points where we can return false.
1288 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001289 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001290 const DexFile* const dex_file = dex_cache->GetDexFile();
1291 const OatFile::OatDexFile* oat_dex_file = dex_file->GetOatDexFile();
1292 if (oat_dex_file != nullptr && oat_dex_file->GetDexCacheArrays() != nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01001293 // If the oat file expects the dex cache arrays to be in the BSS, then allocate there and
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001294 // copy over the arrays.
1295 DCHECK(dex_file != nullptr);
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001296 size_t num_strings = mirror::DexCache::kDexCacheStringCacheSize;
1297 if (dex_file->NumStringIds() < num_strings) {
1298 num_strings = dex_file->NumStringIds();
1299 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001300 size_t num_types = mirror::DexCache::kDexCacheTypeCacheSize;
1301 if (dex_file->NumTypeIds() < num_types) {
1302 num_types = dex_file->NumTypeIds();
1303 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001304 const size_t num_methods = dex_file->NumMethodIds();
Vladimir Markof44d36c2017-03-14 14:18:46 +00001305 size_t num_fields = mirror::DexCache::kDexCacheFieldCacheSize;
1306 if (dex_file->NumFieldIds() < num_fields) {
1307 num_fields = dex_file->NumFieldIds();
1308 }
Narayan Kamath269cb432016-10-28 10:19:54 +01001309 size_t num_method_types = mirror::DexCache::kDexCacheMethodTypeCacheSize;
1310 if (dex_file->NumProtoIds() < num_method_types) {
1311 num_method_types = dex_file->NumProtoIds();
Narayan Kamath25352fc2016-08-03 12:46:58 +01001312 }
Orion Hodsonc069a302017-01-18 09:23:12 +00001313 const size_t num_call_sites = dex_file->NumCallSiteIds();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001314 CHECK_EQ(num_strings, dex_cache->NumStrings());
1315 CHECK_EQ(num_types, dex_cache->NumResolvedTypes());
1316 CHECK_EQ(num_methods, dex_cache->NumResolvedMethods());
1317 CHECK_EQ(num_fields, dex_cache->NumResolvedFields());
Narayan Kamath25352fc2016-08-03 12:46:58 +01001318 CHECK_EQ(num_method_types, dex_cache->NumResolvedMethodTypes());
Orion Hodsonc069a302017-01-18 09:23:12 +00001319 CHECK_EQ(num_call_sites, dex_cache->NumResolvedCallSites());
Andreas Gampe2af99022017-04-25 08:32:59 -07001320 DexCacheArraysLayout layout(image_pointer_size, dex_file);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001321 uint8_t* const raw_arrays = oat_dex_file->GetDexCacheArrays();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001322 if (num_strings != 0u) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001323 mirror::StringDexCacheType* const image_resolved_strings = dex_cache->GetStrings();
1324 mirror::StringDexCacheType* const strings =
1325 reinterpret_cast<mirror::StringDexCacheType*>(raw_arrays + layout.StringsOffset());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001326 CopyDexCachePairs(image_resolved_strings, num_strings, strings);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001327 dex_cache->SetStrings(strings);
1328 }
1329 if (num_types != 0u) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001330 mirror::TypeDexCacheType* const image_resolved_types = dex_cache->GetResolvedTypes();
1331 mirror::TypeDexCacheType* const types =
1332 reinterpret_cast<mirror::TypeDexCacheType*>(raw_arrays + layout.TypesOffset());
1333 CopyDexCachePairs(image_resolved_types, num_types, types);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001334 dex_cache->SetResolvedTypes(types);
1335 }
1336 if (num_methods != 0u) {
1337 ArtMethod** const methods = reinterpret_cast<ArtMethod**>(
1338 raw_arrays + layout.MethodsOffset());
1339 ArtMethod** const image_resolved_methods = dex_cache->GetResolvedMethods();
1340 for (size_t j = 0; kIsDebugBuild && j < num_methods; ++j) {
1341 DCHECK(methods[j] == nullptr);
1342 }
Artem Udovichenkob3ac45b2016-09-09 14:02:25 +03001343 CopyNonNull(image_resolved_methods,
1344 num_methods,
1345 methods,
1346 [] (const ArtMethod* method) {
1347 return method == nullptr;
1348 });
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001349 dex_cache->SetResolvedMethods(methods);
1350 }
1351 if (num_fields != 0u) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001352 mirror::FieldDexCacheType* const image_resolved_fields = dex_cache->GetResolvedFields();
1353 mirror::FieldDexCacheType* const fields =
1354 reinterpret_cast<mirror::FieldDexCacheType*>(raw_arrays + layout.FieldsOffset());
1355 for (size_t j = 0; j < num_fields; ++j) {
Andreas Gampe2af99022017-04-25 08:32:59 -07001356 DCHECK_EQ(mirror::DexCache::GetNativePairPtrSize(fields, j, image_pointer_size).index,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001357 0u);
Andreas Gampe2af99022017-04-25 08:32:59 -07001358 DCHECK(mirror::DexCache::GetNativePairPtrSize(fields, j, image_pointer_size).object ==
Vladimir Markof44d36c2017-03-14 14:18:46 +00001359 nullptr);
1360 mirror::DexCache::SetNativePairPtrSize(
1361 fields,
1362 j,
1363 mirror::DexCache::GetNativePairPtrSize(image_resolved_fields,
1364 j,
Andreas Gampe2af99022017-04-25 08:32:59 -07001365 image_pointer_size),
1366 image_pointer_size);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001367 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001368 dex_cache->SetResolvedFields(fields);
1369 }
Narayan Kamath25352fc2016-08-03 12:46:58 +01001370 if (num_method_types != 0u) {
1371 // NOTE: We currently (Sep 2016) do not resolve any method types at
1372 // compile time, but plan to in the future. This code exists for the
1373 // sake of completeness.
1374 mirror::MethodTypeDexCacheType* const image_resolved_method_types =
1375 dex_cache->GetResolvedMethodTypes();
1376 mirror::MethodTypeDexCacheType* const method_types =
1377 reinterpret_cast<mirror::MethodTypeDexCacheType*>(
1378 raw_arrays + layout.MethodTypesOffset());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001379 CopyDexCachePairs(image_resolved_method_types, num_method_types, method_types);
Narayan Kamath25352fc2016-08-03 12:46:58 +01001380 dex_cache->SetResolvedMethodTypes(method_types);
1381 }
Orion Hodsonc069a302017-01-18 09:23:12 +00001382 if (num_call_sites != 0u) {
1383 GcRoot<mirror::CallSite>* const image_resolved_call_sites =
1384 dex_cache->GetResolvedCallSites();
1385 GcRoot<mirror::CallSite>* const call_sites =
1386 reinterpret_cast<GcRoot<mirror::CallSite>*>(raw_arrays + layout.CallSitesOffset());
1387 for (size_t j = 0; kIsDebugBuild && j < num_call_sites; ++j) {
1388 DCHECK(call_sites[j].IsNull());
1389 }
1390 CopyNonNull(image_resolved_call_sites,
1391 num_call_sites,
1392 call_sites,
1393 [](const GcRoot<mirror::CallSite>& elem) {
1394 return elem.IsNull();
1395 });
1396 dex_cache->SetResolvedCallSites(call_sites);
1397 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001398 }
1399 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001400 WriterMutexLock mu2(self, *Locks::dex_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001401 // Make sure to do this after we update the arrays since we store the resolved types array
1402 // in DexCacheData in RegisterDexFileLocked. We need the array pointer to be the one in the
1403 // BSS.
Andreas Gampe2af99022017-04-25 08:32:59 -07001404 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1405 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001406 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001407 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001408 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001409 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001410 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001411 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001412 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001413 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001414 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001415 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001416 auto it = new_class_set->Find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001417 DCHECK(it != new_class_set->end());
1418 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001419 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001420 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001421 auto it2 = new_class_set->Find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001422 DCHECK(it2 != new_class_set->end());
1423 DCHECK_EQ(it2->Read(), super_class);
1424 }
1425 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1426 const void* code = m.GetEntryPointFromQuickCompiledCode();
Andreas Gampe2af99022017-04-25 08:32:59 -07001427 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1428 if (!class_linker->IsQuickResolutionStub(code) &&
1429 !class_linker->IsQuickGenericJniStub(code) &&
1430 !class_linker->IsQuickToInterpreterBridge(code) &&
Vladimir Marko1a1de672016-10-13 12:53:15 +01001431 !m.IsNative()) {
David Sehr709b0702016-10-13 09:12:37 -07001432 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001433 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001434 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01001435 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1436 const void* code = m.GetEntryPointFromQuickCompiledCode();
Andreas Gampe2af99022017-04-25 08:32:59 -07001437 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1438 if (!class_linker->IsQuickResolutionStub(code) &&
1439 !class_linker->IsQuickGenericJniStub(code) &&
1440 !class_linker->IsQuickToInterpreterBridge(code) &&
Vladimir Marko1a1de672016-10-13 12:53:15 +01001441 !m.IsNative()) {
David Sehr709b0702016-10-13 09:12:37 -07001442 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001443 }
1444 }
1445 }
1446 }
1447 }
1448 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001449 }
1450 if (*out_forward_dex_cache_array) {
1451 ScopedTrace timing("Fixup ArtMethod dex cache arrays");
1452 FixupArtMethodArrayVisitor visitor(header);
Andreas Gampe542451c2016-07-26 09:02:02 -07001453 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001454 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get());
1455 }
1456 if (kVerifyArtMethodDeclaringClasses) {
1457 ScopedTrace timing("Verify declaring classes");
1458 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1459 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001460 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001461 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001462 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001463}
1464
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001465// Update the class loader. Should only be used on classes in the image space.
1466class UpdateClassLoaderVisitor {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001467 public:
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001468 UpdateClassLoaderVisitor(gc::space::ImageSpace* space, ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001469 : space_(space),
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001470 class_loader_(class_loader) {}
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001471
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001472 bool operator()(ObjPtr<mirror::Class> klass) const REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001473 // Do not update class loader for boot image classes where the app image
1474 // class loader is only the initiating loader but not the defining loader.
1475 if (klass->GetClassLoader() != nullptr) {
1476 klass->SetClassLoader(class_loader_);
1477 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001478 return true;
1479 }
1480
1481 gc::space::ImageSpace* const space_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001482 ObjPtr<mirror::ClassLoader> const class_loader_;
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001483};
1484
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001485static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1486 const char* location,
1487 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001488 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001489 DCHECK(error_msg != nullptr);
1490 std::unique_ptr<const DexFile> dex_file;
Richard Uhler9a37efc2016-08-05 16:32:55 -07001491 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001492 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001493 return std::unique_ptr<const DexFile>();
1494 }
1495 std::string inner_error_msg;
1496 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1497 if (dex_file == nullptr) {
1498 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1499 location,
1500 oat_file->GetLocation().c_str(),
1501 inner_error_msg.c_str());
1502 return std::unique_ptr<const DexFile>();
1503 }
1504
1505 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1506 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1507 location,
1508 dex_file->GetLocationChecksum(),
1509 oat_dex_file->GetDexFileLocationChecksum());
1510 return std::unique_ptr<const DexFile>();
1511 }
1512 return dex_file;
1513}
1514
1515bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1516 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1517 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001518 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001519 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001520 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001521 DCHECK(dex_caches_object != nullptr);
1522 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1523 dex_caches_object->AsObjectArray<mirror::DexCache>();
1524 const OatFile* oat_file = space->GetOatFile();
1525 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001526 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001527 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1528 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1529 dex_file_location.c_str(),
1530 error_msg);
1531 if (dex_file == nullptr) {
1532 return false;
1533 }
1534 dex_cache->SetDexFile(dex_file.get());
1535 out_dex_files->push_back(std::move(dex_file));
1536 }
1537 return true;
1538}
1539
Andreas Gampe0793bec2016-12-01 11:37:33 -08001540// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1541// together and caches some intermediate results.
1542class ImageSanityChecks FINAL {
1543 public:
1544 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1545 REQUIRES_SHARED(Locks::mutator_lock_) {
1546 ImageSanityChecks isc(heap, class_linker);
1547 heap->VisitObjects(ImageSanityChecks::SanityCheckObjectsCallback, &isc);
1548 }
1549
1550 static void CheckPointerArray(gc::Heap* heap,
1551 ClassLinker* class_linker,
1552 ArtMethod** arr,
1553 size_t size)
1554 REQUIRES_SHARED(Locks::mutator_lock_) {
1555 ImageSanityChecks isc(heap, class_linker);
1556 isc.SanityCheckArtMethodPointerArray(arr, size);
1557 }
1558
1559 static void SanityCheckObjectsCallback(mirror::Object* obj, void* arg)
1560 REQUIRES_SHARED(Locks::mutator_lock_) {
1561 DCHECK(obj != nullptr);
1562 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1563 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1564 if (obj->IsClass()) {
1565 ImageSanityChecks* isc = reinterpret_cast<ImageSanityChecks*>(arg);
1566
1567 auto klass = obj->AsClass();
1568 for (ArtField& field : klass->GetIFields()) {
1569 CHECK_EQ(field.GetDeclaringClass(), klass);
1570 }
1571 for (ArtField& field : klass->GetSFields()) {
1572 CHECK_EQ(field.GetDeclaringClass(), klass);
1573 }
1574 const auto pointer_size = isc->pointer_size_;
1575 for (auto& m : klass->GetMethods(pointer_size)) {
1576 isc->SanityCheckArtMethod(&m, klass);
1577 }
1578 auto* vtable = klass->GetVTable();
1579 if (vtable != nullptr) {
1580 isc->SanityCheckArtMethodPointerArray(vtable, nullptr);
1581 }
1582 if (klass->ShouldHaveImt()) {
1583 ImTable* imt = klass->GetImt(pointer_size);
1584 for (size_t i = 0; i < ImTable::kSize; ++i) {
1585 isc->SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1586 }
1587 }
1588 if (klass->ShouldHaveEmbeddedVTable()) {
1589 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1590 isc->SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1591 }
1592 }
1593 mirror::IfTable* iftable = klass->GetIfTable();
1594 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1595 if (iftable->GetMethodArrayCount(i) > 0) {
1596 isc->SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1597 }
1598 }
1599 }
1600 }
1601
1602 private:
1603 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1604 : spaces_(heap->GetBootImageSpaces()),
1605 pointer_size_(class_linker->GetImagePointerSize()) {
1606 space_begin_.reserve(spaces_.size());
1607 method_sections_.reserve(spaces_.size());
1608 runtime_method_sections_.reserve(spaces_.size());
1609 for (gc::space::ImageSpace* space : spaces_) {
1610 space_begin_.push_back(space->Begin());
1611 auto& header = space->GetImageHeader();
1612 method_sections_.push_back(&header.GetMethodsSection());
1613 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1614 }
1615 }
1616
1617 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1618 REQUIRES_SHARED(Locks::mutator_lock_) {
1619 if (m->IsRuntimeMethod()) {
1620 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1621 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1622 } else if (m->IsCopied()) {
1623 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1624 } else if (expected_class != nullptr) {
1625 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1626 }
1627 if (!spaces_.empty()) {
1628 bool contains = false;
1629 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1630 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1631 contains = method_sections_[i]->Contains(offset) ||
1632 runtime_method_sections_[i]->Contains(offset);
1633 }
1634 CHECK(contains) << m << " not found";
1635 }
1636 }
1637
1638 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1639 ObjPtr<mirror::Class> expected_class)
1640 REQUIRES_SHARED(Locks::mutator_lock_) {
1641 CHECK(arr != nullptr);
1642 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1643 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1644 // expected_class == null means we are a dex cache.
1645 if (expected_class != nullptr) {
1646 CHECK(method != nullptr);
1647 }
1648 if (method != nullptr) {
1649 SanityCheckArtMethod(method, expected_class);
1650 }
1651 }
1652 }
1653
1654 void SanityCheckArtMethodPointerArray(ArtMethod** arr, size_t size)
1655 REQUIRES_SHARED(Locks::mutator_lock_) {
1656 CHECK_EQ(arr != nullptr, size != 0u);
1657 if (arr != nullptr) {
1658 bool contains = false;
1659 for (auto space : spaces_) {
1660 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
1661 if (space->GetImageHeader().GetImageSection(
1662 ImageHeader::kSectionDexCacheArrays).Contains(offset)) {
1663 contains = true;
1664 break;
1665 }
1666 }
1667 CHECK(contains);
1668 }
1669 for (size_t j = 0; j < size; ++j) {
1670 ArtMethod* method = mirror::DexCache::GetElementPtrSize(arr, j, pointer_size_);
1671 // expected_class == null means we are a dex cache.
1672 if (method != nullptr) {
1673 SanityCheckArtMethod(method, nullptr);
1674 }
1675 }
1676 }
1677
1678 const std::vector<gc::space::ImageSpace*>& spaces_;
1679 const PointerSize pointer_size_;
1680
1681 // Cached sections from the spaces.
1682 std::vector<const uint8_t*> space_begin_;
1683 std::vector<const ImageSection*> method_sections_;
1684 std::vector<const ImageSection*> runtime_method_sections_;
1685};
1686
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001687bool ClassLinker::AddImageSpace(
1688 gc::space::ImageSpace* space,
1689 Handle<mirror::ClassLoader> class_loader,
1690 jobjectArray dex_elements,
1691 const char* dex_location,
1692 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1693 std::string* error_msg) {
1694 DCHECK(out_dex_files != nullptr);
1695 DCHECK(error_msg != nullptr);
1696 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001697 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001698 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001699 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001700 DCHECK(dex_caches_object != nullptr);
1701 Runtime* const runtime = Runtime::Current();
1702 gc::Heap* const heap = runtime->GetHeap();
1703 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001704 // Check that the image is what we are expecting.
1705 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1706 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1707 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1708 image_pointer_size_);
1709 return false;
1710 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001711 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1712 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1713 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1714 expected_image_roots,
1715 header.GetImageRoots()->GetLength());
1716 return false;
1717 }
1718 StackHandleScope<3> hs(self);
1719 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1720 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1721 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1722 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
1723 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1724 "Class loader should be the last image root.");
1725 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
1726 app_image ? header.GetImageRoot(ImageHeader::kClassLoader)->AsClassLoader() : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001727 DCHECK(class_roots != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001728 if (class_roots->GetLength() != static_cast<int32_t>(kClassRootsMax)) {
1729 *error_msg = StringPrintf("Expected %d class roots but got %d",
1730 class_roots->GetLength(),
1731 static_cast<int32_t>(kClassRootsMax));
1732 return false;
1733 }
1734 // Check against existing class roots to make sure they match the ones in the boot image.
1735 for (size_t i = 0; i < kClassRootsMax; i++) {
1736 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i))) {
1737 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1738 return false;
1739 }
1740 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001741 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001742 if (oat_file->GetOatHeader().GetDexFileCount() !=
1743 static_cast<uint32_t>(dex_caches->GetLength())) {
1744 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1745 "image";
1746 return false;
1747 }
1748
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001749 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001750 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1751 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001752 // TODO: Only store qualified paths.
1753 // If non qualified, qualify it.
1754 if (dex_file_location.find('/') == std::string::npos) {
1755 std::string dex_location_path = dex_location;
1756 const size_t pos = dex_location_path.find_last_of('/');
1757 CHECK_NE(pos, std::string::npos);
1758 dex_location_path = dex_location_path.substr(0, pos + 1); // Keep trailing '/'
1759 dex_file_location = dex_location_path + dex_file_location;
1760 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001761 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1762 dex_file_location.c_str(),
1763 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001764 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001765 return false;
1766 }
1767
1768 if (app_image) {
1769 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
1770 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00001771 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001772 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00001773 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001774 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001775 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001776 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001777 }
1778 }
1779 } else {
1780 if (kSanityCheckObjects) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001781 ImageSanityChecks::CheckPointerArray(heap,
1782 this,
Vladimir Markocd556b02017-02-03 11:47:34 +00001783 dex_cache->GetResolvedMethods(),
1784 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001785 }
1786 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00001787 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001788 }
1789 out_dex_files->push_back(std::move(dex_file));
1790 }
1791
1792 if (app_image) {
1793 ScopedObjectAccessUnchecked soa(Thread::Current());
1794 // Check that the class loader resolves the same way as the ones in the image.
1795 // Image class loader [A][B][C][image dex files]
1796 // Class loader = [???][dex_elements][image dex files]
1797 // Need to ensure that [???][dex_elements] == [A][B][C].
1798 // For each class loader, PathClassLoader, the laoder checks the parent first. Also the logic
1799 // for PathClassLoader does this by looping through the array of dex files. To ensure they
1800 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
1801 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001802 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1803 *error_msg = "Unexpected BootClassLoader in app image";
1804 return false;
1805 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001806 std::list<ObjPtr<mirror::String>> image_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001807 std::string temp_error_msg;
1808 if (!FlattenPathClassLoader(image_class_loader.Get(), &image_dex_file_names, &temp_error_msg)) {
1809 *error_msg = StringPrintf("Failed to flatten image class loader hierarchy '%s'",
1810 temp_error_msg.c_str());
1811 return false;
1812 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001813 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001814 if (!FlattenPathClassLoader(class_loader.Get(), &loader_dex_file_names, &temp_error_msg)) {
1815 *error_msg = StringPrintf("Failed to flatten class loader hierarchy '%s'",
1816 temp_error_msg.c_str());
1817 return false;
1818 }
1819 // Add the temporary dex path list elements at the end.
1820 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
1821 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
1822 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
1823 if (element != nullptr) {
1824 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001825 ObjPtr<mirror::String> name;
1826 if (GetDexPathListElementName(element, &name) && name != nullptr) {
1827 loader_dex_file_names.push_back(name);
1828 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01001829 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001830 }
1831 // Ignore the number of image dex files since we are adding those to the class loader anyways.
1832 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
1833 static_cast<size_t>(dex_caches->GetLength()));
1834 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
1835 // Check that the dex file names match.
1836 bool equal = image_count == loader_dex_file_names.size();
1837 if (equal) {
1838 auto it1 = image_dex_file_names.begin();
1839 auto it2 = loader_dex_file_names.begin();
1840 for (size_t i = 0; equal && i < image_count; ++i, ++it1, ++it2) {
1841 equal = equal && (*it1)->Equals(*it2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001842 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001843 }
1844 if (!equal) {
1845 VLOG(image) << "Image dex files " << image_dex_file_names.size();
1846 for (ObjPtr<mirror::String> name : image_dex_file_names) {
1847 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001848 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001849 VLOG(image) << "Loader dex files " << loader_dex_file_names.size();
1850 for (ObjPtr<mirror::String> name : loader_dex_file_names) {
1851 VLOG(image) << name->ToModifiedUtf8();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001852 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001853 *error_msg = "Rejecting application image due to class loader mismatch";
1854 // Ignore class loader mismatch for now since these would just use possibly incorrect
1855 // oat code anyways. The structural class check should be done in the parent.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001856 }
1857 }
1858
1859 if (kSanityCheckObjects) {
1860 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1861 auto* dex_cache = dex_caches->Get(i);
1862 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
1863 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
1864 if (field != nullptr) {
1865 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
1866 }
1867 }
1868 }
1869 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001870 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001871 }
1872 }
1873
1874 // Set entry point to interpreter if in InterpretOnly mode.
1875 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001876 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001877 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001878 }
1879
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001880 ClassTable* class_table = nullptr;
1881 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001882 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001883 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08001884 }
1885 // If we have a class table section, read it and use it for verification in
1886 // UpdateAppImageClassLoadersAndDexCaches.
1887 ClassTable::ClassSet temp_set;
1888 const ImageSection& class_table_section = header.GetImageSection(ImageHeader::kSectionClassTable);
1889 const bool added_class_table = class_table_section.Size() > 0u;
1890 if (added_class_table) {
1891 const uint64_t start_time2 = NanoTime();
1892 size_t read_count = 0;
1893 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
1894 /*make copy*/false,
1895 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08001896 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001897 }
1898 if (app_image) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001899 bool forward_dex_cache_arrays = false;
Andreas Gampe2af99022017-04-25 08:32:59 -07001900 if (!AppImageClassLoadersAndDexCachesHelper::Update(this,
1901 space,
1902 class_loader,
1903 dex_caches,
1904 &temp_set,
1905 /*out*/&forward_dex_cache_arrays,
1906 /*out*/error_msg)) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001907 return false;
1908 }
Mathieu Chartier69731002016-03-02 16:08:31 -08001909 // Update class loader and resolved strings. If added_class_table is false, the resolved
1910 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Nicolas Geoffrayf9bf2502016-12-14 14:59:04 +00001911 UpdateClassLoaderVisitor visitor(space, class_loader.Get());
1912 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001913 visitor(root.Read());
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001914 }
Mathieu Chartier8c4f0412016-02-03 16:40:20 -08001915 // forward_dex_cache_arrays is true iff we copied all of the dex cache arrays into the .bss.
1916 // In this case, madvise away the dex cache arrays section of the image to reduce RAM usage and
1917 // mark as PROT_NONE to catch any invalid accesses.
1918 if (forward_dex_cache_arrays) {
1919 const ImageSection& dex_cache_section = header.GetImageSection(
1920 ImageHeader::kSectionDexCacheArrays);
1921 uint8_t* section_begin = AlignUp(space->Begin() + dex_cache_section.Offset(), kPageSize);
1922 uint8_t* section_end = AlignDown(space->Begin() + dex_cache_section.End(), kPageSize);
1923 if (section_begin < section_end) {
1924 madvise(section_begin, section_end - section_begin, MADV_DONTNEED);
1925 mprotect(section_begin, section_end - section_begin, PROT_NONE);
1926 VLOG(image) << "Released and protected dex cache array image section from "
1927 << reinterpret_cast<const void*>(section_begin) << "-"
1928 << reinterpret_cast<const void*>(section_end);
1929 }
1930 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00001931 }
1932 if (!oat_file->GetBssGcRoots().empty()) {
1933 // Insert oat file to class table for visiting .bss GC roots.
1934 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001935 }
Mathieu Chartier69731002016-03-02 16:08:31 -08001936 if (added_class_table) {
1937 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1938 class_table->AddClassSet(std::move(temp_set));
1939 }
1940 if (kIsDebugBuild && app_image) {
1941 // This verification needs to happen after the classes have been added to the class loader.
1942 // Since it ensures classes are in the class table.
1943 VerifyClassInTableArtMethodVisitor visitor2(class_table);
Andreas Gampe542451c2016-07-26 09:02:02 -07001944 header.VisitPackedArtMethods(&visitor2, space->Begin(), kRuntimePointerSize);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001945 // Verify that all direct interfaces of classes in the class table are also resolved.
1946 VerifyDirectInterfacesInTableClassVisitor visitor(class_loader.Get());
1947 class_table->Visit(visitor);
1948 visitor.Check();
1949 // Check that all non-primitive classes in dex caches are also in the class table.
1950 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1951 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1952 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1953 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1954 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1955 if (klass != nullptr && !klass->IsPrimitive()) {
1956 CHECK(class_table->Contains(klass)) << klass->PrettyDescriptor()
1957 << " " << dex_cache->GetDexFile()->GetLocation();
1958 }
1959 }
1960 }
Mathieu Chartier69731002016-03-02 16:08:31 -08001961 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001962 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001963 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001964}
1965
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001966bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001967 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
1968 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001969}
1970
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001971void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001972 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
1973 // enabling tracing requires the mutator lock, there are no race conditions here.
1974 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001975 Thread* const self = Thread::Current();
1976 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00001977 if (kUseReadBarrier) {
1978 // We do not track new roots for CC.
1979 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
1980 kVisitRootFlagClearRootLog |
1981 kVisitRootFlagStartLoggingNewRoots |
1982 kVisitRootFlagStopLoggingNewRoots));
1983 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001984 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001985 // Argument for how root visiting deals with ArtField and ArtMethod roots.
1986 // There is 3 GC cases to handle:
1987 // Non moving concurrent:
1988 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001989 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001990 //
1991 // Moving non-concurrent:
1992 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
1993 // To prevent missing roots, this case needs to ensure that there is no
1994 // suspend points between the point which we allocate ArtMethod arrays and place them in a
1995 // class which is in the class table.
1996 //
1997 // Moving concurrent:
1998 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
1999 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002000 //
2001 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2002 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2003 // these objects.
2004 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002005 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002006 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002007 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002008 for (const ClassLoaderData& data : class_loaders_) {
2009 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2010 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2011 }
2012 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002013 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002014 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002015 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002016 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002017 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002018 // Concurrent moving GC marked new roots through the to-space invariant.
2019 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002020 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002021 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2022 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2023 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2024 if (old_ref != nullptr) {
2025 DCHECK(old_ref->IsClass());
2026 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2027 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2028 // Concurrent moving GC marked new roots through the to-space invariant.
2029 CHECK_EQ(new_ref, old_ref);
2030 }
2031 }
2032 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002033 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002034 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002035 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002036 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002037 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002038 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002039 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002040 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002041 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002042 }
2043 // We deliberately ignore the class roots in the image since we
2044 // handle image roots by using the MS/CMS rescanning of dirty cards.
2045}
2046
Brian Carlstroma663ea52011-08-19 23:33:41 -07002047// Keep in sync with InitCallback. Anything we visit, we need to
2048// reinit references to when reinitializing a ClassLinker from a
2049// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002050void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002051 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002052 VisitClassRoots(visitor, flags);
Mathieu Chartier31000802015-06-14 14:14:37 -07002053 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002054 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2055 // unloading if we are marking roots.
2056 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002057}
2058
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002059class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2060 public:
2061 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2062 : visitor_(visitor),
2063 done_(false) {}
2064
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002065 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002066 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002067 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002068 if (!done_ && class_table != nullptr) {
2069 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2070 if (!class_table->Visit(visitor)) {
2071 // If the visitor ClassTable returns false it means that we don't need to continue.
2072 done_ = true;
2073 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002074 }
2075 }
2076
2077 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002078 // Class visitor that limits the class visits from a ClassTable to the classes with
2079 // the provided defining class loader. This filter is used to avoid multiple visits
2080 // of the same class which can be recorded for multiple initiating class loaders.
2081 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2082 public:
2083 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2084 ClassVisitor* visitor)
2085 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2086
2087 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
2088 if (klass->GetClassLoader() != defining_class_loader_) {
2089 return true;
2090 }
2091 return (*visitor_)(klass);
2092 }
2093
2094 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2095 ClassVisitor* const visitor_;
2096 };
2097
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002098 ClassVisitor* const visitor_;
2099 // If done is true then we don't need to do any more visiting.
2100 bool done_;
2101};
2102
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002103void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002104 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002105 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2106 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002107 }
2108}
2109
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002110void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002111 Thread* const self = Thread::Current();
2112 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2113 // Not safe to have thread suspension when we are holding a lock.
2114 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002115 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002116 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002117 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002118 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002119 }
2120}
2121
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002122class GetClassesInToVector : public ClassVisitor {
2123 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002124 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002125 classes_.push_back(klass);
2126 return true;
2127 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002128 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002129};
2130
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002131class GetClassInToObjectArray : public ClassVisitor {
2132 public:
2133 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2134 : arr_(arr), index_(0) {}
2135
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002136 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002137 ++index_;
2138 if (index_ <= arr_->GetLength()) {
2139 arr_->Set(index_ - 1, klass);
2140 return true;
2141 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002142 return false;
2143 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002144
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002145 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002146 return index_ <= arr_->GetLength();
2147 }
2148
2149 private:
2150 mirror::ObjectArray<mirror::Class>* const arr_;
2151 int32_t index_;
2152};
2153
2154void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002155 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2156 // is avoiding duplicates.
2157 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002158 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002159 GetClassesInToVector accumulator;
2160 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002161 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002162 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002163 return;
2164 }
2165 }
2166 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002167 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002168 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002169 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002170 // We size the array assuming classes won't be added to the class table during the visit.
2171 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002172 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002173 size_t class_table_size;
2174 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002175 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002176 // Add 100 in case new classes get loaded when we are filling in the object array.
2177 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002178 }
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07002179 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002180 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002181 classes.Assign(
2182 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002183 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002184 GetClassInToObjectArray accumulator(classes.Get());
2185 VisitClasses(&accumulator);
2186 if (accumulator.Succeeded()) {
2187 break;
2188 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002189 }
2190 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2191 // If the class table shrank during creation of the clases array we expect null elements. If
2192 // the class table grew then the loop repeats. If classes are created after the loop has
2193 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002194 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002195 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002196 return;
2197 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002198 }
2199 }
2200}
2201
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002202ClassLinker::~ClassLinker() {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002203 mirror::Class::ResetClass();
2204 mirror::Constructor::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07002205 mirror::Field::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002206 mirror::Method::ResetClass();
2207 mirror::Reference::ResetClass();
2208 mirror::StackTraceElement::ResetClass();
2209 mirror::String::ResetClass();
2210 mirror::Throwable::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002211 mirror::BooleanArray::ResetArrayClass();
2212 mirror::ByteArray::ResetArrayClass();
2213 mirror::CharArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002214 mirror::Constructor::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002215 mirror::DoubleArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002216 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002217 mirror::FloatArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002218 mirror::Method::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002219 mirror::IntArray::ResetArrayClass();
2220 mirror::LongArray::ResetArrayClass();
2221 mirror::ShortArray::ResetArrayClass();
Narayan Kamathafa48272016-08-03 12:46:58 +01002222 mirror::MethodType::ResetClass();
2223 mirror::MethodHandleImpl::ResetClass();
Orion Hodsonc069a302017-01-18 09:23:12 +00002224 mirror::MethodHandlesLookup::ResetClass();
2225 mirror::CallSite::ResetClass();
Narayan Kamath000e1882016-10-24 17:14:25 +01002226 mirror::EmulatedStackFrame::ResetClass();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002227 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002228 for (const ClassLoaderData& data : class_loaders_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002229 DeleteClassLoader(self, data);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002230 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002231 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002232}
2233
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002234void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data) {
2235 Runtime* const runtime = Runtime::Current();
2236 JavaVMExt* const vm = runtime->GetJavaVM();
2237 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002238 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002239 if (runtime->GetJit() != nullptr) {
2240 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2241 if (code_cache != nullptr) {
2242 code_cache->RemoveMethodsIn(self, *data.allocator);
2243 }
2244 }
2245 delete data.allocator;
2246 delete data.class_table;
2247}
2248
Mathieu Chartiere401d142015-04-22 13:56:20 -07002249mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) {
Andreas Gampe542451c2016-07-26 09:02:02 -07002250 return down_cast<mirror::PointerArray*>(
2251 image_pointer_size_ == PointerSize::k64
2252 ? static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length))
2253 : static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002254}
2255
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002256mirror::DexCache* ClassLinker::AllocDexCache(ObjPtr<mirror::String>* out_location,
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002257 Thread* self,
2258 const DexFile& dex_file) {
2259 StackHandleScope<1> hs(self);
2260 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002261 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002262 GetClassRoot(kJavaLangDexCache)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002263 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002264 self->AssertPendingOOMException();
2265 return nullptr;
2266 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002267 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002268 if (location == nullptr) {
2269 self->AssertPendingOOMException();
2270 return nullptr;
2271 }
2272 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002273 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002274}
2275
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002276mirror::DexCache* ClassLinker::AllocAndInitializeDexCache(Thread* self,
2277 const DexFile& dex_file,
2278 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002279 ObjPtr<mirror::String> location = nullptr;
2280 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002281 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002282 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002283 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002284 mirror::DexCache::InitializeDexCache(self,
2285 dex_cache,
2286 location,
2287 &dex_file,
2288 linear_alloc,
2289 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002290 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002291 return dex_cache.Ptr();
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002292}
2293
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002294mirror::Class* ClassLinker::AllocClass(Thread* self,
2295 ObjPtr<mirror::Class> java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08002296 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002297 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002298 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002299 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002300 ObjPtr<mirror::Object> k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002301 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2302 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002303 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002304 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002305 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002306 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002307 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002308}
2309
Ian Rogers6fac4472014-02-25 17:01:10 -08002310mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002311 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002312}
2313
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002314mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002315 Thread* self,
2316 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002317 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2318 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002319}
2320
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002321mirror::Class* ClassLinker::EnsureResolved(Thread* self,
2322 const char* descriptor,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002323 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002324 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002325 if (kIsDebugBuild) {
2326 StackHandleScope<1> hs(self);
2327 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2328 Thread::PoisonObjectPointersIfDebug();
2329 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002330
2331 // For temporary classes we must wait for them to be retired.
2332 if (init_done_ && klass->IsTemp()) {
2333 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002334 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002335 ThrowEarlierClassFailure(klass);
2336 return nullptr;
2337 }
2338 StackHandleScope<1> hs(self);
2339 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2340 ObjectLock<mirror::Class> lock(self, h_class);
2341 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002342 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002343 lock.WaitIgnoringInterrupts();
2344 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002345 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002346 ThrowEarlierClassFailure(h_class.Get());
2347 return nullptr;
2348 }
2349 CHECK(h_class->IsRetired());
2350 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002351 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002352 }
2353
Brian Carlstromaded5f72011-10-07 17:15:04 -07002354 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002355 size_t index = 0;
2356 // Maximum number of yield iterations until we start sleeping.
2357 static const size_t kNumYieldIterations = 1000;
2358 // How long each sleep is in us.
2359 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002360 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002361 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002362 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002363 {
2364 ObjectTryLock<mirror::Class> lock(self, h_class);
2365 // Can not use a monitor wait here since it may block when returning and deadlock if another
2366 // thread has locked klass.
2367 if (lock.Acquired()) {
2368 // Check for circular dependencies between classes, the lock is required for SetStatus.
2369 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2370 ThrowClassCircularityError(h_class.Get());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002371 mirror::Class::SetStatus(h_class, mirror::Class::kStatusErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002372 return nullptr;
2373 }
2374 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002375 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002376 {
2377 // Handle wrapper deals with klass moving.
2378 ScopedThreadSuspension sts(self, kSuspended);
2379 if (index < kNumYieldIterations) {
2380 sched_yield();
2381 } else {
2382 usleep(kSleepDurationUS);
2383 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002384 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002385 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002386 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002387
Vladimir Marko72ab6842017-01-20 19:32:50 +00002388 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002389 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002390 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002391 }
2392 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002393 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002394 self->AssertNoPendingException();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002395 return klass.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002396}
2397
Ian Rogers68b56852014-08-29 20:19:11 -07002398typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2399
2400// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002401ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002402 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002403 for (const DexFile* dex_file : class_path) {
David Sehr9aa352e2016-09-15 18:13:52 -07002404 const DexFile::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002405 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002406 return ClassPathEntry(dex_file, dex_class_def);
2407 }
2408 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002409 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002410}
2411
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002412bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2413 Thread* self,
2414 const char* descriptor,
2415 size_t hash,
2416 Handle<mirror::ClassLoader> class_loader,
2417 ObjPtr<mirror::Class>* result) {
Andreas Gampef865ea92015-04-13 22:14:19 -07002418 // Termination case: boot class-loader.
2419 if (IsBootClassLoader(soa, class_loader.Get())) {
2420 // The boot class loader, search the boot class path.
2421 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2422 if (pair.second != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002423 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
Andreas Gampef865ea92015-04-13 22:14:19 -07002424 if (klass != nullptr) {
2425 *result = EnsureResolved(self, descriptor, klass);
2426 } else {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002427 *result = DefineClass(self,
2428 descriptor,
2429 hash,
2430 ScopedNullHandle<mirror::ClassLoader>(),
2431 *pair.first,
2432 *pair.second);
Andreas Gampef865ea92015-04-13 22:14:19 -07002433 }
2434 if (*result == nullptr) {
2435 CHECK(self->IsExceptionPending()) << descriptor;
2436 self->ClearException();
2437 }
Ian Rogers32427292014-11-19 14:05:21 -08002438 } else {
Andreas Gampef865ea92015-04-13 22:14:19 -07002439 *result = nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002440 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002441 return true;
2442 }
2443
2444 // Unsupported class-loader?
Mathieu Chartier0795f232016-09-27 18:43:30 -07002445 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
2446 class_loader->GetClass()) {
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002447 // PathClassLoader is the most common case, so it's the one we check first. For secondary dex
2448 // files, we also check DexClassLoader here.
2449 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_DexClassLoader) !=
2450 class_loader->GetClass()) {
2451 *result = nullptr;
2452 return false;
2453 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002454 }
2455
2456 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2457 StackHandleScope<4> hs(self);
2458 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002459 bool recursive_result = FindClassInBaseDexClassLoader(soa,
2460 self,
2461 descriptor,
2462 hash,
2463 h_parent,
2464 result);
Andreas Gampef865ea92015-04-13 22:14:19 -07002465
2466 if (!recursive_result) {
2467 // Something wrong up the chain.
2468 return false;
2469 }
2470
2471 if (*result != nullptr) {
2472 // Found the class up the chain.
2473 return true;
2474 }
2475
2476 // Handle this step.
2477 // Handle as if this is the child PathClassLoader.
2478 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2479 // We need to get the DexPathList and loop through it.
Andreas Gampe08883de2016-11-08 13:20:52 -08002480 ArtField* const cookie_field =
2481 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Andreas Gampef865ea92015-04-13 22:14:19 -07002482 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08002483 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002484 ObjPtr<mirror::Object> dex_path_list =
Andreas Gampe08883de2016-11-08 13:20:52 -08002485 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
2486 GetObject(class_loader.Get());
Andreas Gampef865ea92015-04-13 22:14:19 -07002487 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
2488 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002489 ObjPtr<mirror::Object> dex_elements_obj =
Andreas Gampe08883de2016-11-08 13:20:52 -08002490 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
Andreas Gampef865ea92015-04-13 22:14:19 -07002491 GetObject(dex_path_list);
2492 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2493 // at the mCookie which is a DexFile vector.
2494 if (dex_elements_obj != nullptr) {
2495 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2496 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2497 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002498 ObjPtr<mirror::Object> element = dex_elements->GetWithoutChecks(i);
Andreas Gampef865ea92015-04-13 22:14:19 -07002499 if (element == nullptr) {
2500 // Should never happen, fall back to java code to throw a NPE.
2501 break;
2502 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002503 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Andreas Gampef865ea92015-04-13 22:14:19 -07002504 if (dex_file != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002505 ObjPtr<mirror::LongArray> long_array = cookie_field->GetObject(dex_file)->AsLongArray();
Andreas Gampef865ea92015-04-13 22:14:19 -07002506 if (long_array == nullptr) {
2507 // This should never happen so log a warning.
2508 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002509 break;
2510 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002511 int32_t long_array_size = long_array->GetLength();
Mathieu Chartiere58991b2015-10-13 07:59:34 -07002512 // First element is the oat file.
2513 for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) {
Andreas Gampef865ea92015-04-13 22:14:19 -07002514 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
2515 long_array->GetWithoutChecks(j)));
David Sehr9aa352e2016-09-15 18:13:52 -07002516 const DexFile::ClassDef* dex_class_def =
2517 OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002518 if (dex_class_def != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002519 ObjPtr<mirror::Class> klass = DefineClass(self,
Mathieu Chartiere58991b2015-10-13 07:59:34 -07002520 descriptor,
2521 hash,
2522 class_loader,
2523 *cp_dex_file,
2524 *dex_class_def);
Andreas Gampef865ea92015-04-13 22:14:19 -07002525 if (klass == nullptr) {
2526 CHECK(self->IsExceptionPending()) << descriptor;
2527 self->ClearException();
2528 // TODO: Is it really right to break here, and not check the other dex files?
2529 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002530 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002531 *result = klass;
2532 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002533 }
2534 }
2535 }
2536 }
2537 }
Ian Rogers32427292014-11-19 14:05:21 -08002538 self->AssertNoPendingException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002539 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002540
2541 // Result is still null from the parent call, no need to set it again...
2542 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002543}
2544
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002545mirror::Class* ClassLinker::FindClass(Thread* self,
2546 const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002547 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002548 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002549 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002550 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002551 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002552 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002553 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2554 // for primitive classes that aren't backed by dex files.
2555 return FindPrimitiveClass(descriptor[0]);
2556 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002557 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002558 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002559 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002560 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002561 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002562 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002563 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002564 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002565 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002566 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002567 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002568 return DefineClass(self,
2569 descriptor,
2570 hash,
2571 ScopedNullHandle<mirror::ClassLoader>(),
2572 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002573 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002574 } else {
2575 // The boot class loader is searched ahead of the application class loader, failures are
2576 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2577 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002578 ObjPtr<mirror::Throwable> pre_allocated =
2579 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002580 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002581 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002582 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002583 }
2584 ObjPtr<mirror::Class> result_ptr;
2585 bool descriptor_equals;
2586 if (descriptor[0] == '[') {
2587 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2588 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2589 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2590 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002591 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002592 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002593 bool known_hierarchy =
2594 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2595 if (result_ptr != nullptr) {
2596 // The chain was understood and we found the class. We still need to add the class to
2597 // the class table to protect from racy programs that can try and redefine the path list
2598 // which would change the Class<?> returned for subsequent evaluation of const-class.
2599 DCHECK(known_hierarchy);
2600 DCHECK(result_ptr->DescriptorEquals(descriptor));
2601 descriptor_equals = true;
2602 } else {
2603 // Either the chain wasn't understood or the class wasn't found.
2604 //
2605 // If the chain was understood but we did not find the class, let the Java-side
2606 // rediscover all this and throw the exception with the right stack trace. Note that
2607 // the Java-side could still succeed for racy programs if another thread is actively
2608 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002609
Calin Juravleccd56952016-12-15 17:57:38 +00002610 if (!self->CanCallIntoJava()) {
2611 // Oops, we can't call into java so we can't run actual class-loader code.
2612 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002613 ObjPtr<mirror::Throwable> pre_allocated =
2614 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2615 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002616 return nullptr;
2617 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002618
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002619 // Inlined DescriptorToDot(descriptor) with extra validation.
2620 //
2621 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2622 // the DescriptorEquals() check below and give a confusing error message. For example,
2623 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2624 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2625 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2626 size_t descriptor_length = strlen(descriptor);
2627 if (UNLIKELY(descriptor[0] != 'L') ||
2628 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2629 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2630 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2631 return nullptr;
2632 }
2633 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2634 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2635
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002636 ScopedLocalRef<jobject> class_loader_object(
2637 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002638 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2639 {
2640 ScopedThreadStateChange tsc(self, kNative);
2641 ScopedLocalRef<jobject> class_name_object(
2642 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2643 if (class_name_object.get() == nullptr) {
2644 DCHECK(self->IsExceptionPending()); // OOME.
2645 return nullptr;
2646 }
2647 CHECK(class_loader_object.get() != nullptr);
2648 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2649 WellKnownClasses::java_lang_ClassLoader_loadClass,
2650 class_name_object.get()));
2651 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002652 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002653 // broken loader - throw NPE to be compatible with Dalvik
2654 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2655 class_name_string.c_str()).c_str());
2656 return nullptr;
2657 }
2658 result_ptr = soa.Decode<mirror::Class>(result.get());
2659 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002660 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002661 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002662 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002663
2664 if (self->IsExceptionPending()) {
2665 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2666 // However, to comply with the RI behavior, first check if another thread succeeded.
2667 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2668 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2669 self->ClearException();
2670 return EnsureResolved(self, descriptor, result_ptr);
2671 }
2672 return nullptr;
2673 }
2674
2675 // Try to insert the class to the class table, checking for mismatch.
2676 ObjPtr<mirror::Class> old;
2677 {
2678 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2679 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2680 old = class_table->Lookup(descriptor, hash);
2681 if (old == nullptr) {
2682 old = result_ptr; // For the comparison below, after releasing the lock.
2683 if (descriptor_equals) {
2684 class_table->InsertWithHash(result_ptr.Ptr(), hash);
2685 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get());
2686 } // else throw below, after releasing the lock.
2687 }
2688 }
2689 if (UNLIKELY(old != result_ptr)) {
2690 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2691 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2692 mirror::Class* loader_class = class_loader->GetClass();
2693 const char* loader_class_name =
2694 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2695 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2696 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2697 << DescriptorToDot(descriptor) << "\").";
2698 return EnsureResolved(self, descriptor, old);
2699 }
2700 if (UNLIKELY(!descriptor_equals)) {
2701 std::string result_storage;
2702 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2703 std::string loader_storage;
2704 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2705 ThrowNoClassDefFoundError(
2706 "Initiating class loader of type %s returned class %s instead of %s.",
2707 DescriptorToDot(loader_class_name).c_str(),
2708 DescriptorToDot(result_name).c_str(),
2709 DescriptorToDot(descriptor).c_str());
2710 return nullptr;
2711 }
2712 // success, return mirror::Class*
2713 return result_ptr.Ptr();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002714}
2715
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002716mirror::Class* ClassLinker::DefineClass(Thread* self,
2717 const char* descriptor,
2718 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002719 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002720 const DexFile& dex_file,
2721 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002722 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002723 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002724
Brian Carlstromaded5f72011-10-07 17:15:04 -07002725 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002726 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002727 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002728 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002729 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002730 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002731 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002732 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002733 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002734 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2735 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002736 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002737 klass.Assign(GetClassRoot(kJavaLangDexCache));
Alex Lightd6251582016-10-31 11:12:30 -07002738 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
2739 klass.Assign(GetClassRoot(kDalvikSystemClassExt));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002740 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002741 }
2742
Andreas Gampefa4333d2017-02-14 11:10:34 -08002743 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002744 // Allocate a class with the status of not ready.
2745 // Interface object should get the right size here. Regular class will
2746 // figure out the right size later and be replaced with one of the right
2747 // size when the class becomes resolved.
2748 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002749 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08002750 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002751 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07002752 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002753 }
Alex Lightb0f11922017-01-23 14:25:17 -08002754 // Get the real dex file. This will return the input if there aren't any callbacks or they do
2755 // nothing.
2756 DexFile const* new_dex_file = nullptr;
2757 DexFile::ClassDef const* new_class_def = nullptr;
2758 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
2759 // will only be called once.
2760 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
2761 klass,
2762 class_loader,
2763 dex_file,
2764 dex_class_def,
2765 &new_dex_file,
2766 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08002767 // Check to see if an exception happened during runtime callbacks. Return if so.
2768 if (self->IsExceptionPending()) {
2769 return nullptr;
2770 }
Alex Lightb0f11922017-01-23 14:25:17 -08002771 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002772 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002773 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002774 return nullptr;
2775 }
2776 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08002777 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07002778
Jeff Hao848f70a2014-01-15 13:49:50 -08002779 // Mark the string class by setting its access flag.
2780 if (UNLIKELY(!init_done_)) {
2781 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2782 klass->SetStringClass();
2783 }
2784 }
2785
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002786 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002787 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08002788 // Make sure we have a valid empty iftable even if there are errors.
2789 klass->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002790
Mathieu Chartier590fee92013-09-13 13:46:47 -07002791 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002792 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002793 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002794 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2795 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002796 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002797 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002798
Mathieu Chartierc7853442015-03-27 14:35:38 -07002799 // Load the fields and other things after we are inserted in the table. This is so that we don't
2800 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
2801 // other reason is that the field roots are only visited from the class table. So we need to be
2802 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08002803 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002804 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002805 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07002806 // An exception occured during load, set status to erroneous while holding klass' lock in case
2807 // notification is necessary.
2808 if (!klass->IsErroneous()) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002809 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002810 }
2811 return nullptr;
2812 }
2813
Brian Carlstromaded5f72011-10-07 17:15:04 -07002814 // Finish loading (if necessary) by finding parents
2815 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08002816 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002817 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002818 if (!klass->IsErroneous()) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002819 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002820 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002821 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002822 }
2823 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08002824
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07002825 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08002826 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08002827 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08002828
Brian Carlstromaded5f72011-10-07 17:15:04 -07002829 // Link the class (if necessary)
2830 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002831 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002832 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002833
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002834 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002835 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002836 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002837 if (!klass->IsErroneous()) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002838 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002839 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002840 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002841 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002842 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002843 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00002844 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002845
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002846 // Instrumentation may have updated entrypoints for all methods of all
2847 // classes. However it could not update methods of this class while we
2848 // were loading it. Now the class is resolved, we can update entrypoints
2849 // as required by instrumentation.
2850 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2851 // We must be in the kRunnable state to prevent instrumentation from
2852 // suspending all threads to update entrypoints while we are doing it
2853 // for this class.
2854 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002855 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002856 }
2857
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002858 /*
2859 * We send CLASS_PREPARE events to the debugger from here. The
2860 * definition of "preparation" is creating the static fields for a
2861 * class and initializing them to the standard default values, but not
2862 * executing any code (that comes later, during "initialization").
2863 *
2864 * We did the static preparation in LinkClass.
2865 *
2866 * The class has been prepared and resolved but possibly not yet verified
2867 * at this point.
2868 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08002869 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002870
Tamas Berghammer160e6df2016-01-05 14:29:02 +00002871 // Notify native debugger of the new class and its layout.
2872 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
2873
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002874 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002875}
2876
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002877uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2878 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002879 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002880 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002881 size_t num_8 = 0;
2882 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002883 size_t num_32 = 0;
2884 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002885 if (class_data != nullptr) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002886 // We allow duplicate definitions of the same field in a class_data_item
2887 // but ignore the repeated indexes here, b/21868015.
2888 uint32_t last_field_idx = DexFile::kDexNoIndex;
Ian Rogers0571d352011-11-03 19:51:38 -07002889 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002890 uint32_t field_idx = it.GetMemberIndex();
2891 // Ordering enforced by DexFileVerifier.
2892 DCHECK(last_field_idx == DexFile::kDexNoIndex || last_field_idx <= field_idx);
2893 if (UNLIKELY(field_idx == last_field_idx)) {
2894 continue;
2895 }
2896 last_field_idx = field_idx;
2897 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002898 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002899 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002900 switch (c) {
2901 case 'L':
2902 case '[':
2903 num_ref++;
2904 break;
2905 case 'J':
2906 case 'D':
2907 num_64++;
2908 break;
2909 case 'I':
2910 case 'F':
2911 num_32++;
2912 break;
2913 case 'S':
2914 case 'C':
2915 num_16++;
2916 break;
2917 case 'B':
2918 case 'Z':
2919 num_8++;
2920 break;
2921 default:
2922 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002923 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002924 }
2925 }
2926 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002927 return mirror::Class::ComputeClassSize(false,
2928 0,
2929 num_8,
2930 num_16,
2931 num_32,
2932 num_64,
2933 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002934 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002935}
2936
TDYa12785321912012-04-01 15:24:56 -07002937// Special case to get oat code without overwriting a trampoline.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002938const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07002939 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00002940 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002941 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002942 }
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002943 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
2944 if (code != nullptr) {
2945 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08002946 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002947 if (method->IsNative()) {
2948 // No code and native? Use generic trampoline.
2949 return GetQuickGenericJniStub();
2950 }
2951 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07002952}
2953
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002954bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
2955 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
2956 return false;
2957 }
2958
Elliott Hughes956af0f2014-12-11 14:34:28 -08002959 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002960 return true;
2961 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002962
2963 Runtime* runtime = Runtime::Current();
2964 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
2965 if (instr->InterpretOnly()) {
2966 return true;
2967 }
2968
2969 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
2970 // Doing this check avoids doing compiled/interpreter transitions.
2971 return true;
2972 }
2973
2974 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
2975 // Force the use of interpreter when it is required by the debugger.
2976 return true;
2977 }
2978
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002979 if (runtime->IsJavaDebuggable()) {
2980 // For simplicity, we ignore precompiled code and go to the interpreter
2981 // assuming we don't already have jitted code.
2982 // We could look at the oat file where `quick_code` is being defined,
2983 // and check whether it's been compiled debuggable, but we decided to
2984 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08002985 jit::Jit* jit = Runtime::Current()->GetJit();
2986 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
2987 }
2988
David Srbeckyf4480162016-03-16 00:06:24 +00002989 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01002990 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00002991 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00002992 // since we want to JIT it (at first use) with extra stackmaps for native
2993 // debugging. We keep however all AOT code from the boot image,
2994 // since the JIT-at-first-use is blocking and would result in non-negligible
2995 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00002996 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002997 }
2998
2999 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003000}
3001
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003002void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07003003 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003004 if (klass->NumDirectMethods() == 0) {
3005 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003006 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003007 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003008 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003009 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003010 return; // OAT file unavailable.
3011 }
Ian Rogers19846512012-02-24 11:42:47 -08003012 }
Alex Light64ad14d2014-08-19 14:23:13 -07003013
Mathieu Chartierf8322842014-05-16 10:59:25 -07003014 const DexFile& dex_file = klass->GetDexFile();
3015 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07003016 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07003017 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07003018 // There should always be class data if there were direct methods.
David Sehr709b0702016-10-13 09:12:37 -07003019 CHECK(class_data != nullptr) << klass->PrettyDescriptor();
Ian Rogers19846512012-02-24 11:42:47 -08003020 ClassDataItemIterator it(dex_file, class_data);
3021 // Skip fields
3022 while (it.HasNextStaticField()) {
3023 it.Next();
3024 }
3025 while (it.HasNextInstanceField()) {
3026 it.Next();
3027 }
Ian Rogers97b52f82014-08-14 11:34:07 -07003028 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003029 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3030 klass->GetDexClassDefIndex(),
3031 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003032 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003033 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003034 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003035 if (!method->IsStatic()) {
3036 // Only update static methods.
3037 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003038 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003039 const void* quick_code = nullptr;
3040 if (has_oat_class) {
3041 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003042 quick_code = oat_method.GetQuickCode();
3043 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003044 // Check whether the method is native, in which case it's generic JNI.
3045 if (quick_code == nullptr && method->IsNative()) {
3046 quick_code = GetQuickGenericJniStub();
3047 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003048 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003049 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003050 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003051 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003052 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003053 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003054}
3055
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003056// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3057// method. Should only be called on non-invokable methods.
3058inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003059 DCHECK(method != nullptr);
3060 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003061 method->SetEntryPointFromQuickCompiledCodePtrSize(
3062 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3063 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003064}
3065
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003066static void LinkCode(ClassLinker* class_linker,
3067 ArtMethod* method,
3068 const OatFile::OatClass* oat_class,
3069 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003070 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003071 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003072 // The following code only applies to a non-compiler runtime.
3073 return;
3074 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003075 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003076 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003077 if (oat_class != nullptr) {
3078 // Every kind of method should at least get an invoke stub from the oat_method.
3079 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003080 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003081 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003082 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003083
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003084 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003085 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003086 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003087
Alex Light9139e002015-10-09 15:59:48 -07003088 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003089 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003090 return;
3091 }
Ian Rogers19846512012-02-24 11:42:47 -08003092
3093 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003094 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003095 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3096 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003097 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003098 } else if (quick_code == nullptr && method->IsNative()) {
3099 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003100 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003101 // Set entry point from compiled code if there's no code or in interpreter only mode.
3102 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003103 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003104
Ian Rogers62d6c772013-02-27 08:32:07 -08003105 if (method->IsNative()) {
3106 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003107 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003108
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003109 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003110 // We have a native method here without code. Then it should have either the generic JNI
3111 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3112 // TODO: this doesn't handle all the cases where trampolines may be installed.
3113 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003114 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3115 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003116 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003117 }
3118}
3119
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003120void ClassLinker::SetupClass(const DexFile& dex_file,
3121 const DexFile::ClassDef& dex_class_def,
3122 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003123 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003124 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003125 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003126 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003127 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003128 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003129
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003130 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07003131 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003132 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003133 klass->SetAccessFlags(access_flags);
3134 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003135 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003136 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003137
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003138 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003139 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003140}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003141
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003142void ClassLinker::LoadClass(Thread* self,
3143 const DexFile& dex_file,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003144 const DexFile::ClassDef& dex_class_def,
3145 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07003146 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003147 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07003148 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07003149 }
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003150 LoadClassMembers(self, dex_file, class_data, klass);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003151}
3152
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003153LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3154 LinearAlloc* allocator,
3155 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003156 if (length == 0) {
3157 return nullptr;
3158 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003159 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3160 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3161 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003162 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003163 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003164 CHECK(ret != nullptr);
3165 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3166 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003167}
3168
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003169LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3170 LinearAlloc* allocator,
3171 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003172 if (length == 0) {
3173 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003174 }
Vladimir Marko14632852015-08-17 12:07:23 +01003175 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3176 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003177 const size_t storage_size =
3178 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003179 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003180 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003181 CHECK(ret != nullptr);
3182 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003183 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003184 }
3185 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003186}
3187
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003188LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003189 if (class_loader == nullptr) {
3190 return Runtime::Current()->GetLinearAlloc();
3191 }
3192 LinearAlloc* allocator = class_loader->GetAllocator();
3193 DCHECK(allocator != nullptr);
3194 return allocator;
3195}
3196
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003197LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003198 if (class_loader == nullptr) {
3199 return Runtime::Current()->GetLinearAlloc();
3200 }
3201 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3202 LinearAlloc* allocator = class_loader->GetAllocator();
3203 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003204 RegisterClassLoader(class_loader);
3205 allocator = class_loader->GetAllocator();
3206 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003207 }
3208 return allocator;
3209}
3210
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003211void ClassLinker::LoadClassMembers(Thread* self,
3212 const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07003213 const uint8_t* class_data,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003214 Handle<mirror::Class> klass) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003215 {
3216 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3217 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003218 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003219 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003220 // We allow duplicate definitions of the same field in a class_data_item
3221 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003222 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003223 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003224 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3225 allocator,
3226 it.NumStaticFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003227 size_t num_sfields = 0;
3228 uint32_t last_field_idx = 0u;
3229 for (; it.HasNextStaticField(); it.Next()) {
3230 uint32_t field_idx = it.GetMemberIndex();
3231 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3232 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
3233 DCHECK_LT(num_sfields, it.NumStaticFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003234 LoadField(it, klass, &sfields->At(num_sfields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003235 ++num_sfields;
3236 last_field_idx = field_idx;
3237 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003238 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003239
Mathieu Chartiere401d142015-04-22 13:56:20 -07003240 // Load instance fields.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003241 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3242 allocator,
3243 it.NumInstanceFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003244 size_t num_ifields = 0u;
3245 last_field_idx = 0u;
3246 for (; it.HasNextInstanceField(); it.Next()) {
3247 uint32_t field_idx = it.GetMemberIndex();
3248 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3249 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
3250 DCHECK_LT(num_ifields, it.NumInstanceFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003251 LoadField(it, klass, &ifields->At(num_ifields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003252 ++num_ifields;
3253 last_field_idx = field_idx;
3254 }
3255 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003256
Vladimir Marko23682bf2015-06-24 14:28:03 +01003257 if (UNLIKELY(num_sfields != it.NumStaticFields()) ||
3258 UNLIKELY(num_ifields != it.NumInstanceFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003259 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Vladimir Marko23682bf2015-06-24 14:28:03 +01003260 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields()
3261 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003262 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3263 if (sfields != nullptr) {
3264 sfields->SetSize(num_sfields);
3265 }
3266 if (ifields != nullptr) {
3267 ifields->SetSize(num_ifields);
3268 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003269 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003270 // Set the field arrays.
3271 klass->SetSFieldsPtr(sfields);
3272 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003273 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003274 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
3275 // Load methods.
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003276 bool has_oat_class = false;
3277 const OatFile::OatClass oat_class =
3278 (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler())
3279 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3280 : OatFile::OatClass::Invalid();
3281 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
Alex Lighte64300b2015-12-15 15:02:47 -08003282 klass->SetMethodsPtr(
3283 AllocArtMethodArray(self, allocator, it.NumDirectMethods() + it.NumVirtualMethods()),
3284 it.NumDirectMethods(),
3285 it.NumVirtualMethods());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003286 size_t class_def_method_index = 0;
3287 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
3288 size_t last_class_def_method_index = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08003289 // TODO These should really use the iterators.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003290 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
3291 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003292 LoadMethod(dex_file, it, klass, method);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003293 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003294 uint32_t it_method_index = it.GetMemberIndex();
3295 if (last_dex_method_index == it_method_index) {
3296 // duplicate case
3297 method->SetMethodIndex(last_class_def_method_index);
3298 } else {
3299 method->SetMethodIndex(class_def_method_index);
3300 last_dex_method_index = it_method_index;
3301 last_class_def_method_index = class_def_method_index;
3302 }
3303 class_def_method_index++;
3304 }
3305 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
3306 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003307 LoadMethod(dex_file, it, klass, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003308 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003309 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003310 class_def_method_index++;
3311 }
3312 DCHECK(!it.HasNext());
Ian Rogers0571d352011-11-03 19:51:38 -07003313 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003314 // Ensure that the card is marked so that remembered sets pick up native roots.
3315 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003316 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003317}
3318
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003319void ClassLinker::LoadField(const ClassDataItemIterator& it,
3320 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003321 ArtField* dst) {
3322 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003323 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003324 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07003325 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003326}
3327
Mathieu Chartier268764d2016-09-13 12:09:38 -07003328void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003329 const ClassDataItemIterator& it,
3330 Handle<mirror::Class> klass,
3331 ArtMethod* dst) {
Ian Rogers19846512012-02-24 11:42:47 -08003332 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08003333 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003334 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003335
Mathieu Chartier268764d2016-09-13 12:09:38 -07003336 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003337 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003338 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07003339 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003340
Vladimir Marko05792b92015-08-03 11:56:49 +01003341 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods(), image_pointer_size_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003342
Andreas Gampe51829322014-08-25 15:05:04 -07003343 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07003344
Ian Rogersdfb325e2013-10-30 01:00:44 -07003345 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003346 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003347 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3348 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003349 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003350 klass->SetFinalizable();
3351 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003352 std::string temp;
3353 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003354 // The Enum class declares a "final" finalize() method to prevent subclasses from
3355 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3356 // subclasses, so we exclude it here.
3357 // We also want to avoid setting the flag on Object, where we know that finalize() is
3358 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003359 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3360 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003361 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003362 }
3363 }
3364 }
3365 } else if (method_name[0] == '<') {
3366 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003367 bool is_init = (strcmp("<init>", method_name) == 0);
3368 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003369 if (UNLIKELY(!is_init && !is_clinit)) {
3370 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3371 } else {
3372 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3373 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003374 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003375 access_flags |= kAccConstructor;
3376 }
3377 }
3378 }
3379 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003380}
3381
Ian Rogers7b078e82014-09-10 14:44:24 -07003382void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003383 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003384 self,
3385 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003386 Runtime::Current()->GetLinearAlloc());
3387 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003388 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003389}
3390
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003391void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003392 ObjPtr<mirror::DexCache> dex_cache) {
3393 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003394 boot_class_path_.push_back(&dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003395 RegisterBootClassPathDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003396}
3397
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003398void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003399 ObjPtr<mirror::DexCache> dex_cache,
3400 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003401 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003402 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003403 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003404 // For app images, the dex cache location may be a suffix of the dex file location since the
3405 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003406 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3407 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003408 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3409 std::string dex_file_location = dex_file.GetLocation();
3410 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003411 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003412 // Take suffix.
3413 const std::string dex_file_suffix = dex_file_location.substr(
3414 dex_file_location.length() - dex_cache_length,
3415 dex_cache_length);
3416 // Example dex_cache location is SettingsProvider.apk and
3417 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003418 CHECK_EQ(dex_cache_location, dex_file_suffix);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003419 // Clean up pass to remove null dex caches.
3420 // Null dex caches can occur due to class unloading and we are lazily removing null entries.
3421 JavaVMExt* const vm = self->GetJniEnv()->vm;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003422 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3423 DexCacheData data = *it;
3424 if (self->IsJWeakCleared(data.weak_root)) {
3425 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003426 it = dex_caches_.erase(it);
3427 } else {
3428 ++it;
3429 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003430 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003431 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003432 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003433 DexCacheData data;
3434 data.weak_root = dex_cache_jweak;
3435 data.dex_file = dex_cache->GetDexFile();
Vladimir Marko942fd312017-01-16 20:52:19 +00003436 data.resolved_methods = dex_cache->GetResolvedMethods();
Vladimir Markocd556b02017-02-03 11:47:34 +00003437 data.class_table = ClassTableForClassLoader(class_loader);
3438 DCHECK(data.class_table != nullptr);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003439 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003440}
3441
Vladimir Markocd556b02017-02-03 11:47:34 +00003442ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3443 return data.IsValid()
3444 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3445 : nullptr;
3446}
3447
3448ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3449 Thread* self,
3450 ObjPtr<mirror::DexCache> dex_cache,
3451 const DexCacheData& data,
3452 ObjPtr<mirror::ClassLoader> class_loader) {
3453 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3454 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3455 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3456 "Attempt to register dex file %s with multiple class loaders",
3457 data.dex_file->GetLocation().c_str());
3458 return nullptr;
3459 }
3460 return dex_cache;
3461}
3462
3463ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3464 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003465 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003466 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003467 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003468 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003469 old_data = FindDexCacheDataLocked(dex_file);
3470 }
3471 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3472 if (old_dex_cache != nullptr) {
3473 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003474 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003475 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3476 DCHECK(linear_alloc != nullptr);
3477 ClassTable* table;
3478 {
3479 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3480 table = InsertClassTableForClassLoader(class_loader);
3481 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003482 // Don't alloc while holding the lock, since allocation may need to
3483 // suspend all threads and another thread may need the dex_lock_ to
3484 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003485 StackHandleScope<3> hs(self);
3486 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003487 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003488 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3489 self,
3490 dex_file)));
3491 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003492 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003493 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003494 old_data = FindDexCacheDataLocked(dex_file);
3495 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003496 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003497 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3498 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3499 // that the arrays are null.
3500 mirror::DexCache::InitializeDexCache(self,
3501 h_dex_cache.Get(),
3502 h_location.Get(),
3503 &dex_file,
3504 linear_alloc,
3505 image_pointer_size_);
3506 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003507 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003508 }
3509 if (old_dex_cache != nullptr) {
3510 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3511 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003512 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003513 self->ClearException();
3514 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3515 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3516 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003517 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003518 self->AssertPendingOOMException();
3519 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003520 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003521 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003522 if (h_class_loader.Get() != nullptr) {
3523 // Since we added a strong root to the class table, do the write barrier as required for
3524 // remembered sets and generational GCs.
3525 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(h_class_loader.Get());
3526 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003527 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003528}
3529
Vladimir Markocd556b02017-02-03 11:47:34 +00003530void ClassLinker::RegisterBootClassPathDexFile(const DexFile& dex_file,
3531 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003532 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003533 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader */ nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003534}
3535
Vladimir Markocd556b02017-02-03 11:47:34 +00003536bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003537 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003538 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003539}
3540
Vladimir Markocd556b02017-02-03 11:47:34 +00003541ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3542 ReaderMutexLock mu(self, *Locks::dex_lock_);
3543 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, FindDexCacheDataLocked(dex_file));
3544 if (dex_cache != nullptr) {
3545 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003546 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003547 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003548 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003549 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003550 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003551 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003552 }
Andreas Gampe37c58462017-03-27 15:14:27 -07003553 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08003554 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003555}
3556
Vladimir Markocd556b02017-02-03 11:47:34 +00003557ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3558 const DexFile* dex_file = dex_cache->GetDexFile();
3559 DCHECK(dex_file != nullptr);
3560 ReaderMutexLock mu(self, *Locks::dex_lock_);
3561 // Search assuming unique-ness of dex file.
3562 for (const DexCacheData& data : dex_caches_) {
3563 // Avoid decoding (and read barriers) other unrelated dex caches.
3564 if (data.dex_file == dex_file) {
3565 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3566 if (registered_dex_cache != nullptr) {
3567 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3568 return data.class_table;
3569 }
3570 }
3571 }
3572 return nullptr;
3573}
3574
3575ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3576 // Search assuming unique-ness of dex file.
3577 for (const DexCacheData& data : dex_caches_) {
3578 // Avoid decoding (and read barriers) other unrelated dex caches.
3579 if (data.dex_file == &dex_file) {
3580 return data;
3581 }
3582 }
3583 return DexCacheData();
3584}
3585
Mathieu Chartiere401d142015-04-22 13:56:20 -07003586void ClassLinker::FixupDexCaches(ArtMethod* resolution_method) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003587 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003588 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003589 for (const DexCacheData& data : dex_caches_) {
3590 if (!self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07003591 ObjPtr<mirror::DexCache> dex_cache = ObjPtr<mirror::DexCache>::DownCast(
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003592 self->DecodeJObject(data.weak_root));
3593 if (dex_cache != nullptr) {
3594 dex_cache->Fixup(resolution_method, image_pointer_size_);
3595 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003596 }
Ian Rogers19846512012-02-24 11:42:47 -08003597 }
3598}
3599
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003600mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08003601 ObjPtr<mirror::Class> klass =
3602 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003603 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003604 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003605 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003606 }
3607 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003608}
3609
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003610mirror::Class* ClassLinker::InitializePrimitiveClass(ObjPtr<mirror::Class> primitive_class,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003611 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003612 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003613 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003614 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003615 StackHandleScope<1> hs(self);
3616 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003617 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003618 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3619 h_class->SetPrimitiveType(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003620 h_class->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003621 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003622 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003623 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3624 h_class.Get(),
3625 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003626 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003627 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003628}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003629
Brian Carlstrombe977852011-07-19 14:54:54 -07003630// Create an array class (i.e. the class object for the array, not the
3631// array itself). "descriptor" looks like "[C" or "[[[[B" or
3632// "[Ljava/lang/String;".
3633//
3634// If "descriptor" refers to an array of primitives, look up the
3635// primitive type's internally-generated class object.
3636//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003637// "class_loader" is the class loader of the class that's referring to
3638// us. It's used to ensure that we're looking for the element type in
3639// the right context. It does NOT become the class loader for the
3640// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003641//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003642// Returns null with an exception raised on failure.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003643mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003644 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003645 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003646 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003647 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003648 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3649 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003650 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003651 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003652 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003653 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3654 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003655 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003656 DCHECK(self->IsExceptionPending());
3657 return nullptr;
3658 } else {
3659 self->ClearException();
3660 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003661 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003662 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3663 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3664 return nullptr;
3665 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003666 // See if the component type is already loaded. Array classes are
3667 // always associated with the class loader of their underlying
3668 // element type -- an array of Strings goes with the loader for
3669 // java/lang/String -- so we need to look for it there. (The
3670 // caller should have checked for the existence of the class
3671 // before calling here, but they did so with *their* class loader,
3672 // not the component type's loader.)
3673 //
3674 // If we find it, the caller adds "loader" to the class' initiating
3675 // loader list, which should prevent us from going through this again.
3676 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003677 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003678 // are the same, because our caller (FindClass) just did the
3679 // lookup. (Even if we get this wrong we still have correct behavior,
3680 // because we effectively do this lookup again when we add the new
3681 // class to the hash table --- necessary because of possible races with
3682 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003683 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003684 ObjPtr<mirror::Class> new_class =
3685 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003686 if (new_class != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003687 return new_class.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003688 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003689 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003690
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003691 // Fill out the fields in the Class.
3692 //
3693 // It is possible to execute some methods against arrays, because
3694 // all arrays are subclasses of java_lang_Object_, so we need to set
3695 // up a vtable. We can just point at the one in java_lang_Object_.
3696 //
3697 // Array classes are simple enough that we don't need to do a full
3698 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003699 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003700 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003701 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003702 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003703 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003704 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003705 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003706 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003707 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003708 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003709 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003710 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003711 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07003712 } else if (strcmp(descriptor, "[J") == 0) {
3713 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003714 }
3715 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003716 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003717 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003718 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003719 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003720 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003721 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003722 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003723 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003724 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003725 DCHECK(new_class->GetComponentType() != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003726 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003727 new_class->SetSuperClass(java_lang_Object);
3728 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003729 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003730 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07003731 if (component_type->IsPrimitive()) {
3732 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
3733 } else {
3734 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
3735 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003736 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00003737 new_class->PopulateEmbeddedVTable(image_pointer_size_);
3738 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
3739 new_class->SetImt(object_imt, image_pointer_size_);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003740 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003741 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003742 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003743
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003744 // All arrays have java/lang/Cloneable and java/io/Serializable as
3745 // interfaces. We need to set that up here, so that stuff like
3746 // "instanceof" works right.
3747 //
3748 // Note: The GC could run during the call to FindSystemClass,
3749 // so we need to make sure the class object is GC-valid while we're in
3750 // there. Do this by clearing the interface list so the GC will just
3751 // think that the entries are null.
3752
3753
3754 // Use the single, global copies of "interfaces" and "iftable"
3755 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003756 {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003757 ObjPtr<mirror::IfTable> array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003758 CHECK(array_iftable != nullptr);
3759 new_class->SetIfTable(array_iftable);
3760 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003761
Elliott Hughes00626c22013-06-14 15:04:14 -07003762 // Inherit access flags from the component type.
3763 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3764 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3765 access_flags &= kAccJavaFlagsMask;
3766 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003767 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003768 access_flags |= kAccAbstract | kAccFinal;
3769 access_flags &= ~kAccInterface;
3770
3771 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003772
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003773 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003774 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003775 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
3776 // duplicate events in case of races. Array classes don't really follow dedicated
3777 // load and prepare, anyways.
3778 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
3779 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
3780
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003781 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003782 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003783 }
3784 // Another thread must have loaded the class after we
3785 // started but before we finished. Abandon what we've
3786 // done.
3787 //
3788 // (Yes, this happens.)
3789
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003790 return existing.Ptr();
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003791}
3792
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003793mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003794 switch (type) {
3795 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003796 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003797 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003798 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003799 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003800 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003801 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003802 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003803 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003804 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003805 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003806 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003807 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003808 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003809 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003810 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003811 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003812 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003813 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003814 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003815 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003816 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003817 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003818 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003819}
3820
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003821mirror::Class* ClassLinker::InsertClass(const char* descriptor, ObjPtr<mirror::Class> klass, size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003822 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003823 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003824 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003825 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003826 source += " from ";
3827 source += dex_cache->GetLocation()->ToModifiedUtf8();
3828 }
3829 LOG(INFO) << "Loaded class " << descriptor << source;
3830 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003831 {
3832 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003833 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07003834 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003835 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003836 if (existing != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003837 return existing.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07003838 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003839 VerifyObject(klass);
3840 class_table->InsertWithHash(klass, hash);
3841 if (class_loader != nullptr) {
3842 // This is necessary because we need to have the card dirtied for remembered sets.
3843 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3844 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00003845 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07003846 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003847 }
3848 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003849 if (kIsDebugBuild) {
3850 // Test that copied methods correctly can find their holder.
3851 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
3852 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
3853 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08003854 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003855 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003856}
3857
Vladimir Marko1998cd02017-01-13 13:02:58 +00003858void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003859 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3860 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
3861 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
3862 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00003863 }
3864}
3865
Alex Lighte64300b2015-12-15 15:02:47 -08003866// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003867void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08003868 LengthPrefixedArray<ArtMethod>* new_methods) {
3869 klass->SetMethodsPtrUnchecked(new_methods,
3870 klass->NumDirectMethods(),
3871 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003872 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003873 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003874}
3875
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003876mirror::Class* ClassLinker::LookupClass(Thread* self,
3877 const char* descriptor,
3878 size_t hash,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003879 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01003880 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3881 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3882 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003883 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01003884 if (result != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003885 return result.Ptr();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003886 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003887 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01003888 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003889}
3890
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003891class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
3892 public:
3893 explicit MoveClassTableToPreZygoteVisitor() {}
3894
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003895 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003896 REQUIRES(Locks::classlinker_classes_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003897 REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003898 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07003899 if (class_table != nullptr) {
3900 class_table->FreezeSnapshot();
3901 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003902 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003903};
3904
3905void ClassLinker::MoveClassTableToPreZygote() {
3906 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07003907 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003908 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003909 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003910}
3911
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003912// Look up classes by hash and descriptor and put all matching ones in the result array.
3913class LookupClassesVisitor : public ClassLoaderVisitor {
3914 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003915 LookupClassesVisitor(const char* descriptor,
3916 size_t hash,
3917 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003918 : descriptor_(descriptor),
3919 hash_(hash),
3920 result_(result) {}
3921
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003922 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003923 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003924 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003925 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003926 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
3927 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003928 result_->push_back(klass);
3929 }
3930 }
3931
3932 private:
3933 const char* const descriptor_;
3934 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003935 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003936};
3937
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003938void ClassLinker::LookupClasses(const char* descriptor,
3939 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003940 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003941 Thread* const self = Thread::Current();
3942 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003943 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07003944 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003945 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003946 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003947 result.push_back(klass);
3948 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003949 LookupClassesVisitor visitor(descriptor, hash, &result);
3950 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003951}
3952
Alex Lightf1f10492015-10-07 16:08:36 -07003953bool ClassLinker::AttemptSupertypeVerification(Thread* self,
3954 Handle<mirror::Class> klass,
3955 Handle<mirror::Class> supertype) {
3956 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003957 DCHECK(klass != nullptr);
3958 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07003959
Alex Lightf1f10492015-10-07 16:08:36 -07003960 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
3961 VerifyClass(self, supertype);
3962 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00003963
3964 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
3965 // The supertype is either verified, or we soft failed at AOT time.
3966 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07003967 return true;
3968 }
3969 // If we got this far then we have a hard failure.
3970 std::string error_msg =
3971 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07003972 klass->PrettyDescriptor().c_str(),
3973 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07003974 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003975 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07003976 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003977 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003978 // Set during VerifyClass call (if at all).
3979 self->ClearException();
3980 }
3981 // Change into a verify error.
3982 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08003983 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07003984 self->GetException()->SetCause(cause.Get());
3985 }
3986 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
3987 if (Runtime::Current()->IsAotCompiler()) {
3988 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3989 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07003990 // Need to grab the lock to change status.
3991 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko72ab6842017-01-20 19:32:50 +00003992 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07003993 return false;
3994}
3995
Andreas Gampecc1b5352016-12-01 16:58:38 -08003996// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
3997// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
3998// before.
3999static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
4000 REQUIRES_SHARED(Locks::mutator_lock_) {
4001 if (!klass->WasVerificationAttempted()) {
4002 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
4003 klass->SetVerificationAttempted();
4004 }
4005}
4006
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004007verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004008 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004009 {
4010 // TODO: assert that the monitor on the Class is held
4011 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004012
Andreas Gampe884f3b82016-03-30 19:52:58 -07004013 // Is somebody verifying this now?
4014 mirror::Class::Status old_status = klass->GetStatus();
4015 while (old_status == mirror::Class::kStatusVerifying ||
4016 old_status == mirror::Class::kStatusVerifyingAtRuntime) {
4017 lock.WaitIgnoringInterrupts();
Alex Light06039ba2016-04-04 13:23:14 -07004018 CHECK(klass->IsErroneous() || (klass->GetStatus() > old_status))
David Sehr709b0702016-10-13 09:12:37 -07004019 << "Class '" << klass->PrettyClass()
4020 << "' performed an illegal verification state transition from " << old_status
4021 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004022 old_status = klass->GetStatus();
4023 }
jeffhao98eacac2011-09-14 16:11:53 -07004024
Andreas Gampe884f3b82016-03-30 19:52:58 -07004025 // The class might already be erroneous, for example at compile time if we attempted to verify
4026 // this class as a parent to another.
4027 if (klass->IsErroneous()) {
4028 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004029 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004030 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004031
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004032 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004033 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004034 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004035 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004036 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004037
4038 // For AOT, don't attempt to re-verify if we have already found we should
4039 // verify at runtime.
4040 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004041 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004042 }
jeffhao98eacac2011-09-14 16:11:53 -07004043
Andreas Gampe884f3b82016-03-30 19:52:58 -07004044 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
4045 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
4046 } else {
4047 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004048 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004049 CHECK(!Runtime::Current()->IsAotCompiler());
4050 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
4051 }
4052
4053 // Skip verification if disabled.
4054 if (!Runtime::Current()->IsVerificationEnabled()) {
4055 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004056 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004057 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004058 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004059 }
4060
Ian Rogers9ffb0392012-09-10 11:56:50 -07004061 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004062 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004063 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4064 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004065 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004066 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004067 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004068 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004069
Alex Lightf1f10492015-10-07 16:08:36 -07004070 // Verify all default super-interfaces.
4071 //
4072 // (1) Don't bother if the superclass has already had a soft verification failure.
4073 //
4074 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4075 // recursive initialization by themselves. This is because when an interface is initialized
4076 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4077 // but choose not to for an optimization. If the interfaces is being verified due to a class
4078 // initialization (which would need all the default interfaces to be verified) the class code
4079 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004080 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004081 && !klass->IsInterface()) { // See (2)
4082 int32_t iftable_count = klass->GetIfTableCount();
4083 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4084 // Loop through all interfaces this class has defined. It doesn't matter the order.
4085 for (int32_t i = 0; i < iftable_count; i++) {
4086 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004087 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004088 // We only care if we have default interfaces and can skip if we are already verified...
4089 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4090 continue;
4091 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4092 // We had a hard failure while verifying this interface. Just return immediately.
4093 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004094 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004095 } else if (UNLIKELY(!iface->IsVerified())) {
4096 // We softly failed to verify the iface. Stop checking and clean up.
4097 // Put the iface into the supertype handle so we know what caused us to fail.
4098 supertype.Assign(iface.Get());
4099 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004100 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004101 }
4102 }
4103
Alex Lightf1f10492015-10-07 16:08:36 -07004104 // At this point if verification failed, then supertype is the "first" supertype that failed
4105 // verification (without a specific order). If verification succeeded, then supertype is either
4106 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004107 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004108 supertype.Get() == klass->GetSuperClass() ||
4109 !supertype->IsVerified());
4110
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004111 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004112 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004113 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004114 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004115 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4116 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004117 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4118 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004119
Ian Rogers62d6c772013-02-27 08:32:07 -08004120 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004121 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004122 if (!preverified) {
Andreas Gampe53e32d12015-12-09 21:03:23 -08004123 Runtime* runtime = Runtime::Current();
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004124 verifier_failure = verifier::MethodVerifier::VerifyClass(self,
4125 klass.Get(),
Andreas Gampe53e32d12015-12-09 21:03:23 -08004126 runtime->GetCompilerCallbacks(),
4127 runtime->IsAotCompiler(),
Andreas Gampe7fe30232016-03-25 16:58:00 -07004128 log_level,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004129 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004130 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004131
4132 // Verification is done, grab the lock again.
4133 ObjectLock<mirror::Class> lock(self, klass);
4134
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004135 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4136 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004137 VLOG(class_linker) << "Soft verification failure in class "
4138 << klass->PrettyDescriptor()
4139 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4140 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004141 }
Ian Rogers1f539342012-10-03 21:09:42 -07004142 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004143 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004144 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004145 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004146 // Even though there were no verifier failures we need to respect whether the super-class and
4147 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004148 if (supertype == nullptr || supertype->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004149 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004150 } else {
Alex Lightf1f10492015-10-07 16:08:36 -07004151 CHECK_EQ(supertype->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004152 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004153 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004154 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004155 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004156 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004157 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004158 // Soft failures at compile time should be retried at runtime. Soft
4159 // failures at runtime will be handled by slow paths in the generated
4160 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004161 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004162 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004163 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004164 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004165 // As this is a fake verified status, make sure the methods are _not_ marked
4166 // kAccSkipAccessChecks later.
4167 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004168 }
4169 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004170 } else {
David Sehr709b0702016-10-13 09:12:37 -07004171 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004172 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4173 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004174 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004175 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko72ab6842017-01-20 19:32:50 +00004176 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004177 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004178 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004179 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004180 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004181 // method.
4182 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004183 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004184 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004185
4186 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4187 // Never skip access checks if the verification soft fail is forced.
4188 // Mark the class as having a verification attempt to avoid re-running the verifier.
4189 klass->SetVerificationAttempted();
4190 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004191 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004192 }
Andreas Gampe48498592014-09-10 19:48:05 -07004193 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004194 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004195}
4196
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004197bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004198 ObjPtr<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004199 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004200 // If we're compiling, we can only verify the class using the oat file if
4201 // we are not compiling the image or if the class we're verifying is not part of
4202 // the app. In other words, we will only check for preverification of bootclasspath
4203 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004204 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004205 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07004206 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004207 return false;
4208 }
4209 // We are compiling an app (not the image).
4210
4211 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004212 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004213 return false;
4214 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004215 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004216
Richard Uhler07b3c232015-03-31 15:57:54 -07004217 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004218 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004219 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004220 return false;
4221 }
4222
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004223 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004224 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004225 if (oat_file_class_status == mirror::Class::kStatusVerified ||
4226 oat_file_class_status == mirror::Class::kStatusInitialized) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004227 return true;
4228 }
4229 // If we only verified a subset of the classes at compile time, we can end up with classes that
4230 // were resolved by the verifier.
4231 if (oat_file_class_status == mirror::Class::kStatusResolved) {
4232 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004233 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004234 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004235 // Compile time verification failed with a soft error. Compile time verification can fail
4236 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004237 // class ... {
4238 // Foo x;
4239 // .... () {
4240 // if (...) {
4241 // v1 gets assigned a type of resolved class Foo
4242 // } else {
4243 // v1 gets assigned a type of unresolved class Bar
4244 // }
4245 // iput x = v1
4246 // } }
4247 // when we merge v1 following the if-the-else it results in Conflict
4248 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4249 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4250 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4251 // at compile time).
4252 return false;
4253 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004254 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004255 // Compile time verification failed with a hard error. This is caused by invalid instructions
4256 // in the class. These errors are unrecoverable.
4257 return false;
4258 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004259 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004260 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4261 // not loading the class.
4262 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4263 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004264 return false;
4265 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004266 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004267 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004268 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004269 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004270 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004271}
4272
Alex Light5a559862016-01-29 12:24:48 -08004273void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004274 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004275 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004276 }
4277}
4278
Alex Light5a559862016-01-29 12:24:48 -08004279void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004280 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
Alex Light5a559862016-01-29 12:24:48 -08004281 const DexFile::CodeItem* code_item =
4282 method->GetDexFile()->GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004283 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004284 return; // native or abstract method
4285 }
4286 if (code_item->tries_size_ == 0) {
4287 return; // nothing to process
4288 }
Ian Rogers13735952014-10-08 12:43:28 -07004289 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004290 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004291 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4292 CatchHandlerIterator iterator(handlers_ptr);
4293 for (; iterator.HasNext(); iterator.Next()) {
4294 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4295 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004296 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004297 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004298 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004299 DCHECK(Thread::Current()->IsExceptionPending());
4300 Thread::Current()->ClearException();
4301 }
4302 }
4303 }
4304 handlers_ptr = iterator.EndDataPointer();
4305 }
4306}
4307
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004308mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4309 jstring name,
4310 jobjectArray interfaces,
4311 jobject loader,
4312 jobjectArray methods,
4313 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004314 Thread* self = soa.Self();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004315 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004316 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004317 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004318 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004319 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004320 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004321 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004322 DCHECK(temp_klass->GetClass() != nullptr);
4323 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004324 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4325 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004326 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4327 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4328 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4329 temp_klass->SetName(soa.Decode<mirror::String>(name));
4330 temp_klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004331 // Object has an empty iftable, copy it for that reason.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004332 temp_klass->SetIfTable(GetClassRoot(kJavaLangObject)->GetIfTable());
4333 mirror::Class::SetStatus(temp_klass, mirror::Class::kStatusIdx, self);
4334 std::string descriptor(GetDescriptorForProxy(temp_klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004335 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004336
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004337 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004338 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004339
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004340 // Insert the class before loading the fields as the field roots
4341 // (ArtField::declaring_class_) are only visited from the class
4342 // table. There can't be any suspend points between inserting the
4343 // class and setting the field arrays below.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004344 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004345 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004346
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004347 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004348 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004349 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004350 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004351
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004352 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4353 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004354 ArtField& interfaces_sfield = sfields->At(0);
4355 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004356 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004357 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004358
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004359 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004360 ArtField& throws_sfield = sfields->At(1);
4361 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004362 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004363 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004364
Ian Rogers466bb252011-10-14 03:29:56 -07004365 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004366 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004367
Alex Lighte64300b2015-12-15 15:02:47 -08004368 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004369 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004370 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
David Sehr709b0702016-10-13 09:12:37 -07004371 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004372 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004373
4374 // Create the methods array.
4375 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4376 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004377 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4378 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004379 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004380 self->AssertPendingOOMException();
4381 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004382 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004383 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004384
4385 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004386 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004387
4388 // Create virtual method using specified prototypes.
4389 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004390 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004391 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004392 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004393 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004394 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4395 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004396 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004397
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004398 // The super class is java.lang.reflect.Proxy
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004399 temp_klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004400 // Now effectively in the loaded state.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004401 mirror::Class::SetStatus(temp_klass, mirror::Class::kStatusLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004402 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004403
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004404 // At this point the class is loaded. Publish a ClassLoad event.
4405 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4406 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4407
4408 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004409 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004410 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004411 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004412 // Link the fields and virtual methods, creating vtable and iftables.
4413 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004414 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004415 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004416 if (!LinkClass(self, descriptor.c_str(), temp_klass, h_interfaces, &klass)) {
4417 mirror::Class::SetStatus(temp_klass, mirror::Class::kStatusErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004418 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004419 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004420 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004421 CHECK(temp_klass->IsRetired());
4422 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004423
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004424 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004425 interfaces_sfield.SetObject<false>(
4426 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004427 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004428 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4429 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004430 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004431 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004432
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004433 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4434
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004435 {
4436 // Lock on klass is released. Lock new class object.
4437 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004438 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004439 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004440
4441 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004442 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004443 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004444 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4445
Ian Rogersc2b44472011-12-14 21:17:17 -08004446 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004447 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4448 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004449 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004450 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004451
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004452 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004453 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004454 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004455 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004456 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004457
4458 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004459 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004460 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004461
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004462 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004463 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004464 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004465 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004466 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004467 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004468}
4469
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004470std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004471 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004472 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004473 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004474 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4475}
4476
Mathieu Chartiere401d142015-04-22 13:56:20 -07004477void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4478 // Create constructor for Proxy that must initialize the method.
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004479 CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 23u);
4480
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004481 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4482 // on which front-end compiler was used to build the libcore DEX files.
4483 ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->
4484 FindDeclaredDirectMethod("<init>",
4485 "(Ljava/lang/reflect/InvocationHandler;)V",
4486 image_pointer_size_);
4487 DCHECK(proxy_constructor != nullptr)
4488 << "Could not find <init> method in java.lang.reflect.Proxy";
4489
Sebastien Hertzae94e352014-08-27 15:32:56 +02004490 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4491 // constructor method.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004492 GetClassRoot(kJavaLangReflectProxy)->GetDexCache()->SetResolvedMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -07004493 proxy_constructor->GetDexMethodIndex(), proxy_constructor, image_pointer_size_);
Jeff Haodb8a6642014-08-14 17:18:52 -07004494 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4495 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004496 DCHECK(out != nullptr);
4497 out->CopyFrom(proxy_constructor, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004498 // Make this constructor public and fix the class to be our Proxy version
Mathieu Chartiere401d142015-04-22 13:56:20 -07004499 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) | kAccPublic);
4500 out->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004501}
4502
Mathieu Chartiere401d142015-04-22 13:56:20 -07004503void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004504 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004505 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4506 CHECK_STREQ(np->GetName(), "<init>");
4507 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004508 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004509}
4510
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004511void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004512 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004513 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4514 // prototype method
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004515 auto* dex_cache = prototype->GetDeclaringClass()->GetDexCache();
4516 // Avoid dirtying the dex cache unless we need to.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004517 if (dex_cache->GetResolvedMethod(prototype->GetDexMethodIndex(), image_pointer_size_) !=
4518 prototype) {
4519 dex_cache->SetResolvedMethod(
4520 prototype->GetDexMethodIndex(), prototype, image_pointer_size_);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004521 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004522 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004523 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004524 DCHECK(out != nullptr);
4525 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004526
Alex Lighte9dd04f2016-03-16 16:09:45 -07004527 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004528 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004529 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4530 // preference to the invocation handler.
4531 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4532 // Make the method final.
4533 const uint32_t kAddFlags = kAccFinal;
4534 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4535
4536 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4537 // method they copy might (if it's a default method).
4538 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004539
Ian Rogers466bb252011-10-14 03:29:56 -07004540 // At runtime the method looks like a reference and argument saving method, clone the code
4541 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004542 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004543}
Jesse Wilson95caa792011-10-12 18:14:17 -04004544
Mathieu Chartiere401d142015-04-22 13:56:20 -07004545void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004546 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004547 CHECK(!prototype->IsFinal());
4548 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004549 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004550
4551 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4552 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Vladimir Marko05792b92015-08-03 11:56:49 +01004553 CHECK(prototype->HasSameDexCacheResolvedMethods(method, image_pointer_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07004554 auto* np = method->GetInterfaceMethodIfProxy(image_pointer_size_);
4555 CHECK_EQ(prototype->GetDeclaringClass()->GetDexCache(), np->GetDexCache());
Ian Rogers19846512012-02-24 11:42:47 -08004556 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4557
Mathieu Chartiere401d142015-04-22 13:56:20 -07004558 CHECK_STREQ(np->GetName(), prototype->GetName());
4559 CHECK_STREQ(np->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004560 // More complex sanity - via dex cache
Vladimir Marko942fd312017-01-16 20:52:19 +00004561 CHECK_EQ(np->GetReturnType(true /* resolve */), prototype->GetReturnType(true /* resolve */));
Jesse Wilson95caa792011-10-12 18:14:17 -04004562}
4563
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004564bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004565 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004566 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004567 return true;
4568 }
4569 if (!can_init_statics) {
4570 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004571 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004572 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004573 return false;
4574 }
4575 // Check if there are encoded static values needing initialization.
4576 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004577 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004578 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004579 if (dex_class_def->static_values_off_ != 0) {
4580 return false;
4581 }
4582 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004583 // If we are a class we need to initialize all interfaces with default methods when we are
4584 // initialized. Check all of them.
4585 if (!klass->IsInterface()) {
4586 size_t num_interfaces = klass->GetIfTableCount();
4587 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004588 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07004589 if (iface->HasDefaultMethods() &&
4590 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
4591 return false;
4592 }
4593 }
4594 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004595 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004596 if (klass->IsInterface() || !klass->HasSuperClass()) {
4597 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004598 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004599 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07004600 if (!can_init_parents && !super_class->IsInitialized()) {
4601 return false;
4602 }
4603 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004604}
4605
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004606bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
4607 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004608 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4609
4610 // Are we already initialized and therefore done?
4611 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4612 // an initialized class will never change its state.
4613 if (klass->IsInitialized()) {
4614 return true;
4615 }
4616
4617 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004618 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004619 return false;
4620 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004621
Ian Rogers7b078e82014-09-10 14:44:24 -07004622 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004623 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004624 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004625 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004626
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004627 // Re-check under the lock in case another thread initialized ahead of us.
4628 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004629 return true;
4630 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004631
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004632 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004633 if (klass->IsErroneous()) {
Andreas Gampecb086952015-11-02 16:20:00 -08004634 ThrowEarlierClassFailure(klass.Get(), true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07004635 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004636 return false;
4637 }
4638
Vladimir Marko72ab6842017-01-20 19:32:50 +00004639 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
4640 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004641
4642 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004643 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004644 if (!klass->IsVerified()) {
4645 // We failed to verify, expect either the klass to be erroneous or verification failed at
4646 // compile time.
4647 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07004648 // The class is erroneous. This may be a verifier error, or another thread attempted
4649 // verification and/or initialization and failed. We can distinguish those cases by
4650 // whether an exception is already pending.
4651 if (self->IsExceptionPending()) {
4652 // Check that it's a VerifyError.
4653 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07004654 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07004655 } else {
4656 // Check that another thread attempted initialization.
4657 DCHECK_NE(0, klass->GetClinitThreadId());
4658 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
4659 // Need to rethrow the previous failure now.
4660 ThrowEarlierClassFailure(klass.Get(), true);
4661 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07004662 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004663 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004664 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004665 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004666 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004667 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004668 } else {
4669 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004670 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07004671
4672 // A separate thread could have moved us all the way to initialized. A "simple" example
4673 // involves a subclass of the current class being initialized at the same time (which
4674 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00004675 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07004676 if (klass->IsInitialized()) {
4677 return true;
4678 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004679 }
4680
Brian Carlstromd1422f82011-09-28 11:37:09 -07004681 // If the class is kStatusInitializing, either this thread is
4682 // initializing higher up the stack or another thread has beat us
4683 // to initializing and we need to wait. Either way, this
4684 // invocation of InitializeClass will not be responsible for
4685 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004686 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004687 // Could have got an exception during verification.
4688 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004689 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004690 return false;
4691 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004692 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004693 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004694 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004695 return true;
4696 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004697 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004698 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004699 }
4700
4701 if (!ValidateSuperClassDescriptors(klass)) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00004702 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004703 return false;
4704 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004705 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004706
David Sehr709b0702016-10-13 09:12:37 -07004707 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07004708 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004709
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004710 // From here out other threads may observe that we're initializing and so changes of state
4711 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004712 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004713 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004714
4715 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004716 }
4717
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004718 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004719 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004720 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004721 if (!super_class->IsInitialized()) {
4722 CHECK(!super_class->IsInterface());
4723 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004724 StackHandleScope<1> hs(self);
4725 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004726 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004727 if (!super_initialized) {
4728 // The super class was verified ahead of entering initializing, we should only be here if
4729 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004730 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004731 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07004732 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004733 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004734 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004735 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004736 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004737 // Initialization failed because the super-class is erroneous.
Vladimir Marko72ab6842017-01-20 19:32:50 +00004738 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004739 return false;
4740 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004741 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004742 }
4743
Alex Lighteb7c1442015-08-31 13:17:42 -07004744 if (!klass->IsInterface()) {
4745 // Initialize interfaces with default methods for the JLS.
4746 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004747 // Only setup the (expensive) handle scope if we actually need to.
4748 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07004749 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07004750 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
4751 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004752 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004753 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004754 CHECK(handle_scope_iface->IsInterface());
4755 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
4756 // We have already done this for this interface. Skip it.
4757 continue;
4758 }
4759 // We cannot just call initialize class directly because we need to ensure that ALL
4760 // interfaces with default methods are initialized. Non-default interface initialization
4761 // will not affect other non-default super-interfaces.
4762 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
4763 handle_scope_iface,
4764 can_init_statics,
4765 can_init_parents);
4766 if (!iface_initialized) {
4767 ObjectLock<mirror::Class> lock(self, klass);
4768 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko72ab6842017-01-20 19:32:50 +00004769 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07004770 return false;
4771 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004772 }
4773 }
4774 }
4775
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004776 const size_t num_static_fields = klass->NumStaticFields();
4777 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004778 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004779 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004780 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004781 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004782 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004783 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004784
4785 // Eagerly fill in static fields so that the we don't have to do as many expensive
4786 // Class::FindStaticField in ResolveField.
4787 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004788 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004789 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004790 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004791 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004792 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004793 } else {
4794 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004795 }
4796 }
4797
David Sehr9323e6e2016-09-13 08:58:35 -07004798 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_file,
4799 &dex_cache,
4800 &class_loader,
4801 this,
4802 *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004803 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004804 ClassDataItemIterator field_it(dex_file, class_data);
4805 if (value_it.HasNext()) {
4806 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004807 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004808 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004809 ArtField* field = ResolveField(
4810 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004811 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004812 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004813 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004814 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004815 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07004816 if (self->IsExceptionPending()) {
4817 break;
4818 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004819 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004820 }
4821 }
4822 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004823
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004824
Mathieu Chartierda595be2016-08-10 13:57:39 -07004825 if (!self->IsExceptionPending()) {
4826 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4827 if (clinit != nullptr) {
4828 CHECK(can_init_statics);
4829 JValue result;
4830 clinit->Invoke(self, nullptr, 0, &result, "V");
4831 }
4832 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004833 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004834 uint64_t t1 = NanoTime();
4835
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004836 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004837 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004838 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004839
4840 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004841 WrapExceptionInInitializer(klass);
Vladimir Marko72ab6842017-01-20 19:32:50 +00004842 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004843 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004844 } else if (Runtime::Current()->IsTransactionAborted()) {
4845 // The exception thrown when the transaction aborted has been caught and cleared
4846 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07004847 VLOG(compiler) << "Return from class initializer of "
4848 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01004849 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02004850 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko72ab6842017-01-20 19:32:50 +00004851 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004852 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004853 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004854 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4855 RuntimeStats* thread_stats = self->GetStats();
4856 ++global_stats->class_init_count;
4857 ++thread_stats->class_init_count;
4858 global_stats->class_init_time_ns += (t1 - t0);
4859 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004860 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004861 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004862 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004863 std::string temp;
4864 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004865 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004866 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004867 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004868 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004869 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004870 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004871 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004872}
4873
Alex Lighteb7c1442015-08-31 13:17:42 -07004874// We recursively run down the tree of interfaces. We need to do this in the order they are declared
4875// and perform the initialization only on those interfaces that contain default methods.
4876bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
4877 Handle<mirror::Class> iface,
4878 bool can_init_statics,
4879 bool can_init_parents) {
4880 CHECK(iface->IsInterface());
4881 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004882 // Only create the (expensive) handle scope if we need it.
4883 if (UNLIKELY(num_direct_ifaces > 0)) {
4884 StackHandleScope<1> hs(self);
4885 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
4886 // First we initialize all of iface's super-interfaces recursively.
4887 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00004888 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00004889 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07004890 if (!super_iface->HasBeenRecursivelyInitialized()) {
4891 // Recursive step
4892 handle_super_iface.Assign(super_iface);
4893 if (!InitializeDefaultInterfaceRecursive(self,
4894 handle_super_iface,
4895 can_init_statics,
4896 can_init_parents)) {
4897 return false;
4898 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004899 }
4900 }
4901 }
4902
4903 bool result = true;
4904 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
4905 // initialize if we don't have default methods.
4906 if (iface->HasDefaultMethods()) {
4907 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
4908 }
4909
4910 // Mark that this interface has undergone recursive default interface initialization so we know we
4911 // can skip it on any later class initializations. We do this even if we are not a default
4912 // interface since we can still avoid the traversal. This is purely a performance optimization.
4913 if (result) {
4914 // TODO This should be done in a better way
4915 ObjectLock<mirror::Class> lock(self, iface);
4916 iface->SetRecursivelyInitialized();
4917 }
4918 return result;
4919}
4920
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004921bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
4922 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004923 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004924 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004925 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004926 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004927 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004928 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004929
4930 // When we wake up, repeat the test for init-in-progress. If
4931 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004932 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004933 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004934 WrapExceptionInInitializer(klass);
Vladimir Marko72ab6842017-01-20 19:32:50 +00004935 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004936 return false;
4937 }
4938 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004939 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004940 continue;
4941 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004942 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
4943 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004944 // Compile time initialization failed.
4945 return false;
4946 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004947 if (klass->IsErroneous()) {
4948 // The caller wants an exception, but it was thrown in a
4949 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004950 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07004951 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004952 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004953 return false;
4954 }
4955 if (klass->IsInitialized()) {
4956 return true;
4957 }
David Sehr709b0702016-10-13 09:12:37 -07004958 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004959 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004960 }
Ian Rogers07140832014-09-30 15:43:59 -07004961 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004962}
4963
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004964static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
4965 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004966 ArtMethod* method,
4967 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004968 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004969 DCHECK(Thread::Current()->IsExceptionPending());
4970 DCHECK(!m->IsProxyMethod());
4971 const DexFile* dex_file = m->GetDexFile();
4972 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
4973 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08004974 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07004975 std::string return_type = dex_file->PrettyType(return_type_idx);
4976 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004977 ThrowWrappedLinkageError(klass.Get(),
4978 "While checking class %s method %s signature against %s %s: "
4979 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07004980 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
4981 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004982 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07004983 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004984 return_type.c_str(), class_loader.c_str());
4985}
4986
4987static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
4988 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004989 ArtMethod* method,
4990 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004991 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08004992 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004993 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004994 DCHECK(Thread::Current()->IsExceptionPending());
4995 DCHECK(!m->IsProxyMethod());
4996 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07004997 std::string arg_type = dex_file->PrettyType(arg_type_idx);
4998 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004999 ThrowWrappedLinkageError(klass.Get(),
5000 "While checking class %s method %s signature against %s %s: "
5001 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005002 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5003 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005004 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005005 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005006 index, arg_type.c_str(), class_loader.c_str());
5007}
5008
5009static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5010 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005011 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005012 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005013 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005014 ThrowLinkageError(klass.Get(),
5015 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005016 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5017 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005018 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005019 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005020 error_msg.c_str());
5021}
5022
Ian Rogersb5fb2072014-12-02 17:22:02 -08005023static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005024 Handle<mirror::Class> klass,
5025 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005026 ArtMethod* method1,
5027 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005028 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005029 {
5030 StackHandleScope<1> hs(self);
Vladimir Marko942fd312017-01-16 20:52:19 +00005031 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType(true /* resolve */)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005032 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005033 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005034 return false;
5035 }
Vladimir Marko942fd312017-01-16 20:52:19 +00005036 ObjPtr<mirror::Class> other_return_type = method2->GetReturnType(true /* resolve */);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005037 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005038 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005039 return false;
5040 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005041 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005042 ThrowSignatureMismatch(klass, super_klass, method1,
5043 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005044 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005045 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005046 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005047 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005048 return false;
5049 }
5050 }
5051 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
5052 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
5053 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005054 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005055 ThrowSignatureMismatch(klass, super_klass, method1,
5056 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005057 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005058 return false;
5059 }
5060 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005061 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005062 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005063 ThrowSignatureMismatch(klass, super_klass, method1,
5064 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005065 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005066 return false;
5067 }
5068 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005069 }
5070 uint32_t num_types = types1->Size();
5071 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005072 ThrowSignatureMismatch(klass, super_klass, method1,
5073 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005074 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005075 return false;
5076 }
5077 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005078 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005079 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005080 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Marko942fd312017-01-16 20:52:19 +00005081 method1->GetClassFromTypeIndex(param_type_idx, true /* resolve */)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005082 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005083 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005084 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005085 return false;
5086 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005087 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005088 ObjPtr<mirror::Class> other_param_type =
Vladimir Marko942fd312017-01-16 20:52:19 +00005089 method2->GetClassFromTypeIndex(other_param_type_idx, true /* resolve */);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005090 if (UNLIKELY(other_param_type == nullptr)) {
5091 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005092 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005093 return false;
5094 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005095 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005096 ThrowSignatureMismatch(klass, super_klass, method1,
5097 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5098 i,
David Sehr709b0702016-10-13 09:12:37 -07005099 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005100 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005101 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005102 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005103 return false;
5104 }
5105 }
5106 return true;
5107}
5108
5109
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005110bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005111 if (klass->IsInterface()) {
5112 return true;
5113 }
Ian Rogers151f2212014-05-06 11:27:27 -07005114 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005115 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005116 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005117 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005118 if (klass->HasSuperClass() &&
5119 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005120 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005121 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005122 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5123 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5124 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005125 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5126 klass,
5127 super_klass,
5128 m,
5129 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005130 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005131 return false;
5132 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005133 }
5134 }
5135 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005136 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005137 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5138 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5139 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005140 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005141 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5142 j, image_pointer_size_);
5143 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5144 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005145 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5146 klass,
5147 super_klass,
5148 m,
5149 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005150 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005151 return false;
5152 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005153 }
5154 }
5155 }
5156 }
5157 return true;
5158}
5159
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005160bool ClassLinker::EnsureInitialized(Thread* self,
5161 Handle<mirror::Class> c,
5162 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005163 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005164 DCHECK(c != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005165 if (c->IsInitialized()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08005166 EnsureSkipAccessChecksMethods(c, image_pointer_size_);
Mathieu Chartier8502f722016-06-08 15:09:08 -07005167 self->AssertNoPendingException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005168 return true;
5169 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005170 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005171 if (!success) {
5172 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005173 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005174 }
5175 } else {
5176 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005177 }
5178 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005179}
5180
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005181void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5182 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005183 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005184 for (ArtField& field : new_class->GetIFields()) {
5185 if (field.GetDeclaringClass() == temp_class) {
5186 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005187 }
5188 }
5189
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005190 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005191 for (ArtField& field : new_class->GetSFields()) {
5192 if (field.GetDeclaringClass() == temp_class) {
5193 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005194 }
5195 }
5196
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005197 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005198 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005199 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005200 if (method.GetDeclaringClass() == temp_class) {
5201 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005202 }
5203 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005204
5205 // Make sure the remembered set and mod-union tables know that we updated some of the native
5206 // roots.
5207 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005208}
5209
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005210void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005211 CHECK(class_loader->GetAllocator() == nullptr);
5212 CHECK(class_loader->GetClassTable() == nullptr);
5213 Thread* const self = Thread::Current();
5214 ClassLoaderData data;
5215 data.weak_root = self->GetJniEnv()->vm->AddWeakGlobalRef(self, class_loader);
5216 // Create and set the class table.
5217 data.class_table = new ClassTable;
5218 class_loader->SetClassTable(data.class_table);
5219 // Create and set the linear allocator.
5220 data.allocator = Runtime::Current()->CreateLinearAlloc();
5221 class_loader->SetAllocator(data.allocator);
5222 // Add to the list so that we know to free the data later.
5223 class_loaders_.push_back(data);
5224}
5225
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005226ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005227 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005228 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005229 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005230 ClassTable* class_table = class_loader->GetClassTable();
5231 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005232 RegisterClassLoader(class_loader);
5233 class_table = class_loader->GetClassTable();
5234 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005235 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005236 return class_table;
5237}
5238
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005239ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005240 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005241}
5242
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005243static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005244 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005245 while (klass->HasSuperClass()) {
5246 klass = klass->GetSuperClass();
5247 if (klass->ShouldHaveImt()) {
5248 return klass->GetImt(pointer_size);
5249 }
5250 }
5251 return nullptr;
5252}
5253
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005254bool ClassLinker::LinkClass(Thread* self,
5255 const char* descriptor,
5256 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005257 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005258 MutableHandle<mirror::Class>* h_new_class_out) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005259 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005260
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005261 if (!LinkSuperClass(klass)) {
5262 return false;
5263 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005264 ArtMethod* imt_data[ImTable::kSize];
5265 // If there are any new conflicts compared to super class.
5266 bool new_conflict = false;
5267 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
5268 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005269 return false;
5270 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005271 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005272 return false;
5273 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005274 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005275 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005276 return false;
5277 }
5278 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005279 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005280
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005281 ImTable* imt = nullptr;
5282 if (klass->ShouldHaveImt()) {
5283 // If there are any new conflicts compared to the super class we can not make a copy. There
5284 // can be cases where both will have a conflict method at the same slot without having the same
5285 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5286 // will possibly create a table that is incorrect for either of the classes.
5287 // Same IMT with new_conflict does not happen very often.
5288 if (!new_conflict) {
5289 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5290 if (super_imt != nullptr) {
5291 bool imt_equals = true;
5292 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5293 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5294 }
5295 if (imt_equals) {
5296 imt = super_imt;
5297 }
5298 }
5299 }
5300 if (imt == nullptr) {
5301 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5302 imt = reinterpret_cast<ImTable*>(
5303 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5304 if (imt == nullptr) {
5305 return false;
5306 }
5307 imt->Populate(imt_data, image_pointer_size_);
5308 }
5309 }
5310
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005311 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5312 // We don't need to retire this class as it has no embedded tables or it was created the
5313 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005314 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005315
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005316 if (klass->ShouldHaveEmbeddedVTable()) {
5317 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005318 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005319 if (klass->ShouldHaveImt()) {
5320 klass->SetImt(imt, image_pointer_size_);
5321 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005322
5323 // Update CHA info based on whether we override methods.
5324 // Have to do this before setting the class as resolved which allows
5325 // instantiation of klass.
5326 Runtime::Current()->GetClassHierarchyAnalysis()->UpdateAfterLoadingOf(klass);
5327
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005328 // This will notify waiters on klass that saw the not yet resolved
5329 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07005330 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005331 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005332 } else {
5333 CHECK(!klass->IsResolved());
5334 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005335 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005336 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005337 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5338 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5339 // may not see any references to the target space and clean the card for a class if another
5340 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005341 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005342 klass->SetSFieldsPtrUnchecked(nullptr);
5343 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005344 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005345 self->AssertPendingOOMException();
Vladimir Marko72ab6842017-01-20 19:32:50 +00005346 mirror::Class::SetStatus(klass, mirror::Class::kStatusErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005347 return false;
5348 }
5349
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005350 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5351 ObjectLock<mirror::Class> lock(self, h_new_class);
5352 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005353
5354 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005355 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005356 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005357 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005358 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005359 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005360 if (class_loader != nullptr) {
5361 // We updated the class in the class table, perform the write barrier so that the GC knows
5362 // about the change.
5363 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
5364 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005365 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005366 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005367 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5368 }
5369 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005370
Mingyao Yang063fc772016-08-02 11:02:54 -07005371 // Update CHA info based on whether we override methods.
5372 // Have to do this before setting the class as resolved which allows
5373 // instantiation of klass.
5374 Runtime::Current()->GetClassHierarchyAnalysis()->UpdateAfterLoadingOf(h_new_class);
5375
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005376 // This will notify waiters on temp class that saw the not yet resolved class in the
5377 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07005378 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005379
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005380 CHECK_EQ(h_new_class->GetStatus(), mirror::Class::kStatusResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005381 // This will notify waiters on new_class that saw the not yet resolved
5382 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005383 mirror::Class::SetStatus(h_new_class, mirror::Class::kStatusResolved, self);
5384 // Return the new class.
5385 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005386 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005387 return true;
5388}
5389
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005390static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
5391 size_t* virtual_methods,
5392 size_t* direct_methods,
5393 size_t* static_fields,
5394 size_t* instance_fields) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005395 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
5396
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005397 while (dex_data.HasNextStaticField()) {
5398 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08005399 (*static_fields)++;
5400 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005401 while (dex_data.HasNextInstanceField()) {
5402 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08005403 (*instance_fields)++;
5404 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005405 while (dex_data.HasNextDirectMethod()) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005406 (*direct_methods)++;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005407 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08005408 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005409 while (dex_data.HasNextVirtualMethod()) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005410 (*virtual_methods)++;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005411 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08005412 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005413 DCHECK(!dex_data.HasNext());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005414}
5415
5416static void DumpClass(std::ostream& os,
5417 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
5418 const char* suffix) {
5419 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
5420 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
5421 os << " Static fields:\n";
5422 while (dex_data.HasNextStaticField()) {
5423 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
5424 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
5425 dex_data.Next();
5426 }
5427 os << " Instance fields:\n";
5428 while (dex_data.HasNextInstanceField()) {
5429 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
5430 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
5431 dex_data.Next();
5432 }
5433 os << " Direct methods:\n";
5434 while (dex_data.HasNextDirectMethod()) {
5435 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
5436 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
5437 dex_data.Next();
5438 }
5439 os << " Virtual methods:\n";
5440 while (dex_data.HasNextVirtualMethod()) {
5441 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
5442 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
5443 dex_data.Next();
5444 }
5445}
5446
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005447static std::string DumpClasses(const DexFile& dex_file1,
5448 const DexFile::ClassDef& dex_class_def1,
5449 const DexFile& dex_file2,
5450 const DexFile::ClassDef& dex_class_def2) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005451 std::ostringstream os;
5452 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
5453 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
5454 return os.str();
5455}
5456
5457
5458// Very simple structural check on whether the classes match. Only compares the number of
5459// methods and fields.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005460static bool SimpleStructuralCheck(const DexFile& dex_file1,
5461 const DexFile::ClassDef& dex_class_def1,
5462 const DexFile& dex_file2,
5463 const DexFile::ClassDef& dex_class_def2,
Andreas Gampefd9eb392014-11-06 16:52:58 -08005464 std::string* error_msg) {
5465 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
5466 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
5467
5468 // Counters for current dex file.
5469 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005470 CountMethodsAndFields(dex_data1,
5471 &dex_virtual_methods1,
5472 &dex_direct_methods1,
5473 &dex_static_fields1,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005474 &dex_instance_fields1);
Andreas Gampefd9eb392014-11-06 16:52:58 -08005475 // Counters for compile-time dex file.
5476 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005477 CountMethodsAndFields(dex_data2,
5478 &dex_virtual_methods2,
5479 &dex_direct_methods2,
5480 &dex_static_fields2,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005481 &dex_instance_fields2);
Andreas Gampefd9eb392014-11-06 16:52:58 -08005482
5483 if (dex_virtual_methods1 != dex_virtual_methods2) {
5484 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005485 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s",
5486 dex_virtual_methods1,
5487 dex_virtual_methods2,
5488 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005489 return false;
5490 }
5491 if (dex_direct_methods1 != dex_direct_methods2) {
5492 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005493 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s",
5494 dex_direct_methods1,
5495 dex_direct_methods2,
5496 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005497 return false;
5498 }
5499 if (dex_static_fields1 != dex_static_fields2) {
5500 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005501 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s",
5502 dex_static_fields1,
5503 dex_static_fields2,
5504 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005505 return false;
5506 }
5507 if (dex_instance_fields1 != dex_instance_fields2) {
5508 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005509 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s",
5510 dex_instance_fields1,
5511 dex_instance_fields2,
5512 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005513 return false;
5514 }
5515
5516 return true;
5517}
5518
5519// Checks whether a the super-class changed from what we had at compile-time. This would
5520// invalidate quickening.
5521static bool CheckSuperClassChange(Handle<mirror::Class> klass,
5522 const DexFile& dex_file,
5523 const DexFile::ClassDef& class_def,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005524 ObjPtr<mirror::Class> super_class)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005525 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005526 // Check for unexpected changes in the superclass.
5527 // Quick check 1) is the super_class class-loader the boot class loader? This always has
5528 // precedence.
5529 if (super_class->GetClassLoader() != nullptr &&
5530 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
5531 // which is implied by different dex cache.
5532 klass->GetDexCache() != super_class->GetDexCache()) {
5533 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
5534 // definition for the super-class, and (b) the files are in separate oat files. The oat files
5535 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
Richard Uhler07b3c232015-03-31 15:57:54 -07005536 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
5537 const OatFile* class_oat_file = nullptr;
5538 if (class_oat_dex_file != nullptr) {
5539 class_oat_file = class_oat_dex_file->GetOatFile();
5540 }
5541
Andreas Gampefd9eb392014-11-06 16:52:58 -08005542 if (class_oat_file != nullptr) {
Richard Uhler07b3c232015-03-31 15:57:54 -07005543 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
5544 const OatFile* loaded_super_oat_file = nullptr;
5545 if (loaded_super_oat_dex_file != nullptr) {
5546 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
5547 }
5548
Andreas Gampefd9eb392014-11-06 16:52:58 -08005549 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
5550 // Now check (a).
5551 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
5552 if (super_class_def != nullptr) {
5553 // Uh-oh, we found something. Do our check.
5554 std::string error_msg;
5555 if (!SimpleStructuralCheck(dex_file, *super_class_def,
5556 super_class->GetDexFile(), *super_class->GetClassDef(),
5557 &error_msg)) {
5558 // Print a warning to the log. This exception might be caught, e.g., as common in test
5559 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
5560 // only save the type of the exception.
5561 LOG(WARNING) << "Incompatible structural change detected: " <<
5562 StringPrintf(
5563 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
David Sehr709b0702016-10-13 09:12:37 -07005564 dex_file.PrettyType(super_class_def->class_idx_).c_str(),
Andreas Gampefd9eb392014-11-06 16:52:58 -08005565 class_oat_file->GetLocation().c_str(),
5566 loaded_super_oat_file->GetLocation().c_str(),
5567 error_msg.c_str());
5568 ThrowIncompatibleClassChangeError(klass.Get(),
5569 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
David Sehr709b0702016-10-13 09:12:37 -07005570 dex_file.PrettyType(super_class_def->class_idx_).c_str(),
Andreas Gampefd9eb392014-11-06 16:52:58 -08005571 class_oat_file->GetLocation().c_str(),
5572 loaded_super_oat_file->GetLocation().c_str(),
5573 error_msg.c_str());
5574 return false;
5575 }
5576 }
5577 }
5578 }
5579 }
5580 return true;
5581}
5582
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005583bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005584 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005585 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005586 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5587 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005588 // Check that a class does not inherit from itself directly.
5589 //
5590 // TODO: This is a cheap check to detect the straightforward case
5591 // of a class extending itself (b/28685551), but we should do a
5592 // proper cycle detection on loaded classes, to detect all cases
5593 // of class circularity errors (b/28830038).
5594 if (super_class_idx == class_def.class_idx_) {
5595 ThrowClassCircularityError(klass.Get(),
5596 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005597 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005598 return false;
5599 }
5600
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005601 ObjPtr<mirror::Class> super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005602 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005603 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005604 return false;
5605 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005606 // Verify
5607 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005608 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005609 super_class->PrettyDescriptor().c_str(),
5610 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005611 return false;
5612 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005613 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005614 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08005615
5616 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
5617 DCHECK(Thread::Current()->IsExceptionPending());
5618 return false;
5619 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005620 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005621 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005622 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005623 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005624 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005625 ObjPtr<mirror::Class> interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005626 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005627 DCHECK(Thread::Current()->IsExceptionPending());
5628 return false;
5629 }
5630 // Verify
5631 if (!klass->CanAccess(interface)) {
5632 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005633 ThrowIllegalAccessError(klass.Get(),
5634 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005635 interface->PrettyDescriptor().c_str(),
5636 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005637 return false;
5638 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005639 }
5640 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005641 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07005642 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005643 return true;
5644}
5645
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005646bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005647 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005648 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005649 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005650 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005651 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005652 return false;
5653 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005654 return true;
5655 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005656 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005657 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005658 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005659 return false;
5660 }
5661 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07005662 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005663 ThrowIncompatibleClassChangeError(klass.Get(),
5664 "Superclass %s of %s is %s",
David Sehr709b0702016-10-13 09:12:37 -07005665 super->PrettyDescriptor().c_str(),
5666 klass->PrettyDescriptor().c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005667 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005668 return false;
5669 }
5670 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005671 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005672 super->PrettyDescriptor().c_str(),
5673 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005674 return false;
5675 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005676
Brian Carlstromf3632832014-05-20 15:36:53 -07005677 // Inherit kAccClassIsFinalizable from the superclass in case this
5678 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005679 if (super->IsFinalizable()) {
5680 klass->SetFinalizable();
5681 }
5682
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005683 // Inherit class loader flag form super class.
5684 if (super->IsClassLoaderClass()) {
5685 klass->SetClassLoaderClass();
5686 }
5687
Elliott Hughes2da50362011-10-10 16:57:08 -07005688 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005689 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005690 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005691 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005692 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005693 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005694 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07005695 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005696 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005697 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005698 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005699 return false;
5700 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005701
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005702 if (kIsDebugBuild) {
5703 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005704 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005705 CHECK(super->IsResolved());
5706 super = super->GetSuperClass();
5707 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005708 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005709 return true;
5710}
5711
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005712// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005713bool ClassLinker::LinkMethods(Thread* self,
5714 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005715 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005716 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005717 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005718 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005719 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5720 // need to have default methods be in the virtuals array of each class but we don't set that up
5721 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07005722 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07005723 // Link virtual methods then interface methods.
5724 // We set up the interface lookup table first because we need it to determine if we need to update
5725 // any vtable entries with new default method implementations.
5726 return SetupInterfaceLookupTable(self, klass, interfaces)
5727 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005728 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005729}
5730
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005731// Comparator for name and signature of a method, used in finding overriding methods. Implementation
5732// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
5733// caches in the implementation below.
5734class MethodNameAndSignatureComparator FINAL : public ValueObject {
5735 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005736 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005737 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005738 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
5739 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07005740 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005741 }
5742
5743 const char* GetName() {
5744 if (name_ == nullptr) {
5745 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
5746 }
5747 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005748 }
5749
Mathieu Chartiere401d142015-04-22 13:56:20 -07005750 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005751 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07005752 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005753 const DexFile* other_dex_file = other->GetDexFile();
5754 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
5755 if (dex_file_ == other_dex_file) {
5756 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
5757 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005758 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005759 uint32_t other_name_len;
5760 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
5761 &other_name_len);
5762 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
5763 return false;
5764 }
5765 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
5766 }
5767
5768 private:
5769 // Dex file for the method to compare against.
5770 const DexFile* const dex_file_;
5771 // MethodId for the method to compare against.
5772 const DexFile::MethodId* const mid_;
5773 // Lazily computed name from the dex file's strings.
5774 const char* name_;
5775 // Lazily computed name length.
5776 uint32_t name_len_;
5777};
5778
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005779class LinkVirtualHashTable {
5780 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005781 LinkVirtualHashTable(Handle<mirror::Class> klass,
5782 size_t hash_size,
5783 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07005784 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005785 : klass_(klass),
5786 hash_size_(hash_size),
5787 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07005788 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005789 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
5790 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005791
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005792 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005793 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
5794 virtual_method_index, image_pointer_size_);
5795 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005796 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005797 uint32_t index = hash % hash_size_;
5798 // Linear probe until we have an empty slot.
5799 while (hash_table_[index] != invalid_index_) {
5800 if (++index == hash_size_) {
5801 index = 0;
5802 }
5803 }
5804 hash_table_[index] = virtual_method_index;
5805 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005806
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005807 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005808 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005809 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005810 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005811 size_t index = hash % hash_size_;
5812 while (true) {
5813 const uint32_t value = hash_table_[index];
5814 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
5815 // the block and can safely assume not found.
5816 if (value == invalid_index_) {
5817 break;
5818 }
5819 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005820 ArtMethod* virtual_method =
5821 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
5822 if (comparator->HasSameNameAndSignature(
5823 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005824 hash_table_[index] = removed_index_;
5825 return value;
5826 }
5827 }
5828 if (++index == hash_size_) {
5829 index = 0;
5830 }
5831 }
5832 return GetNotFoundIndex();
5833 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005834
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005835 static uint32_t GetNotFoundIndex() {
5836 return invalid_index_;
5837 }
5838
5839 private:
5840 static const uint32_t invalid_index_;
5841 static const uint32_t removed_index_;
5842
5843 Handle<mirror::Class> klass_;
5844 const size_t hash_size_;
5845 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07005846 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005847};
5848
5849const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
5850const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
5851
Stephen Hines1ddd9132017-02-08 01:51:18 -08005852bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07005853 Thread* self,
5854 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07005855 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005856 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07005857 if (klass->IsInterface()) {
5858 // No vtable.
5859 if (!IsUint<16>(num_virtual_methods)) {
5860 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
5861 return false;
5862 }
5863 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07005864 // Assign each method an IMT index and set the default flag.
5865 for (size_t i = 0; i < num_virtual_methods; ++i) {
5866 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5867 m->SetMethodIndex(i);
5868 if (!m->IsAbstract()) {
5869 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
5870 has_defaults = true;
5871 }
5872 }
5873 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
5874 // during initialization. This is a performance optimization. We could simply traverse the
5875 // virtual_methods_ array again during initialization.
5876 if (has_defaults) {
5877 klass->SetHasDefaultMethods();
5878 }
5879 return true;
5880 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005881 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
5882 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005883 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07005884 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07005885 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005886 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005887 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005888 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005889 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005890 return false;
5891 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005892 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005893 vtable->SetElementPtrSize(
5894 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005895 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005896 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5897 // might give us new default methods). If no new interfaces then we can skip the rest since
5898 // the class cannot override any of the super-class's methods. This is required for
5899 // correctness since without it we might not update overridden default method vtable entries
5900 // correctly.
5901 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005902 klass->SetVTable(vtable.Get());
5903 return true;
5904 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005905 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07005906 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005907 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07005908 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07005909 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5910 // might give us new default methods). See comment above.
5911 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005912 klass->SetVTable(super_vtable);
5913 return true;
5914 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005915 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
5916 super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005917 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005918 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005919 return false;
5920 }
Ian Rogersa436fde2013-08-27 23:34:06 -07005921 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005922 // How the algorithm works:
5923 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
5924 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
5925 // method which has not been matched to a vtable method, and j if the virtual method at the
5926 // index overrode the super virtual method at index j.
5927 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
5928 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
5929 // the need for the initial vtable which we later shrink back down).
5930 // 3. Add non overridden methods to the end of the vtable.
5931 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07005932 // + 1 so that even if we only have new default methods we will still be able to use this hash
5933 // table (i.e. it will never have 0 size).
5934 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005935 uint32_t* hash_table_ptr;
5936 std::unique_ptr<uint32_t[]> hash_heap_storage;
5937 if (hash_table_size <= kMaxStackHash) {
5938 hash_table_ptr = reinterpret_cast<uint32_t*>(
5939 alloca(hash_table_size * sizeof(*hash_table_ptr)));
5940 } else {
5941 hash_heap_storage.reset(new uint32_t[hash_table_size]);
5942 hash_table_ptr = hash_heap_storage.get();
5943 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005944 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005945 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005946 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005947 DCHECK(klass->GetVirtualMethodDuringLinking(
5948 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005949 hash_table.Add(i);
5950 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005951 // 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 -07005952 // the hash table.
5953 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005954 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005955 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005956 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
5957 super_method->GetAccessFlags())) {
5958 // Continue on to the next method since this one is package private and canot be overridden.
5959 // Before Android 4.1, the package-private method super_method might have been incorrectly
5960 // overridden.
5961 continue;
5962 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005963 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005964 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07005965 // We remove the method so that subsequent lookups will be faster by making the hash-map
5966 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005967 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5968 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005969 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
5970 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07005971 if (super_method->IsFinal()) {
5972 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5973 virtual_method->PrettyMethod().c_str(),
5974 super_method->GetDeclaringClassDescriptor());
5975 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005976 }
Alex Lightc7a420c2016-10-18 14:33:18 -07005977 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
5978 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07005979 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005980 // We didn't directly override this method but we might through default methods...
5981 // Check for default method update.
5982 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07005983 switch (FindDefaultMethodImplementation(self,
5984 super_method,
5985 klass,
5986 /*out*/&default_method)) {
5987 case DefaultMethodSearchResult::kDefaultConflict: {
5988 // A conflict was found looking for default methods. Note this (assuming it wasn't
5989 // pre-existing) in the translations map.
5990 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
5991 // Don't generate another conflict method to reduce memory use as an optimization.
5992 default_translations->insert(
5993 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
5994 }
5995 break;
5996 }
5997 case DefaultMethodSearchResult::kAbstractFound: {
5998 // No conflict but method is abstract.
5999 // We note that this vtable entry must be made abstract.
6000 if (UNLIKELY(!super_method->IsAbstract())) {
6001 default_translations->insert(
6002 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6003 }
6004 break;
6005 }
6006 case DefaultMethodSearchResult::kDefaultFound: {
6007 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6008 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6009 // Found a default method implementation that is new.
6010 // TODO Refactor this add default methods to virtuals here and not in
6011 // LinkInterfaceMethods maybe.
6012 // The problem is default methods might override previously present
6013 // default-method or miranda-method vtable entries from the superclass.
6014 // Unfortunately we need these to be entries in this class's virtuals. We do not
6015 // give these entries there until LinkInterfaceMethods so we pass this map around
6016 // to let it know which vtable entries need to be updated.
6017 // Make a note that vtable entry j must be updated, store what it needs to be updated
6018 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6019 // then.
6020 default_translations->insert(
6021 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006022 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6023 << " overridden by default "
6024 << default_method->PrettyMethod()
6025 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006026 }
6027 break;
6028 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006029 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006030 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006031 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006032 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006033 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006034 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006035 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006036 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6037 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006038 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006039 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006040 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006041 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006042 local_method->SetMethodIndex(actual_count);
6043 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006044 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006045 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006046 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006047 return false;
6048 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006049 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006050 CHECK_LE(actual_count, max_count);
6051 if (actual_count < max_count) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006052 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006053 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006054 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006055 return false;
6056 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006057 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006058 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006059 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07006060 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006061 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006062 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6063 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006064 return false;
6065 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006066 auto* vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006067 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006068 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006069 return false;
6070 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006071 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006072 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6073 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006074 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006075 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006076 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006077 }
6078 return true;
6079}
6080
Alex Light9139e002015-10-09 15:59:48 -07006081// Determine if the given iface has any subinterface in the given list that declares the method
6082// specified by 'target'.
6083//
6084// Arguments
6085// - self: The thread we are running on
6086// - target: A comparator that will match any method that overrides the method we are checking for
6087// - iftable: The iftable we are searching for an overriding method on.
6088// - ifstart: The index of the interface we are checking to see if anything overrides
6089// - iface: The interface we are checking to see if anything overrides.
6090// - image_pointer_size:
6091// The image pointer size.
6092//
6093// Returns
6094// - True: There is some method that matches the target comparator defined in an interface that
6095// is a subtype of iface.
6096// - False: There is no method that matches the target comparator in any interface that is a subtype
6097// of iface.
6098static bool ContainsOverridingMethodOf(Thread* self,
6099 MethodNameAndSignatureComparator& target,
6100 Handle<mirror::IfTable> iftable,
6101 size_t ifstart,
6102 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006103 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006104 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006105 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006106 DCHECK(iface != nullptr);
6107 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006108 DCHECK_GE(ifstart, 0u);
6109 DCHECK_LT(ifstart, iftable->Count());
6110 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6111 DCHECK(iface->IsInterface());
6112
6113 size_t iftable_count = iftable->Count();
6114 StackHandleScope<1> hs(self);
6115 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6116 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6117 // Skip ifstart since our current interface obviously cannot override itself.
6118 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006119 // Iterate through every method on this interface. The order does not matter.
6120 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006121 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006122 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006123 // Check if the i'th interface is a subtype of this one.
6124 if (iface->IsAssignableFrom(current_iface.Get())) {
6125 return true;
6126 }
6127 break;
6128 }
6129 }
6130 }
6131 return false;
6132}
6133
Alex Lighteb7c1442015-08-31 13:17:42 -07006134// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006135// out_default_method and returns kDefaultFound on success. If no default method was found return
6136// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6137// default_method conflict) it will return kDefaultConflict.
6138ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6139 Thread* self,
6140 ArtMethod* target_method,
6141 Handle<mirror::Class> klass,
6142 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006143 DCHECK(self != nullptr);
6144 DCHECK(target_method != nullptr);
6145 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006146
6147 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006148
6149 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6150 // table. This lets us walk the table backwards when searching for default methods. The first one
6151 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6152 // track of it and then continue checking all other interfaces, since we need to throw an error if
6153 // we encounter conflicting default method implementations (one is not a subtype of the other).
6154 //
6155 // The order of unrelated interfaces does not matter and is not defined.
6156 size_t iftable_count = klass->GetIfTableCount();
6157 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006158 // No interfaces. We have already reset out to null so just return kAbstractFound.
6159 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006160 }
6161
Alex Light9139e002015-10-09 15:59:48 -07006162 StackHandleScope<3> hs(self);
6163 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006164 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006165 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006166 MethodNameAndSignatureComparator target_name_comparator(
6167 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6168 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006169 for (size_t k = iftable_count; k != 0; ) {
6170 --k;
6171
Alex Lighteb7c1442015-08-31 13:17:42 -07006172 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006173
6174 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006175 // Iterate through every declared method on this interface. The order does not matter.
6176 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6177 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006178 // Skip abstract methods and methods with different names.
6179 if (current_method->IsAbstract() ||
6180 !target_name_comparator.HasSameNameAndSignature(
6181 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6182 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006183 } else if (!current_method->IsPublic()) {
6184 // The verifier should have caught the non-public method for dex version 37. Just warn and
6185 // skip it since this is from before default-methods so we don't really need to care that it
6186 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006187 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6188 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006189 << "This will be a fatal error in subsequent versions of android. "
6190 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006191 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006192 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006193 // We have multiple default impls of the same method. This is a potential default conflict.
6194 // We need to check if this possibly conflicting method is either a superclass of the chosen
6195 // default implementation or is overridden by a non-default interface method. In either case
6196 // there is no conflict.
6197 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6198 !ContainsOverridingMethodOf(self,
6199 target_name_comparator,
6200 iftable,
6201 k,
6202 iface,
6203 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006204 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006205 << current_method->PrettyMethod() << " and "
6206 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6207 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006208 *out_default_method = nullptr;
6209 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006210 } else {
6211 break; // Continue checking at the next interface.
6212 }
6213 } else {
Alex Light9139e002015-10-09 15:59:48 -07006214 // chosen_iface == null
6215 if (!ContainsOverridingMethodOf(self,
6216 target_name_comparator,
6217 iftable,
6218 k,
6219 iface,
6220 image_pointer_size_)) {
6221 // Don't set this as the chosen interface if something else is overriding it (because that
6222 // other interface would be potentially chosen instead if it was default). If the other
6223 // interface was abstract then we wouldn't select this interface as chosen anyway since
6224 // the abstract method masks it.
6225 *out_default_method = current_method;
6226 chosen_iface.Assign(iface.Get());
6227 // We should now finish traversing the graph to find if we have default methods that
6228 // conflict.
6229 } else {
David Sehr709b0702016-10-13 09:12:37 -07006230 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6231 << "' was "
6232 << "skipped because it was overridden by an abstract method in a "
6233 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006234 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006235 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006236 break;
6237 }
6238 }
Alex Light9139e002015-10-09 15:59:48 -07006239 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006240 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6241 << "' selected "
6242 << "as the implementation for '" << target_method->PrettyMethod()
6243 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006244 return DefaultMethodSearchResult::kDefaultFound;
6245 } else {
6246 return DefaultMethodSearchResult::kAbstractFound;
6247 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006248}
6249
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006250ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006251 ArtMethod* conflict_method,
6252 ArtMethod* interface_method,
6253 ArtMethod* method,
6254 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006255 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006256 Runtime* const runtime = Runtime::Current();
6257 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6258 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6259
6260 // Create a new entry if the existing one is the shared conflict method.
6261 ArtMethod* new_conflict_method = new_entry
6262 ? runtime->CreateImtConflictMethod(linear_alloc)
6263 : conflict_method;
6264
6265 // Allocate a new table. Note that we will leak this table at the next conflict,
6266 // but that's a tradeoff compared to making the table fixed size.
6267 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006268 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6269 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006270 if (data == nullptr) {
6271 LOG(ERROR) << "Failed to allocate conflict table";
6272 return conflict_method;
6273 }
6274 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6275 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006276 method,
6277 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006278
6279 // Do a fence to ensure threads see the data in the table before it is assigned
6280 // to the conflict method.
6281 // Note that there is a race in the presence of multiple threads and we may leak
6282 // memory from the LinearAlloc, but that's a tradeoff compared to using
6283 // atomic operations.
6284 QuasiAtomic::ThreadFenceRelease();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006285 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006286 return new_conflict_method;
6287}
6288
Vladimir Marko921094a2017-01-12 18:37:06 +00006289bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6290 Handle<mirror::Class> klass,
6291 Handle<mirror::IfTable> iftable) {
6292 DCHECK(!klass->IsInterface());
6293 const bool has_superclass = klass->HasSuperClass();
6294 const bool extend_super_iftable = has_superclass;
6295 const size_t ifcount = klass->GetIfTableCount();
6296 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6297 for (size_t i = 0; i < ifcount; ++i) {
6298 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6299 if (num_methods > 0) {
6300 const bool is_super = i < super_ifcount;
6301 // This is an interface implemented by a super-class. Therefore we can just copy the method
6302 // array from the superclass.
6303 const bool super_interface = is_super && extend_super_iftable;
6304 ObjPtr<mirror::PointerArray> method_array;
6305 if (super_interface) {
6306 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6307 DCHECK(if_table != nullptr);
6308 DCHECK(if_table->GetMethodArray(i) != nullptr);
6309 // If we are working on a super interface, try extending the existing method array.
6310 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
6311 } else {
6312 method_array = AllocPointerArray(self, num_methods);
6313 }
6314 if (UNLIKELY(method_array == nullptr)) {
6315 self->AssertPendingOOMException();
6316 return false;
6317 }
6318 iftable->SetMethodArray(i, method_array);
6319 }
6320 }
6321 return true;
6322}
6323
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006324void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6325 ArtMethod* imt_conflict_method,
6326 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006327 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006328 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006329 // Place method in imt if entry is empty, place conflict otherwise.
6330 if (*imt_ref == unimplemented_method) {
6331 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006332 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006333 // If we are not a conflict and we have the same signature and name as the imt
6334 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006335 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6336 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006337 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006338 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006339 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006340 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006341 *imt_ref = current_method;
6342 } else {
Alex Light9139e002015-10-09 15:59:48 -07006343 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006344 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006345 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006346 } else {
6347 // Place the default conflict method. Note that there may be an existing conflict
6348 // method in the IMT, but it could be one tailored to the super class, with a
6349 // specific ImtConflictTable.
6350 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006351 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006352 }
6353}
6354
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006355void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006356 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6357 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006358 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006359 Runtime* const runtime = Runtime::Current();
6360 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6361 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006362 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006363 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006364 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006365 FillIMTFromIfTable(klass->GetIfTable(),
6366 unimplemented_method,
6367 conflict_method,
6368 klass,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006369 /*create_conflict_tables*/true,
6370 /*ignore_copied_methods*/false,
6371 &new_conflict,
6372 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006373 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006374 if (!klass->ShouldHaveImt()) {
6375 return;
6376 }
6377 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6378 // we can just use the same pointer.
6379 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006380 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006381 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6382 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6383 bool same = true;
6384 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6385 ArtMethod* method = imt_data[i];
6386 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6387 if (method != super_method) {
6388 bool is_conflict_table = method->IsRuntimeMethod() &&
6389 method != unimplemented_method &&
6390 method != conflict_method;
6391 // Verify conflict contents.
6392 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6393 super_method != unimplemented_method &&
6394 super_method != conflict_method;
6395 if (!is_conflict_table || !super_conflict_table) {
6396 same = false;
6397 } else {
6398 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6399 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6400 same = same && table1->Equals(table2, image_pointer_size_);
6401 }
6402 }
6403 }
6404 if (same) {
6405 imt = super_imt;
6406 }
6407 }
6408 if (imt == nullptr) {
6409 imt = klass->GetImt(image_pointer_size_);
6410 DCHECK(imt != nullptr);
6411 imt->Populate(imt_data, image_pointer_size_);
6412 } else {
6413 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006414 }
6415}
6416
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006417ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6418 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006419 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006420 void* data = linear_alloc->Alloc(Thread::Current(),
6421 ImtConflictTable::ComputeSize(count,
6422 image_pointer_size));
6423 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6424}
6425
6426ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6427 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6428}
6429
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006430void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006431 ArtMethod* unimplemented_method,
6432 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006433 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006434 bool create_conflict_tables,
6435 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006436 /*out*/bool* new_conflict,
6437 /*out*/ArtMethod** imt) {
6438 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006439 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006440 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006441 const size_t num_virtuals = interface->NumVirtualMethods();
6442 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6443 // Virtual methods can be larger than the if table methods if there are default methods.
6444 DCHECK_GE(num_virtuals, method_array_count);
6445 if (kIsDebugBuild) {
6446 if (klass->IsInterface()) {
6447 DCHECK_EQ(method_array_count, 0u);
6448 } else {
6449 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6450 }
6451 }
6452 if (method_array_count == 0) {
6453 continue;
6454 }
6455 auto* method_array = if_table->GetMethodArray(i);
6456 for (size_t j = 0; j < method_array_count; ++j) {
6457 ArtMethod* implementation_method =
6458 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6459 if (ignore_copied_methods && implementation_method->IsCopied()) {
6460 continue;
6461 }
6462 DCHECK(implementation_method != nullptr);
6463 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6464 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6465 // or interface methods in the IMT here they will not create extra conflicts since we compare
6466 // names and signatures in SetIMTRef.
6467 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006468 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006469
6470 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6471 // the same implementation method, keep track of this to avoid creating a conflict table in
6472 // this case.
6473
6474 // Conflict table size for each IMT slot.
6475 ++conflict_counts[imt_index];
6476
6477 SetIMTRef(unimplemented_method,
6478 imt_conflict_method,
6479 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006480 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006481 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006482 }
6483 }
6484
6485 if (create_conflict_tables) {
6486 // Create the conflict tables.
6487 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006488 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006489 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006490 if (imt[i] == imt_conflict_method) {
6491 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6492 if (new_table != nullptr) {
6493 ArtMethod* new_conflict_method =
6494 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6495 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6496 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006497 } else {
6498 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006499 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006500 }
6501 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006502 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006503 }
6504 }
6505
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006506 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006507 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006508 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6509 // Virtual methods can be larger than the if table methods if there are default methods.
6510 if (method_array_count == 0) {
6511 continue;
6512 }
6513 auto* method_array = if_table->GetMethodArray(i);
6514 for (size_t j = 0; j < method_array_count; ++j) {
6515 ArtMethod* implementation_method =
6516 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6517 if (ignore_copied_methods && implementation_method->IsCopied()) {
6518 continue;
6519 }
6520 DCHECK(implementation_method != nullptr);
6521 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006522 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006523 if (!imt[imt_index]->IsRuntimeMethod() ||
6524 imt[imt_index] == unimplemented_method ||
6525 imt[imt_index] == imt_conflict_method) {
6526 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006527 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006528 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6529 const size_t num_entries = table->NumEntries(image_pointer_size_);
6530 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6531 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006532 }
6533 }
6534 }
6535}
6536
Alex Lighteb7c1442015-08-31 13:17:42 -07006537// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6538// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006539static bool NotSubinterfaceOfAny(
6540 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6541 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006542 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006543 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006544 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006545 for (ObjPtr<mirror::Class> c : classes) {
6546 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006547 return false;
6548 }
6549 }
6550 return true;
6551}
6552
6553// Fills in and flattens the interface inheritance hierarchy.
6554//
6555// By the end of this function all interfaces in the transitive closure of to_process are added to
6556// the iftable and every interface precedes all of its sub-interfaces in this list.
6557//
6558// all I, J: Interface | I <: J implies J precedes I
6559//
6560// (note A <: B means that A is a subtype of B)
6561//
6562// This returns the total number of items in the iftable. The iftable might be resized down after
6563// this call.
6564//
6565// We order this backwards so that we do not need to reorder superclass interfaces when new
6566// interfaces are added in subclass's interface tables.
6567//
6568// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6569// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6570// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6571// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006572static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006573 size_t super_ifcount,
6574 std::vector<mirror::Class*> to_process)
6575 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006576 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006577 // This is the set of all class's already in the iftable. Used to make checking if a class has
6578 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006579 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006580 // The first super_ifcount elements are from the superclass. We note that they are already added.
6581 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006582 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006583 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6584 classes_in_iftable.insert(iface);
6585 }
6586 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006587 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006588 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6589 // At this point in the loop current-iface-list has the invariant that:
6590 // for every pair of interfaces I,J within it:
6591 // if index_of(I) < index_of(J) then I is not a subtype of J
6592
6593 // If we have already seen this element then all of its super-interfaces must already be in the
6594 // current-iface-list so we can skip adding it.
6595 if (!ContainsElement(classes_in_iftable, interface)) {
6596 // We haven't seen this interface so add all of its super-interfaces onto the
6597 // current-iface-list, skipping those already on it.
6598 int32_t ifcount = interface->GetIfTableCount();
6599 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006600 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006601 if (!ContainsElement(classes_in_iftable, super_interface)) {
6602 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6603 classes_in_iftable.insert(super_interface);
6604 iftable->SetInterface(filled_ifcount, super_interface);
6605 filled_ifcount++;
6606 }
6607 }
6608 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6609 // Place this interface onto the current-iface-list after all of its super-interfaces.
6610 classes_in_iftable.insert(interface);
6611 iftable->SetInterface(filled_ifcount, interface);
6612 filled_ifcount++;
6613 } else if (kIsDebugBuild) {
6614 // Check all super-interfaces are already in the list.
6615 int32_t ifcount = interface->GetIfTableCount();
6616 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006617 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006618 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006619 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6620 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006621 }
6622 }
6623 }
6624 if (kIsDebugBuild) {
6625 // Check that the iftable is ordered correctly.
6626 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006627 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006628 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006629 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006630 // !(if_a <: if_b)
6631 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006632 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6633 << ") extends "
6634 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006635 << "interface list.";
6636 }
6637 }
6638 }
6639 return filled_ifcount;
6640}
6641
6642bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6643 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6644 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006645 const bool has_superclass = klass->HasSuperClass();
6646 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006647 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006648 const size_t num_interfaces =
6649 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006650 if (num_interfaces == 0) {
6651 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006652 if (LIKELY(has_superclass)) {
6653 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6654 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006655 // Class implements no interfaces.
6656 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006657 return true;
6658 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006659 // Class implements same interfaces as parent, are any of these not marker interfaces?
6660 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006661 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006662 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006663 if (super_iftable->GetMethodArrayCount(i) > 0) {
6664 has_non_marker_interface = true;
6665 break;
6666 }
6667 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006668 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006669 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006670 klass->SetIfTable(super_iftable);
6671 return true;
6672 }
6673 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006674 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006675 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006676 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006677 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006678 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006679 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006680 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006681 if (UNLIKELY(!interface->IsInterface())) {
6682 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006683 ThrowIncompatibleClassChangeError(klass.Get(),
6684 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006685 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006686 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6687 return false;
6688 }
6689 ifcount += interface->GetIfTableCount();
6690 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006691 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006692 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006693 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006694 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006695 return false;
6696 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006697 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006698 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006699 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006700 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006701 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006702 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006703 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006704 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006705
6706 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6707 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6708 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006709 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006710
6711 size_t new_ifcount;
6712 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006713 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Alex Lighteb7c1442015-08-31 13:17:42 -07006714 std::vector<mirror::Class*> to_add;
6715 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006716 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006717 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006718 to_add.push_back(interface.Ptr());
Ian Rogersb52b01a2012-01-12 17:01:38 -08006719 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006720
6721 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006722 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006723
Ian Rogers7b078e82014-09-10 14:44:24 -07006724 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006725
Ian Rogersb52b01a2012-01-12 17:01:38 -08006726 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07006727 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006728 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006729 iftable.Assign(down_cast<mirror::IfTable*>(
Alex Lighteb7c1442015-08-31 13:17:42 -07006730 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006731 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006732 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006733 return false;
6734 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006735 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08006736 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006737 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006738 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006739 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07006740 return true;
6741}
6742
Alex Light1f3925d2016-09-07 12:04:20 -07006743// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
6744// of methods must be unique.
6745static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
6746 return nullptr;
6747}
6748
6749template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07006750static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07006751 const ScopedArenaVector<ArtMethod*>& list,
6752 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006753 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006754 for (ArtMethod* method : list) {
6755 if (cmp.HasSameNameAndSignature(method)) {
6756 return method;
6757 }
6758 }
Alex Light1f3925d2016-09-07 12:04:20 -07006759 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07006760}
6761
Alex Light1f3925d2016-09-07 12:04:20 -07006762// Check that all vtable entries are present in this class's virtuals or are the same as a
6763// superclasses vtable entry.
6764static void CheckClassOwnsVTableEntries(Thread* self,
6765 Handle<mirror::Class> klass,
6766 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006767 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07006768 StackHandleScope<2> hs(self);
6769 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006770 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07006771 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006772 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006773 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6774 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6775 CHECK(m != nullptr);
6776
Alex Lighta41a30782017-03-29 11:33:19 -07006777 if (m->GetMethodIndexDuringLinking() != i) {
6778 LOG(WARNING) << m->PrettyMethod()
6779 << " has an unexpected method index for its spot in the vtable for class"
6780 << klass->PrettyClass();
6781 }
Alex Lighte64300b2015-12-15 15:02:47 -08006782 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6783 auto is_same_method = [m] (const ArtMethod& meth) {
6784 return &meth == m;
6785 };
Alex Light3f980532017-03-17 15:10:32 -07006786 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6787 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
6788 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
6789 << klass->PrettyClass() << " or any of its superclasses!";
6790 }
Alex Lighte64300b2015-12-15 15:02:47 -08006791 }
6792}
6793
Alex Light1f3925d2016-09-07 12:04:20 -07006794// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
6795// method is overridden in a subclass.
6796static void CheckVTableHasNoDuplicates(Thread* self,
6797 Handle<mirror::Class> klass,
6798 PointerSize pointer_size)
6799 REQUIRES_SHARED(Locks::mutator_lock_) {
6800 StackHandleScope<1> hs(self);
6801 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6802 int32_t num_entries = vtable->GetLength();
6803 for (int32_t i = 0; i < num_entries; i++) {
6804 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6805 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe).
6806 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6807 vtable_entry->GetAccessFlags())) {
6808 continue;
6809 }
6810 MethodNameAndSignatureComparator name_comparator(
6811 vtable_entry->GetInterfaceMethodIfProxy(pointer_size));
Alex Lightc7a420c2016-10-18 14:33:18 -07006812 for (int32_t j = i + 1; j < num_entries; j++) {
Alex Light1f3925d2016-09-07 12:04:20 -07006813 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Alex Lightc7a420c2016-10-18 14:33:18 -07006814 if (!klass->CanAccessMember(other_entry->GetDeclaringClass(),
6815 other_entry->GetAccessFlags())) {
6816 continue;
6817 }
Alex Light3f980532017-03-17 15:10:32 -07006818 if (vtable_entry == other_entry ||
6819 name_comparator.HasSameNameAndSignature(
6820 other_entry->GetInterfaceMethodIfProxy(pointer_size))) {
6821 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
6822 << klass->PrettyClass() << " in method " << vtable_entry->PrettyMethod()
6823 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(vtable_entry) << ") and "
6824 << other_entry->PrettyMethod() << " (0x" << std::hex
6825 << reinterpret_cast<uintptr_t>(other_entry) << ")";
6826 }
Alex Light1f3925d2016-09-07 12:04:20 -07006827 }
6828 }
6829}
6830
6831static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
6832 REQUIRES_SHARED(Locks::mutator_lock_) {
6833 CheckClassOwnsVTableEntries(self, klass, pointer_size);
6834 CheckVTableHasNoDuplicates(self, klass, pointer_size);
6835}
6836
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006837void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
6838 ArtMethod* unimplemented_method,
6839 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006840 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006841 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07006842 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006843 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006844 if (super_class->ShouldHaveImt()) {
6845 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6846 for (size_t i = 0; i < ImTable::kSize; ++i) {
6847 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07006848 }
6849 } else {
6850 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006851 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08006852 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006853 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006854 FillIMTFromIfTable(if_table,
6855 unimplemented_method,
6856 imt_conflict_method,
6857 klass.Get(),
6858 /*create_conflict_table*/false,
6859 /*ignore_copied_methods*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006860 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006861 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07006862 }
6863 }
6864}
6865
Vladimir Marko921094a2017-01-12 18:37:06 +00006866class ClassLinker::LinkInterfaceMethodsHelper {
6867 public:
6868 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
6869 Handle<mirror::Class> klass,
6870 Thread* self,
6871 Runtime* runtime)
6872 : class_linker_(class_linker),
6873 klass_(klass),
6874 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
6875 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
6876 self_(self),
6877 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
6878 allocator_(&stack_),
6879 default_conflict_methods_(allocator_.Adapter()),
6880 overriding_default_conflict_methods_(allocator_.Adapter()),
6881 miranda_methods_(allocator_.Adapter()),
6882 default_methods_(allocator_.Adapter()),
6883 overriding_default_methods_(allocator_.Adapter()),
6884 move_table_(allocator_.Adapter()) {
6885 }
6886
6887 ArtMethod* FindMethod(ArtMethod* interface_method,
6888 MethodNameAndSignatureComparator& interface_name_comparator,
6889 ArtMethod* vtable_impl)
6890 REQUIRES_SHARED(Locks::mutator_lock_);
6891
6892 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
6893 MethodNameAndSignatureComparator& interface_name_comparator)
6894 REQUIRES_SHARED(Locks::mutator_lock_);
6895
6896 bool HasNewVirtuals() const {
6897 return !(miranda_methods_.empty() &&
6898 default_methods_.empty() &&
6899 overriding_default_methods_.empty() &&
6900 overriding_default_conflict_methods_.empty() &&
6901 default_conflict_methods_.empty());
6902 }
6903
6904 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
6905
6906 ObjPtr<mirror::PointerArray> UpdateVtable(
6907 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
6908 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
6909
6910 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
6911
6912 void UpdateIMT(ArtMethod** out_imt);
6913
6914 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
6915 if (kIsDebugBuild) {
6916 PointerSize pointer_size = class_linker_->GetImagePointerSize();
6917 // Check that there are no stale methods are in the dex cache array.
6918 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
6919 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
6920 auto* m = mirror::DexCache::GetElementPtrSize(resolved_methods, i, pointer_size);
6921 CHECK(move_table_.find(m) == move_table_.end() ||
6922 // The original versions of copied methods will still be present so allow those too.
6923 // Note that if the first check passes this might fail to GetDeclaringClass().
6924 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
6925 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
6926 [m] (ArtMethod& meth) {
6927 return &meth == m;
6928 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
6929 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
6930 }
6931 }
6932 }
6933
6934 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
6935 LengthPrefixedArray<ArtMethod>* methods) {
6936 if (kIsDebugBuild) {
6937 CHECK(methods != nullptr);
6938 // Put some random garbage in old methods to help find stale pointers.
6939 if (methods != old_methods && old_methods != nullptr) {
6940 // Need to make sure the GC is not running since it could be scanning the methods we are
6941 // about to overwrite.
6942 ScopedThreadStateChange tsc(self_, kSuspended);
6943 gc::ScopedGCCriticalSection gcs(self_,
6944 gc::kGcCauseClassLinker,
6945 gc::kCollectorTypeClassLinker);
6946 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
6947 method_size_,
6948 method_alignment_);
6949 memset(old_methods, 0xFEu, old_size);
6950 }
6951 }
6952 }
6953
6954 private:
6955 size_t NumberOfNewVirtuals() const {
6956 return miranda_methods_.size() +
6957 default_methods_.size() +
6958 overriding_default_conflict_methods_.size() +
6959 overriding_default_methods_.size() +
6960 default_conflict_methods_.size();
6961 }
6962
6963 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
6964 return !klass_->IsInterface();
6965 }
6966
6967 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
6968 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
6969 << "Interfaces should only have default-conflict methods appended to them.";
6970 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
6971 << miranda_methods_.size()
6972 << " default_methods=" << default_methods_.size()
6973 << " overriding_default_methods=" << overriding_default_methods_.size()
6974 << " default_conflict_methods=" << default_conflict_methods_.size()
6975 << " overriding_default_conflict_methods="
6976 << overriding_default_conflict_methods_.size();
6977 }
6978
6979 ClassLinker* class_linker_;
6980 Handle<mirror::Class> klass_;
6981 size_t method_alignment_;
6982 size_t method_size_;
6983 Thread* const self_;
6984
6985 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
6986 // the virtual methods array.
6987 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
6988 // during cross compilation.
6989 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
6990 ArenaStack stack_;
6991 ScopedArenaAllocator allocator_;
6992
6993 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
6994 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
6995 ScopedArenaVector<ArtMethod*> miranda_methods_;
6996 ScopedArenaVector<ArtMethod*> default_methods_;
6997 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
6998
6999 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7000};
7001
7002ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7003 ArtMethod* interface_method,
7004 MethodNameAndSignatureComparator& interface_name_comparator,
7005 ArtMethod* vtable_impl) {
7006 ArtMethod* current_method = nullptr;
7007 switch (class_linker_->FindDefaultMethodImplementation(self_,
7008 interface_method,
7009 klass_,
7010 /*out*/&current_method)) {
7011 case DefaultMethodSearchResult::kDefaultConflict: {
7012 // Default method conflict.
7013 DCHECK(current_method == nullptr);
7014 ArtMethod* default_conflict_method = nullptr;
7015 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7016 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7017 default_conflict_method = vtable_impl;
7018 } else {
7019 // See if we already have a conflict method for this method.
7020 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7021 interface_name_comparator,
7022 default_conflict_methods_,
7023 overriding_default_conflict_methods_);
7024 if (LIKELY(preexisting_conflict != nullptr)) {
7025 // We already have another conflict we can reuse.
7026 default_conflict_method = preexisting_conflict;
7027 } else {
7028 // Note that we do this even if we are an interface since we need to create this and
7029 // cannot reuse another classes.
7030 // Create a new conflict method for this to use.
7031 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7032 new(default_conflict_method) ArtMethod(interface_method,
7033 class_linker_->GetImagePointerSize());
7034 if (vtable_impl == nullptr) {
7035 // Save the conflict method. We need to add it to the vtable.
7036 default_conflict_methods_.push_back(default_conflict_method);
7037 } else {
7038 // Save the conflict method but it is already in the vtable.
7039 overriding_default_conflict_methods_.push_back(default_conflict_method);
7040 }
7041 }
7042 }
7043 current_method = default_conflict_method;
7044 break;
7045 } // case kDefaultConflict
7046 case DefaultMethodSearchResult::kDefaultFound: {
7047 DCHECK(current_method != nullptr);
7048 // Found a default method.
7049 if (vtable_impl != nullptr &&
7050 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7051 // We found a default method but it was the same one we already have from our
7052 // superclass. Don't bother adding it to our vtable again.
7053 current_method = vtable_impl;
7054 } else if (LIKELY(FillTables())) {
7055 // Interfaces don't need to copy default methods since they don't have vtables.
7056 // Only record this default method if it is new to save space.
7057 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7058 // would make lookup for interface super much faster. (We would only need to scan
7059 // the iftable to find if there is a NSME or AME.)
7060 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7061 default_methods_,
7062 overriding_default_methods_);
7063 if (old == nullptr) {
7064 // We found a default method implementation and there were no conflicts.
7065 if (vtable_impl == nullptr) {
7066 // Save the default method. We need to add it to the vtable.
7067 default_methods_.push_back(current_method);
7068 } else {
7069 // Save the default method but it is already in the vtable.
7070 overriding_default_methods_.push_back(current_method);
7071 }
7072 } else {
7073 CHECK(old == current_method) << "Multiple default implementations selected!";
7074 }
7075 }
7076 break;
7077 } // case kDefaultFound
7078 case DefaultMethodSearchResult::kAbstractFound: {
7079 DCHECK(current_method == nullptr);
7080 // Abstract method masks all defaults.
7081 if (vtable_impl != nullptr &&
7082 vtable_impl->IsAbstract() &&
7083 !vtable_impl->IsDefaultConflicting()) {
7084 // We need to make this an abstract method but the version in the vtable already is so
7085 // don't do anything.
7086 current_method = vtable_impl;
7087 }
7088 break;
7089 } // case kAbstractFound
7090 }
7091 return current_method;
7092}
7093
7094ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7095 ArtMethod* interface_method,
7096 MethodNameAndSignatureComparator& interface_name_comparator) {
7097 // Find out if there is already a miranda method we can use.
7098 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7099 miranda_methods_);
7100 if (miranda_method == nullptr) {
7101 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7102 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7103 CHECK(miranda_method != nullptr);
7104 // Point the interface table at a phantom slot.
7105 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7106 miranda_methods_.push_back(miranda_method);
7107 }
7108 return miranda_method;
7109}
7110
7111void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7112 LogNewVirtuals();
7113
7114 const size_t old_method_count = klass_->NumMethods();
7115 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7116 DCHECK_NE(old_method_count, new_method_count);
7117
7118 // Attempt to realloc to save RAM if possible.
7119 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7120 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7121 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7122 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7123 // CopyFrom has internal read barriers.
7124 //
7125 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7126 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7127 method_size_,
7128 method_alignment_);
7129 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7130 method_size_,
7131 method_alignment_);
7132 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7133 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
7134 Runtime::Current()->GetLinearAlloc()->Realloc(
7135 self_, old_methods, old_methods_ptr_size, new_size));
7136 CHECK(methods != nullptr); // Native allocation failure aborts.
7137
7138 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7139 if (methods != old_methods) {
7140 // Maps from heap allocated miranda method to linear alloc miranda method.
7141 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7142 // Copy over the old methods.
7143 for (auto& m : klass_->GetMethods(pointer_size)) {
7144 move_table_.emplace(&m, &*out);
7145 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7146 // barriers when it copies.
7147 out->CopyFrom(&m, pointer_size);
7148 ++out;
7149 }
7150 }
7151 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7152 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7153 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007154 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7155 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007156 ArtMethod& new_method = *out;
7157 new_method.CopyFrom(mir_method, pointer_size);
7158 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7159 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7160 << "Miranda method should be abstract!";
7161 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007162 // Update the entry in the method array, as the array will be used for future lookups,
7163 // where thread suspension is allowed.
7164 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7165 // would not see them.
7166 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007167 ++out;
7168 }
7169 // We need to copy the default methods into our own method table since the runtime requires that
7170 // every method on a class's vtable be in that respective class's virtual method table.
7171 // NOTE This means that two classes might have the same implementation of a method from the same
7172 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7173 // default method found on a class with one found on the declaring interface directly and must
7174 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007175 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7176 &overriding_default_methods_}) {
7177 for (size_t i = 0; i < methods_vec->size(); ++i) {
7178 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007179 ArtMethod& new_method = *out;
7180 new_method.CopyFrom(def_method, pointer_size);
7181 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7182 // verified yet it shouldn't have methods that are skipping access checks.
7183 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7184 // methods are skip_access_checks.
7185 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7186 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7187 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7188 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007189 // Update the entry in the method array, as the array will be used for future lookups,
7190 // where thread suspension is allowed.
7191 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7192 // would not see them.
7193 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007194 ++out;
7195 }
7196 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007197 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7198 &overriding_default_conflict_methods_}) {
7199 for (size_t i = 0; i < methods_vec->size(); ++i) {
7200 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007201 ArtMethod& new_method = *out;
7202 new_method.CopyFrom(conf_method, pointer_size);
7203 // This is a type of default method (there are default method impls, just a conflict) so
7204 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7205 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7206 // methods that are skipping access checks.
7207 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
7208 constexpr uint32_t kMaskFlags = ~(kAccAbstract | kAccSkipAccessChecks);
7209 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7210 DCHECK(new_method.IsDefaultConflicting());
7211 // The actual method might or might not be marked abstract since we just copied it from a
7212 // (possibly default) interface method. We need to set it entry point to be the bridge so
7213 // that the compiler will not invoke the implementation of whatever method we copied from.
7214 EnsureThrowsInvocationError(class_linker_, &new_method);
7215 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007216 // Update the entry in the method array, as the array will be used for future lookups,
7217 // where thread suspension is allowed.
7218 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7219 // would not see them.
7220 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007221 ++out;
7222 }
7223 }
7224 methods->SetSize(new_method_count);
7225 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7226}
7227
7228ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7229 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7230 ObjPtr<mirror::PointerArray> old_vtable) {
7231 // Update the vtable to the new method structures. We can skip this for interfaces since they
7232 // do not have vtables.
7233 const size_t old_vtable_count = old_vtable->GetLength();
7234 const size_t new_vtable_count = old_vtable_count +
7235 miranda_methods_.size() +
7236 default_methods_.size() +
7237 default_conflict_methods_.size();
7238
7239 ObjPtr<mirror::PointerArray> vtable =
7240 down_cast<mirror::PointerArray*>(old_vtable->CopyOf(self_, new_vtable_count));
7241 if (UNLIKELY(vtable == nullptr)) {
7242 self_->AssertPendingOOMException();
7243 return nullptr;
7244 }
7245
7246 size_t vtable_pos = old_vtable_count;
7247 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7248 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7249 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7250 default_conflict_methods_,
7251 miranda_methods_}) {
7252 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007253 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007254 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7255 // fields are references into the dex file the method was defined in. Since the ArtMethod
7256 // does not store that information it uses declaring_class_->dex_cache_.
7257 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7258 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7259 ++vtable_pos;
7260 }
7261 }
7262 DCHECK_EQ(vtable_pos, new_vtable_count);
7263
7264 // Update old vtable methods. We use the default_translations map to figure out what each
7265 // vtable entry should be updated to, if they need to be at all.
7266 for (size_t i = 0; i < old_vtable_count; ++i) {
7267 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7268 // Try and find what we need to change this method to.
7269 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007270 if (translation_it != default_translations.end()) {
7271 if (translation_it->second.IsInConflict()) {
7272 // Find which conflict method we are to use for this method.
7273 MethodNameAndSignatureComparator old_method_comparator(
7274 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7275 // We only need to look through overriding_default_conflict_methods since this is an
7276 // overridden method we are fixing up here.
7277 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7278 old_method_comparator, overriding_default_conflict_methods_);
7279 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7280 translated_method = new_conflict_method;
7281 } else if (translation_it->second.IsAbstract()) {
7282 // Find which miranda method we are to use for this method.
7283 MethodNameAndSignatureComparator old_method_comparator(
7284 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7285 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7286 miranda_methods_);
7287 DCHECK(miranda_method != nullptr);
7288 translated_method = miranda_method;
7289 } else {
7290 // Normal default method (changed from an older default or abstract interface method).
7291 DCHECK(translation_it->second.IsTranslation());
7292 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007293 auto it = move_table_.find(translated_method);
7294 DCHECK(it != move_table_.end());
7295 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007296 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007297 } else {
7298 auto it = move_table_.find(translated_method);
7299 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007300 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007301
7302 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007303 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007304 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007305 if (kIsDebugBuild) {
7306 auto* methods = klass_->GetMethodsPtr();
7307 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007308 reinterpret_cast<uintptr_t>(translated_method));
7309 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007310 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7311 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007312 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007313 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007314 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007315 }
7316 }
7317 klass_->SetVTable(vtable.Ptr());
7318 return vtable;
7319}
7320
7321void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7322 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7323 const size_t ifcount = klass_->GetIfTableCount();
7324 // Go fix up all the stale iftable pointers.
7325 for (size_t i = 0; i < ifcount; ++i) {
7326 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7327 auto* method_array = iftable->GetMethodArray(i);
7328 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7329 DCHECK(m != nullptr) << klass_->PrettyClass();
7330 auto it = move_table_.find(m);
7331 if (it != move_table_.end()) {
7332 auto* new_m = it->second;
7333 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7334 method_array->SetElementPtrSize(j, new_m, pointer_size);
7335 }
7336 }
7337 }
7338}
7339
7340void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7341 // Fix up IMT next.
7342 for (size_t i = 0; i < ImTable::kSize; ++i) {
7343 auto it = move_table_.find(out_imt[i]);
7344 if (it != move_table_.end()) {
7345 out_imt[i] = it->second;
7346 }
7347 }
7348}
7349
Alex Light705ad492015-09-21 11:36:30 -07007350// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007351bool ClassLinker::LinkInterfaceMethods(
7352 Thread* self,
7353 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007354 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007355 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007356 ArtMethod** out_imt) {
7357 StackHandleScope<3> hs(self);
7358 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007359
7360 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007361 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007362 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007363 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007364 const size_t ifcount = klass->GetIfTableCount();
7365
Vladimir Marko921094a2017-01-12 18:37:06 +00007366 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007367
7368 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7369 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007370 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007371 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007372 const bool extend_super_iftable = has_superclass;
7373 if (has_superclass && fill_tables) {
7374 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007375 unimplemented_method,
7376 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007377 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007378 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007379 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007380 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7381 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007382 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007383 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7384 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007385 }
7386 }
7387
Vladimir Marko921094a2017-01-12 18:37:06 +00007388 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7389
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007390 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007391 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007392 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7393 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7394 // they will already be null. This has the additional benefit that the declarer of a miranda
7395 // method will actually declare an abstract method.
7396 for (size_t i = ifcount; i != 0; ) {
7397 --i;
7398
7399 DCHECK_GE(i, 0u);
7400 DCHECK_LT(i, ifcount);
7401
Alex Light705ad492015-09-21 11:36:30 -07007402 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007403 if (num_methods > 0) {
7404 StackHandleScope<2> hs2(self);
7405 const bool is_super = i < super_ifcount;
7406 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007407 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7408 // conflict methods. Just set this as nullptr in those cases.
7409 Handle<mirror::PointerArray> method_array(fill_tables
7410 ? hs2.NewHandle(iftable->GetMethodArray(i))
7411 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007412
Alex Lighte64300b2015-12-15 15:02:47 -08007413 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007414 ScopedNullHandle<mirror::PointerArray> null_handle;
7415 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007416 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007417
Alex Light9139e002015-10-09 15:59:48 -07007418 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7419 // and confusing. Default methods should always look through all the superclasses
7420 // because they are the last choice of an implementation. We get around this by looking
7421 // at the super-classes iftable methods (copied into method_array previously) when we are
7422 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007423 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007424 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007425 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007426 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007427 using_virtuals = true;
7428 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7429 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007430 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007431 // For a new interface, however, we need the whole vtable in case a new
7432 // interface method is implemented in the whole superclass.
7433 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007434 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007435 input_vtable_array = vtable;
7436 input_array_length = input_vtable_array->GetLength();
7437 }
Alex Lighte64300b2015-12-15 15:02:47 -08007438
Alex Lighteb7c1442015-08-31 13:17:42 -07007439 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007440 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007441 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007442 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007443 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Andreas Gampe75a7db62016-09-26 12:04:26 -07007444 uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Alex Lighteb7c1442015-08-31 13:17:42 -07007445 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007446 // For each method listed in the interface's method list, find the
7447 // matching method in our class's method list. We want to favor the
7448 // subclass over the superclass, which just requires walking
7449 // back from the end of the vtable. (This only matters if the
7450 // superclass defines a private method and this class redefines
7451 // it -- otherwise it would use the same vtable slot. In .dex files
7452 // those don't end up in the virtual method table, so it shouldn't
7453 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007454 //
7455 // To find defaults we need to do the same but also go over interfaces.
7456 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007457 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007458 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007459 ArtMethod* vtable_method = using_virtuals ?
7460 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007461 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7462 ArtMethod* vtable_method_for_name_comparison =
7463 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007464 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007465 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007466 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007467 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7468 // allocations.
7469 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007470 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007471 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007472 vtable_method->PrettyMethod().c_str(),
7473 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007474 return false;
Alex Light9139e002015-10-09 15:59:48 -07007475 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007476 // We might have a newer, better, default method for this, so we just skip it. If we
7477 // are still using this we will select it again when scanning for default methods. To
7478 // obviate the need to copy the method again we will make a note that we already found
7479 // a default here.
7480 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007481 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007482 break;
7483 } else {
7484 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007485 if (LIKELY(fill_tables)) {
7486 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7487 // Place method in imt if entry is empty, place conflict otherwise.
7488 SetIMTRef(unimplemented_method,
7489 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007490 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007491 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007492 /*out*/imt_ptr);
7493 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007494 break;
7495 }
7496 }
Alex Light9139e002015-10-09 15:59:48 -07007497 }
7498 // Continue on to the next method if we are done.
7499 if (LIKELY(found_impl)) {
7500 continue;
7501 } else if (LIKELY(super_interface)) {
7502 // Don't look for a default implementation when the super-method is implemented directly
7503 // by the class.
7504 //
7505 // See if we can use the superclasses method and skip searching everything else.
7506 // Note: !found_impl && super_interface
7507 CHECK(extend_super_iftable);
7508 // If this is a super_interface method it is possible we shouldn't override it because a
7509 // superclass could have implemented it directly. We get the method the superclass used
7510 // to implement this to know if we can override it with a default method. Doing this is
7511 // safe since we know that the super_iftable is filled in so we can simply pull it from
7512 // there. We don't bother if this is not a super-classes interface since in that case we
7513 // have scanned the entire vtable anyway and would have found it.
7514 // TODO This is rather dirty but it is faster than searching through the entire vtable
7515 // every time.
7516 ArtMethod* supers_method =
7517 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7518 DCHECK(supers_method != nullptr);
7519 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007520 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007521 // The method is not overridable by a default method (i.e. it is directly implemented
7522 // in some class). Therefore move onto the next interface method.
7523 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007524 } else {
7525 // If the super-classes method is override-able by a default method we need to keep
7526 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7527 // 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 -07007528 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7529 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7530 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007531 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007532 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7533 << " and not 'nullptr' or "
7534 << supers_method->PrettyMethod()
7535 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007536 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007537 }
7538 }
7539 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007540 ArtMethod* current_method = helper.FindMethod(interface_method,
7541 interface_name_comparator,
7542 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007543 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007544 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007545 // We could not find an implementation for this method and since it is a brand new
7546 // interface we searched the entire vtable (and all default methods) for an
7547 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007548 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7549 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007550 }
7551
7552 if (current_method != nullptr) {
7553 // We found a default method implementation. Record it in the iftable and IMT.
7554 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7555 SetIMTRef(unimplemented_method,
7556 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007557 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007558 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007559 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007560 }
7561 }
Alex Light705ad492015-09-21 11:36:30 -07007562 } // For each method in interface end.
7563 } // if (num_methods > 0)
7564 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007565 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007566 if (helper.HasNewVirtuals()) {
7567 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7568 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7569 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7570
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007571 // 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 -07007572 // suspension assert.
7573 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007574
Alex Light705ad492015-09-21 11:36:30 -07007575 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007576 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007577 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007578 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07007579 return false;
7580 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007581 helper.UpdateIfTable(iftable);
7582 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007583 }
Alex Light705ad492015-09-21 11:36:30 -07007584
Vladimir Marko921094a2017-01-12 18:37:06 +00007585 helper.CheckNoStaleMethodsInDexCache();
7586 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007587 } else {
7588 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007589 }
Alex Light705ad492015-09-21 11:36:30 -07007590 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007591 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007592 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007593 return true;
7594}
7595
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007596bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007597 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007598 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007599}
7600
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007601bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007602 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007603 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007604}
7605
Brian Carlstromdbc05252011-09-09 01:59:59 -07007606struct LinkFieldsComparator {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007607 explicit LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07007608 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007609 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007610 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007611 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07007612 // 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 -07007613 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7614 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08007615 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00007616 if (type1 == Primitive::kPrimNot) {
7617 // Reference always goes first.
7618 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08007619 }
Vladimir Markod5777482014-11-12 17:02:02 +00007620 if (type2 == Primitive::kPrimNot) {
7621 // Reference always goes first.
7622 return false;
7623 }
7624 size_t size1 = Primitive::ComponentSize(type1);
7625 size_t size2 = Primitive::ComponentSize(type2);
7626 if (size1 != size2) {
7627 // Larger primitive types go first.
7628 return size1 > size2;
7629 }
7630 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7631 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007632 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007633 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7634 // by name and for equal names by type id index.
7635 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7636 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07007637 }
7638};
7639
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007640bool ClassLinker::LinkFields(Thread* self,
7641 Handle<mirror::Class> klass,
7642 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007643 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07007644 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07007645 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007646 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7647 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007648
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007649 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07007650 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007651 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007652 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007653 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007654 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007655 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07007656 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007657 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007658 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007659 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007660 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007661
David Sehr709b0702016-10-13 09:12:37 -07007662 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007663
Brian Carlstromdbc05252011-09-09 01:59:59 -07007664 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07007665 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08007666 //
7667 // The overall sort order order is:
7668 // 1) All object reference fields, sorted alphabetically.
7669 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7670 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7671 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7672 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7673 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7674 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7675 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7676 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7677 //
7678 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7679 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007680 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07007681 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07007682 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07007683 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007684 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007685 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07007686 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7687 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07007688
Fred Shih381e4ca2014-08-25 17:24:27 -07007689 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07007690 size_t current_field = 0;
7691 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07007692 FieldGaps gaps;
7693
Brian Carlstromdbc05252011-09-09 01:59:59 -07007694 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007695 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007696 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07007697 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007698 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07007699 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007700 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007701 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7702 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07007703 MemberOffset old_offset = field_offset;
7704 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7705 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7706 }
Roland Levillain14d90572015-07-16 10:52:26 +01007707 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007708 grouped_and_sorted_fields.pop_front();
7709 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007710 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00007711 field_offset = MemberOffset(field_offset.Uint32Value() +
7712 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007713 }
Fred Shih381e4ca2014-08-25 17:24:27 -07007714 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7715 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00007716 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7717 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7718 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7719 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07007720 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
7721 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07007722 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007723
Elliott Hughesadb460d2011-10-05 17:02:34 -07007724 // 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 -07007725 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07007726 // We know there are no non-reference fields in the Reference classes, and we know
7727 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07007728 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007729 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07007730 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07007731 --num_reference_fields;
7732 }
7733
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007734 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007735 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007736 if (is_static) {
7737 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007738 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007739 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007740 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007741 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007742 if (num_reference_fields == 0 || super_class == nullptr) {
7743 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007744 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007745 if (super_class == nullptr ||
7746 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
7747 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007748 }
7749 }
7750 if (kIsDebugBuild) {
7751 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
7752 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007753 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007754 while (cur_super != nullptr) {
7755 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
7756 cur_super = cur_super->GetSuperClass();
7757 }
7758 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07007759 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007760 } else {
7761 // Check that there is at least num_reference_fields other than Object.class.
7762 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07007763 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007764 }
7765 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07007766 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007767 std::string temp;
7768 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
7769 size_t previous_size = klass->GetObjectSize();
7770 if (previous_size != 0) {
7771 // Make sure that we didn't originally have an incorrect size.
7772 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07007773 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007774 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007775 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007776 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007777
7778 if (kIsDebugBuild) {
7779 // Make sure that the fields array is ordered by name but all reference
7780 // offsets are at the beginning as far as alignment allows.
7781 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07007782 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00007783 : klass->GetFirstReferenceInstanceFieldOffset();
7784 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
7785 num_reference_fields *
7786 sizeof(mirror::HeapReference<mirror::Object>));
7787 MemberOffset current_ref_offset = start_ref_offset;
7788 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007789 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007790 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07007791 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
7792 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007793 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007794 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007795 // NOTE: The field names can be the same. This is not possible in the Java language
7796 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007797 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00007798 }
7799 Primitive::Type type = field->GetTypeAsPrimitiveType();
7800 bool is_primitive = type != Primitive::kPrimNot;
7801 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
7802 strcmp("referent", field->GetName()) == 0) {
7803 is_primitive = true; // We lied above, so we have to expect a lie here.
7804 }
7805 MemberOffset offset = field->GetOffsetDuringLinking();
7806 if (is_primitive) {
7807 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
7808 // Shuffled before references.
7809 size_t type_size = Primitive::ComponentSize(type);
7810 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
7811 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
7812 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
7813 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
7814 }
7815 } else {
7816 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
7817 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
7818 sizeof(mirror::HeapReference<mirror::Object>));
7819 }
7820 }
7821 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
7822 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007823 return true;
7824}
7825
Vladimir Marko76649e82014-11-10 18:32:59 +00007826// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007827void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007828 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007829 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007830 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007831 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007832 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007833 // Compute reference offsets unless our superclass overflowed.
7834 if (reference_offsets != mirror::Class::kClassWalkSuper) {
7835 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007836 if (num_reference_fields != 0u) {
7837 // All of the fields that contain object references are guaranteed be grouped in memory
7838 // starting at an appropriately aligned address after super class object data.
7839 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
7840 sizeof(mirror::HeapReference<mirror::Object>));
7841 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007842 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00007843 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007844 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007845 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00007846 reference_offsets |= (0xffffffffu << start_bit) &
7847 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007848 }
7849 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07007850 }
7851 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07007852 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007853}
7854
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007855mirror::String* ClassLinker::ResolveString(const DexFile& dex_file,
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007856 dex::StringIndex string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007857 Handle<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007858 DCHECK(dex_cache != nullptr);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007859 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007860 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007861 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007862 return resolved.Ptr();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007863 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07007864 uint32_t utf16_length;
7865 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007866 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007867 if (string != nullptr) {
7868 dex_cache->SetResolvedString(string_idx, string);
7869 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007870 return string.Ptr();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007871}
7872
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007873mirror::String* ClassLinker::LookupString(const DexFile& dex_file,
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007874 dex::StringIndex string_idx,
Vladimir Markof25cc732017-03-16 16:18:15 +00007875 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007876 DCHECK(dex_cache != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007877 ObjPtr<mirror::String> resolved = dex_cache->GetResolvedString(string_idx);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007878 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007879 return resolved.Ptr();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007880 }
7881 uint32_t utf16_length;
7882 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08007883 ObjPtr<mirror::String> string =
7884 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007885 if (string != nullptr) {
7886 dex_cache->SetResolvedString(string_idx, string);
7887 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007888 return string.Ptr();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007889}
7890
Mathieu Chartierb8901302016-09-30 10:27:43 -07007891ObjPtr<mirror::Class> ClassLinker::LookupResolvedType(const DexFile& dex_file,
Andreas Gampea5b09a62016-11-17 15:21:22 -08007892 dex::TypeIndex type_idx,
Mathieu Chartierb8901302016-09-30 10:27:43 -07007893 ObjPtr<mirror::DexCache> dex_cache,
7894 ObjPtr<mirror::ClassLoader> class_loader) {
7895 ObjPtr<mirror::Class> type = dex_cache->GetResolvedType(type_idx);
7896 if (type == nullptr) {
7897 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
7898 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
7899 if (descriptor[1] == '\0') {
7900 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
7901 // for primitive classes that aren't backed by dex files.
7902 type = FindPrimitiveClass(descriptor[0]);
7903 } else {
7904 Thread* const self = Thread::Current();
7905 DCHECK(self != nullptr);
7906 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
7907 // Find the class in the loaded classes table.
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07007908 type = LookupClass(self, descriptor, hash, class_loader.Ptr());
Mathieu Chartierb8901302016-09-30 10:27:43 -07007909 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007910 if (type != nullptr) {
7911 if (type->IsResolved()) {
7912 dex_cache->SetResolvedType(type_idx, type);
7913 } else {
7914 type = nullptr;
7915 }
7916 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07007917 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007918 DCHECK(type == nullptr || type->IsResolved());
7919 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07007920}
7921
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007922mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
Andreas Gampea5b09a62016-11-17 15:21:22 -08007923 dex::TypeIndex type_idx,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007924 ObjPtr<mirror::Class> referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007925 StackHandleScope<2> hs(Thread::Current());
7926 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
7927 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07007928 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
7929}
7930
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007931mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
Andreas Gampea5b09a62016-11-17 15:21:22 -08007932 dex::TypeIndex type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007933 Handle<mirror::DexCache> dex_cache,
7934 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007935 DCHECK(dex_cache != nullptr);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007936 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007937 ObjPtr<mirror::Class> resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007938 if (resolved == nullptr) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00007939 // TODO: Avoid this lookup as it duplicates work done in FindClass(). It is here
7940 // as a workaround for FastNative JNI to avoid AssertNoPendingException() when
7941 // trying to resolve annotations while an exception may be pending. Bug: 34659969
7942 resolved = LookupResolvedType(dex_file, type_idx, dex_cache.Get(), class_loader.Get());
7943 }
7944 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08007945 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07007946 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08007947 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007948 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05007949 // TODO: we used to throw here if resolved's class loader was not the
7950 // boot class loader. This was to permit different classes with the
7951 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007952 dex_cache->SetResolvedType(type_idx, resolved);
7953 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08007954 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08007955 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08007956 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007957 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00007958 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08007959 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007960 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08007961 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08007962 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00007963 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08007964 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007965 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007966 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00007967 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07007968 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007969 return resolved.Ptr();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007970}
7971
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007972template <ClassLinker::ResolveMode kResolveMode>
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007973ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file,
7974 uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07007975 Handle<mirror::DexCache> dex_cache,
7976 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007977 ArtMethod* referrer,
7978 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007979 DCHECK(dex_cache != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07007980 // Check for hit in the dex cache.
Mathieu Chartiere401d142015-04-22 13:56:20 -07007981 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007982 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07007983 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007984 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007985 if (kResolveMode == ClassLinker::kForceICCECheck) {
7986 if (resolved->CheckIncompatibleClassChange(type)) {
7987 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
7988 return nullptr;
7989 }
7990 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007991 return resolved;
7992 }
Ian Rogers08f753d2012-08-24 14:35:25 -07007993 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007994 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007995 ObjPtr<mirror::Class> klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007996 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07007997 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007998 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007999 }
Ian Rogers08f753d2012-08-24 14:35:25 -07008000 // Scan using method_idx, this saves string compares but will only hit for matching dex
8001 // caches/files.
8002 switch (type) {
8003 case kDirect: // Fall-through.
8004 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07008005 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8006 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07008007 break;
8008 case kInterface:
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008009 // We have to check whether the method id really belongs to an interface (dex static bytecode
8010 // constraint A15). Otherwise you must not invoke-interface on it.
8011 //
8012 // This is not symmetric to A12-A14 (direct, static, virtual), as using FindInterfaceMethod
8013 // assumes that the given type is an interface, and will check the interface table if the
8014 // method isn't declared in the class. So it may find an interface method (usually by name
8015 // in the handling below, but we do the constraint check early). In that case,
8016 // CheckIncompatibleClassChange will succeed (as it is called on an interface method)
8017 // unexpectedly.
8018 // Example:
8019 // interface I {
8020 // foo()
8021 // }
8022 // class A implements I {
8023 // ...
8024 // }
8025 // class B extends A {
8026 // ...
8027 // }
8028 // invoke-interface B.foo
8029 // -> FindInterfaceMethod finds I.foo (interface method), not A.foo (miranda method)
8030 if (UNLIKELY(!klass->IsInterface())) {
8031 ThrowIncompatibleClassChangeError(klass,
8032 "Found class %s, but interface was expected",
David Sehr709b0702016-10-13 09:12:37 -07008033 klass->PrettyDescriptor().c_str());
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008034 return nullptr;
8035 } else {
8036 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8037 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
8038 }
Ian Rogers08f753d2012-08-24 14:35:25 -07008039 break;
Alex Light705ad492015-09-21 11:36:30 -07008040 case kSuper:
8041 if (klass->IsInterface()) {
8042 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8043 } else {
8044 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8045 }
8046 break;
Ian Rogers08f753d2012-08-24 14:35:25 -07008047 case kVirtual:
Mathieu Chartiere401d142015-04-22 13:56:20 -07008048 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07008049 break;
8050 default:
8051 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07008052 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008053 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008054 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008055 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008056 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07008057 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07008058 switch (type) {
8059 case kDirect: // Fall-through.
8060 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07008061 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_);
8062 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07008063 break;
8064 case kInterface:
Mathieu Chartiere401d142015-04-22 13:56:20 -07008065 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008066 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07008067 break;
Alex Light705ad492015-09-21 11:36:30 -07008068 case kSuper:
8069 if (klass->IsInterface()) {
8070 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
8071 } else {
8072 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
8073 }
8074 break;
Ian Rogers08f753d2012-08-24 14:35:25 -07008075 case kVirtual:
Mathieu Chartiere401d142015-04-22 13:56:20 -07008076 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07008077 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008078 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008079 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008080 // If we found a method, check for incompatible class changes.
8081 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008082 // Be a good citizen and update the dex cache to speed subsequent calls.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008083 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07008084 return resolved;
8085 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008086 // If we had a method, it's an incompatible-class-change error.
8087 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008088 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008089 } else {
8090 // We failed to find the method which means either an access error, an incompatible class
8091 // change, or no such method. First try to find the method among direct and virtual methods.
8092 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8093 const Signature signature = dex_file.GetMethodSignature(method_id);
8094 switch (type) {
8095 case kDirect:
8096 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07008097 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008098 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
8099 // have had a resolved method before, which triggers the "true" branch above.
8100 break;
8101 case kInterface:
8102 case kVirtual:
8103 case kSuper:
Mathieu Chartiere401d142015-04-22 13:56:20 -07008104 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008105 break;
8106 }
8107
8108 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08008109 bool exception_generated = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008110 if (resolved != nullptr && referrer != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008111 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8112 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008113 if (!referring_class->CanAccess(methods_class)) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008114 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class,
8115 methods_class,
8116 resolved,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008117 type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008118 exception_generated = true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008119 } else if (!referring_class->CanAccessMember(methods_class, resolved->GetAccessFlags())) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008120 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008121 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008122 }
8123 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008124 if (!exception_generated) {
8125 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
8126 // interface methods and throw if we find the method there. If we find nothing, throw a
8127 // NoSuchMethodError.
8128 switch (type) {
8129 case kDirect:
8130 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008131 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008132 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008133 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008134 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008135 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008136 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008137 } else {
8138 ThrowNoSuchMethodError(type, klass, name, signature);
8139 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008140 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008141 break;
8142 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008143 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008144 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008145 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008146 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008147 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008148 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008149 } else {
8150 ThrowNoSuchMethodError(type, klass, name, signature);
8151 }
8152 }
8153 break;
8154 case kSuper:
8155 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008156 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008157 } else {
8158 ThrowNoSuchMethodError(type, klass, name, signature);
8159 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008160 break;
8161 case kVirtual:
8162 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008163 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008164 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008165 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008166 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008167 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08008168 } else {
8169 ThrowNoSuchMethodError(type, klass, name, signature);
8170 }
8171 }
8172 break;
8173 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008174 }
Ian Rogers08f753d2012-08-24 14:35:25 -07008175 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008176 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008177 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008178 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008179}
8180
Jeff Hao13e748b2015-08-25 20:44:19 +00008181ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(const DexFile& dex_file,
8182 uint32_t method_idx,
8183 Handle<mirror::DexCache> dex_cache,
8184 Handle<mirror::ClassLoader> class_loader) {
8185 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008186 Thread::PoisonObjectPointersIfDebug();
Jeff Hao13e748b2015-08-25 20:44:19 +00008187 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
8188 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8189 return resolved;
8190 }
8191 // Fail, get the declaring class.
8192 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008193 ObjPtr<mirror::Class> klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008194 if (klass == nullptr) {
8195 Thread::Current()->AssertPendingException();
8196 return nullptr;
8197 }
8198 if (klass->IsInterface()) {
David Sehr709b0702016-10-13 09:12:37 -07008199 LOG(FATAL) << "ResolveAmbiguousMethod: unexpected method in interface: "
8200 << klass->PrettyClass();
Jeff Hao13e748b2015-08-25 20:44:19 +00008201 return nullptr;
8202 }
8203
8204 // Search both direct and virtual methods
8205 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8206 if (resolved == nullptr) {
8207 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8208 }
8209
8210 return resolved;
8211}
8212
Vladimir Markof44d36c2017-03-14 14:18:46 +00008213ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8214 ObjPtr<mirror::DexCache> dex_cache,
8215 ObjPtr<mirror::ClassLoader> class_loader,
8216 bool is_static) {
8217 const DexFile& dex_file = *dex_cache->GetDexFile();
8218 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
8219 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8220 if (klass == nullptr) {
8221 klass = LookupResolvedType(dex_file, field_id.class_idx_, dex_cache, class_loader);
8222 }
8223 if (klass == nullptr) {
8224 // The class has not been resolved yet, so the field is also unresolved.
8225 return nullptr;
8226 }
8227 DCHECK(klass->IsResolved());
8228 Thread* self = is_static ? Thread::Current() : nullptr;
8229
8230 // First try to find a field declared directly by `klass` by the field index.
8231 ArtField* resolved_field = is_static
8232 ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8233 : klass->FindInstanceField(dex_cache, field_idx);
8234
8235 if (resolved_field == nullptr) {
8236 // If not found in `klass` by field index, search the class hierarchy using the name and type.
8237 const char* name = dex_file.GetFieldName(field_id);
8238 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8239 resolved_field = is_static
8240 ? mirror::Class::FindStaticField(self, klass, name, type)
8241 : klass->FindInstanceField(name, type);
8242 }
8243
8244 if (resolved_field != nullptr) {
8245 dex_cache->SetResolvedField(field_idx, resolved_field, image_pointer_size_);
8246 }
8247 return resolved_field;
8248}
8249
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008250ArtField* ClassLinker::ResolveField(const DexFile& dex_file,
8251 uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008252 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008253 Handle<mirror::ClassLoader> class_loader,
8254 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008255 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008256 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008257 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008258 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008259 return resolved;
8260 }
8261 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07008262 Thread* const self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00008263 ObjPtr<mirror::Class> klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
8264 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008265 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008266 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008267 }
8268
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008269 if (is_static) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008270 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008271 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07008272 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07008273 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008274
Andreas Gampe58a5af82014-07-31 16:23:49 -07008275 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008276 const char* name = dex_file.GetFieldName(field_id);
8277 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8278 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07008279 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008280 } else {
8281 resolved = klass->FindInstanceField(name, type);
8282 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07008283 if (resolved == nullptr) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008284 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008285 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008286 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008287 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07008288 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08008289 return resolved;
8290}
8291
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008292ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
8293 uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008294 Handle<mirror::DexCache> dex_cache,
8295 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008296 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008297 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008298 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008299 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008300 return resolved;
8301 }
8302 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07008303 Thread* self = Thread::Current();
Vladimir Marko19a4d372016-12-08 14:41:46 +00008304 ObjPtr<mirror::Class> klass(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader));
8305 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008306 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008307 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008308 }
8309
Vladimir Markof44d36c2017-03-14 14:18:46 +00008310 StringPiece name(dex_file.GetFieldName(field_id));
8311 StringPiece type(dex_file.GetFieldTypeDescriptor(field_id));
Mathieu Chartierf8322842014-05-16 10:59:25 -07008312 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008313 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008314 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08008315 } else {
Vladimir Marko19a4d372016-12-08 14:41:46 +00008316 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008317 }
8318 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008319}
8320
Narayan Kamath25352fc2016-08-03 12:46:58 +01008321mirror::MethodType* ClassLinker::ResolveMethodType(const DexFile& dex_file,
8322 uint32_t proto_idx,
8323 Handle<mirror::DexCache> dex_cache,
8324 Handle<mirror::ClassLoader> class_loader) {
8325 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008326 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008327
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008328 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008329 if (resolved != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008330 return resolved.Ptr();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008331 }
8332
8333 Thread* const self = Thread::Current();
8334 StackHandleScope<4> hs(self);
8335
8336 // First resolve the return type.
8337 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
8338 Handle<mirror::Class> return_type(hs.NewHandle(
8339 ResolveType(dex_file, proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008340 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008341 DCHECK(self->IsExceptionPending());
8342 return nullptr;
8343 }
8344
8345 // Then resolve the argument types.
8346 //
8347 // TODO: Is there a better way to figure out the number of method arguments
8348 // other than by looking at the shorty ?
8349 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8350
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008351 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008352 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008353 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8354 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008355 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008356 DCHECK(self->IsExceptionPending());
8357 return nullptr;
8358 }
8359
8360 DexFileParameterIterator it(dex_file, proto_id);
8361 int32_t i = 0;
8362 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8363 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008364 const dex::TypeIndex type_idx = it.GetTypeIdx();
Narayan Kamath25352fc2016-08-03 12:46:58 +01008365 param_class.Assign(ResolveType(dex_file, type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008366 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008367 DCHECK(self->IsExceptionPending());
8368 return nullptr;
8369 }
8370
8371 method_params->Set(i++, param_class.Get());
8372 }
8373
8374 DCHECK(!it.HasNext());
8375
8376 Handle<mirror::MethodType> type = hs.NewHandle(
8377 mirror::MethodType::Create(self, return_type, method_params));
8378 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8379
8380 return type.Get();
8381}
8382
Orion Hodsonc069a302017-01-18 09:23:12 +00008383mirror::MethodHandle* ClassLinker::ResolveMethodHandle(uint32_t method_handle_idx,
8384 ArtMethod* referrer)
8385 REQUIRES_SHARED(Locks::mutator_lock_) {
8386 Thread* const self = Thread::Current();
8387 const DexFile* const dex_file = referrer->GetDexFile();
8388 const DexFile::MethodHandleItem& mh = dex_file->GetMethodHandle(method_handle_idx);
8389
8390 union {
8391 ArtField* field;
8392 ArtMethod* method;
8393 uintptr_t field_or_method;
8394 } target;
8395 uint32_t num_params;
8396 mirror::MethodHandle::Kind kind;
8397 DexFile::MethodHandleType handle_type =
8398 static_cast<DexFile::MethodHandleType>(mh.method_handle_type_);
8399 switch (handle_type) {
8400 case DexFile::MethodHandleType::kStaticPut: {
8401 kind = mirror::MethodHandle::Kind::kStaticPut;
8402 target.field = ResolveField(mh.field_or_method_idx_, referrer, true /* is_static */);
8403 num_params = 1;
8404 break;
8405 }
8406 case DexFile::MethodHandleType::kStaticGet: {
8407 kind = mirror::MethodHandle::Kind::kStaticGet;
8408 target.field = ResolveField(mh.field_or_method_idx_, referrer, true /* is_static */);
8409 num_params = 0;
8410 break;
8411 }
8412 case DexFile::MethodHandleType::kInstancePut: {
8413 kind = mirror::MethodHandle::Kind::kInstancePut;
8414 target.field = ResolveField(mh.field_or_method_idx_, referrer, false /* is_static */);
8415 num_params = 2;
8416 break;
8417 }
8418 case DexFile::MethodHandleType::kInstanceGet: {
8419 kind = mirror::MethodHandle::Kind::kInstanceGet;
8420 target.field = ResolveField(mh.field_or_method_idx_, referrer, false /* is_static */);
8421 num_params = 1;
8422 break;
8423 }
8424 case DexFile::MethodHandleType::kInvokeStatic: {
8425 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8426 target.method = ResolveMethod<kNoICCECheckForCache>(self,
8427 mh.field_or_method_idx_,
8428 referrer,
8429 InvokeType::kStatic);
8430 uint32_t shorty_length;
8431 target.method->GetShorty(&shorty_length);
8432 num_params = shorty_length - 1; // Remove 1 for return value.
8433 break;
8434 }
8435 case DexFile::MethodHandleType::kInvokeInstance: {
8436 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8437 target.method = ResolveMethod<kNoICCECheckForCache>(self,
8438 mh.field_or_method_idx_,
8439 referrer,
8440 InvokeType::kVirtual);
8441 uint32_t shorty_length;
8442 target.method->GetShorty(&shorty_length);
8443 num_params = shorty_length - 1; // Remove 1 for return value.
8444 break;
8445 }
8446 case DexFile::MethodHandleType::kInvokeConstructor: {
8447 UNIMPLEMENTED(FATAL) << "Invoke constructor is implemented as a transform.";
8448 num_params = 0;
8449 }
8450 }
8451
8452 StackHandleScope<5> hs(self);
8453 ObjPtr<mirror::Class> class_type = mirror::Class::GetJavaLangClass();
8454 ObjPtr<mirror::Class> array_of_class = FindArrayClass(self, &class_type);
8455 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8456 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
8457 if (method_params.Get() == nullptr) {
8458 DCHECK(self->IsExceptionPending());
8459 return nullptr;
8460 }
8461
8462 Handle<mirror::Class> return_type;
8463 switch (handle_type) {
8464 case DexFile::MethodHandleType::kStaticPut: {
8465 method_params->Set(0, target.field->GetType<true>());
8466 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8467 break;
8468 }
8469 case DexFile::MethodHandleType::kStaticGet: {
8470 return_type = hs.NewHandle(target.field->GetType<true>());
8471 break;
8472 }
8473 case DexFile::MethodHandleType::kInstancePut: {
8474 method_params->Set(0, target.field->GetDeclaringClass());
8475 method_params->Set(1, target.field->GetType<true>());
8476 return_type = hs.NewHandle(FindPrimitiveClass('V'));
8477 break;
8478 }
8479 case DexFile::MethodHandleType::kInstanceGet: {
8480 method_params->Set(0, target.field->GetDeclaringClass());
8481 return_type = hs.NewHandle(target.field->GetType<true>());
8482 break;
8483 }
8484 case DexFile::MethodHandleType::kInvokeStatic:
8485 case DexFile::MethodHandleType::kInvokeInstance: {
8486 // TODO(oth): This will not work for varargs methods as this
8487 // requires instantiating a Transformer. This resolution step
8488 // would be best done in managed code rather than in the run
8489 // time (b/35235705)
8490 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8491 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8492 DexFileParameterIterator it(*dex_file, target.method->GetPrototype());
8493 for (int32_t i = 0; it.HasNext(); i++, it.Next()) {
8494 const dex::TypeIndex type_idx = it.GetTypeIdx();
8495 mirror::Class* klass = ResolveType(*dex_file, type_idx, dex_cache, class_loader);
8496 if (nullptr == klass) {
8497 DCHECK(self->IsExceptionPending());
8498 return nullptr;
8499 }
8500 method_params->Set(i, klass);
8501 }
8502 return_type = hs.NewHandle(target.method->GetReturnType(true));
8503 break;
8504 }
8505 case DexFile::MethodHandleType::kInvokeConstructor: {
8506 // TODO(oth): b/35235705
8507 UNIMPLEMENTED(FATAL) << "Invoke constructor is implemented as a transform.";
8508 }
8509 }
8510
8511 if (return_type.IsNull()) {
8512 DCHECK(self->IsExceptionPending());
8513 return nullptr;
8514 }
8515
8516 Handle<mirror::MethodType>
8517 mt(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8518 if (mt.IsNull()) {
8519 DCHECK(self->IsExceptionPending());
8520 return nullptr;
8521 }
8522 return mirror::MethodHandleImpl::Create(self, target.field_or_method, kind, mt);
8523}
8524
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008525bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
8526 return (entry_point == GetQuickResolutionStub()) ||
8527 (quick_resolution_trampoline_ == entry_point);
8528}
8529
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008530bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
8531 return (entry_point == GetQuickToInterpreterBridge()) ||
8532 (quick_to_interpreter_bridge_trampoline_ == entry_point);
8533}
8534
8535bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
8536 return (entry_point == GetQuickGenericJniStub()) ||
8537 (quick_generic_jni_trampoline_ == entry_point);
8538}
8539
8540const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
8541 return GetQuickGenericJniStub();
8542}
8543
Andreas Gampecc1b5352016-12-01 16:58:38 -08008544void ClassLinker::SetEntryPointsToCompiledCode(ArtMethod* method, const void* code) const {
8545 CHECK(code != nullptr);
8546 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
8547 base -= sizeof(void*); // Move backward so that code_offset != 0.
8548 const uint32_t code_offset = sizeof(void*);
8549 OatFile::OatMethod oat_method(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008550 oat_method.LinkMethod(method);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008551}
8552
Mathieu Chartiere401d142015-04-22 13:56:20 -07008553void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008554 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008555 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
8556 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08008557 SetEntryPointsToCompiledCode(method, GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008558 }
8559}
8560
Alex Lightdb01a092017-04-03 15:39:55 -07008561void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
8562 DCHECK(method->IsObsolete());
8563 // We cannot mess with the entrypoints of native methods because they are used to determine how
8564 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
8565 if (!method->IsNative()) {
8566 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
8567 }
8568}
8569
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008570void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07008571 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07008572 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008573 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
8574 << NumNonZygoteClasses() << "\n";
8575}
8576
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008577class CountClassesVisitor : public ClassLoaderVisitor {
8578 public:
8579 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
8580
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008581 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07008582 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008583 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07008584 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00008585 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
8586 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07008587 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008588 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008589
8590 size_t num_zygote_classes;
8591 size_t num_non_zygote_classes;
8592};
8593
8594size_t ClassLinker::NumZygoteClasses() const {
8595 CountClassesVisitor visitor;
8596 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008597 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008598}
8599
8600size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008601 CountClassesVisitor visitor;
8602 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07008603 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07008604}
8605
Ian Rogers7dfb28c2013-08-22 08:18:36 -07008606size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07008607 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08008608 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07008609 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07008610}
8611
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008612pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07008613 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07008614}
8615
8616pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08008617 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07008618}
8619
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008620void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008621 DCHECK(!init_done_);
8622
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008623 DCHECK(klass != nullptr);
8624 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008625
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07008626 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008627 DCHECK(class_roots != nullptr);
8628 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07008629 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08008630}
8631
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008632const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
8633 static const char* class_roots_descriptors[] = {
8634 "Ljava/lang/Class;",
8635 "Ljava/lang/Object;",
8636 "[Ljava/lang/Class;",
8637 "[Ljava/lang/Object;",
8638 "Ljava/lang/String;",
8639 "Ljava/lang/DexCache;",
8640 "Ljava/lang/ref/Reference;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008641 "Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008642 "Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008643 "Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008644 "Ljava/lang/reflect/Proxy;",
8645 "[Ljava/lang/String;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008646 "[Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008647 "[Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07008648 "[Ljava/lang/reflect/Method;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008649 "Ljava/lang/invoke/CallSite;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008650 "Ljava/lang/invoke/MethodHandleImpl;",
Orion Hodsonc069a302017-01-18 09:23:12 +00008651 "Ljava/lang/invoke/MethodHandles$Lookup;",
Narayan Kamathafa48272016-08-03 12:46:58 +01008652 "Ljava/lang/invoke/MethodType;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008653 "Ljava/lang/ClassLoader;",
8654 "Ljava/lang/Throwable;",
8655 "Ljava/lang/ClassNotFoundException;",
8656 "Ljava/lang/StackTraceElement;",
Narayan Kamath000e1882016-10-24 17:14:25 +01008657 "Ldalvik/system/EmulatedStackFrame;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008658 "Z",
8659 "B",
8660 "C",
8661 "D",
8662 "F",
8663 "I",
8664 "J",
8665 "S",
8666 "V",
8667 "[Z",
8668 "[B",
8669 "[C",
8670 "[D",
8671 "[F",
8672 "[I",
8673 "[J",
8674 "[S",
8675 "[Ljava/lang/StackTraceElement;",
Alex Lightd6251582016-10-31 11:12:30 -07008676 "Ldalvik/system/ClassExt;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008677 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08008678 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
8679 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008680
8681 const char* descriptor = class_roots_descriptors[class_root];
8682 CHECK(descriptor != nullptr);
8683 return descriptor;
8684}
8685
Jeff Hao5872d7c2016-04-27 11:07:41 -07008686jobject ClassLinker::CreatePathClassLoader(Thread* self,
8687 const std::vector<const DexFile*>& dex_files) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008688 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
8689 // We could move the jobject to the callers, but all call-sites do this...
8690 ScopedObjectAccessUnchecked soa(self);
8691
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008692 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Vladimir Marko19a4d372016-12-08 14:41:46 +00008693 StackHandleScope<6> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008694
Mathieu Chartierc7853442015-03-27 14:35:38 -07008695 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008696 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008697
Mathieu Chartier3398c782016-09-30 10:27:43 -07008698 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->GetType<true>()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008699 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008700 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008701 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07008702 mirror::ObjectArray<mirror::Object>::Alloc(self,
8703 dex_elements_class.Get(),
8704 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008705 Handle<mirror::Class> h_dex_element_class =
8706 hs.NewHandle(dex_elements_class->GetComponentType());
8707
Mathieu Chartierc7853442015-03-27 14:35:38 -07008708 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008709 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008710 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008711
Andreas Gampe08883de2016-11-08 13:20:52 -08008712 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008713 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008714
Andreas Gampe08883de2016-11-08 13:20:52 -08008715 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008716 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->GetType<false>());
8717
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008718 // Fill the elements array.
8719 int32_t index = 0;
8720 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008721 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008722
Mathieu Chartier966878d2016-01-14 14:33:29 -08008723 // CreatePathClassLoader is only used by gtests. Index 0 of h_long_array is supposed to be the
8724 // oat file but we can leave it null.
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008725 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
8726 self,
8727 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008728 DCHECK(h_long_array != nullptr);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008729 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008730
Mathieu Chartier3738e982017-05-12 16:07:28 -07008731 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
8732 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008733 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008734 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008735 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008736 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008737
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008738 Handle<mirror::String> h_file_name = hs2.NewHandle(
8739 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008740 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008741 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
8742
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008743 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008744 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008745 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008746
8747 h_dex_elements->Set(index, h_element.Get());
8748 index++;
8749 }
8750 DCHECK_EQ(index, h_dex_elements->GetLength());
8751
8752 // Create DexPathList.
8753 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008754 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008755 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008756 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008757 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008758
8759 // Create PathClassLoader.
8760 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -07008761 soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008762 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
8763 h_path_class_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008764 DCHECK(h_path_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008765 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008766 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08008767 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008768 DCHECK(path_list_field != nullptr);
8769 path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008770
8771 // Make a pretend boot-classpath.
8772 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07008773 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00008774 mirror::Class::FindField(self,
8775 h_path_class_loader->GetClass(),
8776 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07008777 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01008778 DCHECK(parent_field != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07008779 ObjPtr<mirror::Object> boot_cl =
Mathieu Chartier0795f232016-09-27 18:43:30 -07008780 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
Mathieu Chartier966878d2016-01-14 14:33:29 -08008781 parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008782
8783 // Make it a global ref and return.
8784 ScopedLocalRef<jobject> local_ref(
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07008785 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008786 return soa.Env()->NewGlobalRef(local_ref.get());
8787}
8788
Andreas Gampe8ac75952015-06-02 21:01:45 -07008789void ClassLinker::DropFindArrayClassCache() {
8790 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
8791 find_array_class_cache_next_victim_ = 0;
8792}
8793
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07008794void ClassLinker::ClearClassTableStrongRoots() const {
8795 Thread* const self = Thread::Current();
8796 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8797 for (const ClassLoaderData& data : class_loaders_) {
8798 if (data.class_table != nullptr) {
8799 data.class_table->ClearStrongRoots();
8800 }
8801 }
8802}
8803
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008804void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008805 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008806 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07008807 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008808 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
8809 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008810 if (class_loader != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008811 visitor->Visit(class_loader.Ptr());
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008812 }
8813 }
8814}
8815
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008816void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
8817 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008818 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07008819 Thread* const self = Thread::Current();
8820 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07008821 ClassTable* const table = ClassTableForClassLoader(class_loader.Ptr());
Mathieu Chartier00310e02015-10-17 12:46:42 -07008822 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07008823 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008824 // It was not already inserted, perform the write barrier to let the GC know the class loader's
8825 // class table was modified.
8826 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
8827 }
8828}
8829
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008830void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008831 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07008832 std::vector<ClassLoaderData> to_delete;
8833 // Do the delete outside the lock to avoid lock violation in jit code cache.
8834 {
8835 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8836 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
8837 const ClassLoaderData& data = *it;
8838 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008839 ObjPtr<mirror::ClassLoader> class_loader =
8840 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07008841 if (class_loader != nullptr) {
8842 ++it;
8843 } else {
8844 VLOG(class_linker) << "Freeing class loader";
8845 to_delete.push_back(data);
8846 it = class_loaders_.erase(it);
8847 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008848 }
8849 }
Mathieu Chartier65975772016-08-05 10:46:36 -07008850 for (ClassLoaderData& data : to_delete) {
8851 DeleteClassLoader(self, data);
8852 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008853}
8854
Vladimir Marko21300532017-01-24 18:06:55 +00008855class GetResolvedClassesVisitor : public ClassVisitor {
8856 public:
8857 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
8858 : result_(result),
8859 ignore_boot_classes_(ignore_boot_classes),
8860 last_resolved_classes_(result->end()),
8861 last_dex_file_(nullptr),
8862 vlog_is_on_(VLOG_IS_ON(class_linker)),
8863 extra_stats_(),
8864 last_extra_stats_(extra_stats_.end()) { }
8865
8866 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
8867 if (!klass->IsProxyClass() &&
8868 !klass->IsArrayClass() &&
8869 klass->IsResolved() &&
8870 !klass->IsErroneousResolved() &&
8871 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
8872 const DexFile& dex_file = klass->GetDexFile();
8873 if (&dex_file != last_dex_file_) {
8874 last_dex_file_ = &dex_file;
8875 DexCacheResolvedClasses resolved_classes(dex_file.GetLocation(),
8876 dex_file.GetBaseLocation(),
8877 dex_file.GetLocationChecksum());
8878 last_resolved_classes_ = result_->find(resolved_classes);
8879 if (last_resolved_classes_ == result_->end()) {
8880 last_resolved_classes_ = result_->insert(resolved_classes).first;
8881 }
8882 }
8883 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
8884 if (UNLIKELY(vlog_is_on_) && added) {
8885 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
8886 if (last_extra_stats_ == extra_stats_.end() ||
8887 last_extra_stats_->first != resolved_classes) {
8888 last_extra_stats_ = extra_stats_.find(resolved_classes);
8889 if (last_extra_stats_ == extra_stats_.end()) {
8890 last_extra_stats_ =
8891 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
8892 }
8893 }
8894 }
8895 }
8896 return true;
8897 }
8898
8899 void PrintStatistics() const {
8900 if (vlog_is_on_) {
8901 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
8902 auto it = extra_stats_.find(std::addressof(resolved_classes));
8903 DCHECK(it != extra_stats_.end());
8904 const ExtraStats& extra_stats = it->second;
8905 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
8906 << " has " << resolved_classes.GetClasses().size() << " / "
8907 << extra_stats.number_of_class_defs_ << " resolved classes";
8908 }
8909 }
8910 }
8911
8912 private:
8913 struct ExtraStats {
8914 explicit ExtraStats(uint32_t number_of_class_defs)
8915 : number_of_class_defs_(number_of_class_defs) {}
8916 uint32_t number_of_class_defs_;
8917 };
8918
8919 std::set<DexCacheResolvedClasses>* result_;
8920 bool ignore_boot_classes_;
8921 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
8922 const DexFile* last_dex_file_;
8923
8924 // Statistics.
8925 bool vlog_is_on_;
8926 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
8927 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
8928};
8929
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008930std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08008931 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008932 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07008933 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008934 std::set<DexCacheResolvedClasses> ret;
8935 VLOG(class_linker) << "Collecting resolved classes";
8936 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00008937 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
8938 VisitClasses(&visitor);
8939 if (VLOG_IS_ON(class_linker)) {
8940 visitor.PrintStatistics();
8941 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008942 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008943 return ret;
8944}
8945
Mathieu Chartier046854b2017-03-01 17:16:22 -08008946std::unordered_set<std::string> ClassLinker::GetClassDescriptorsForResolvedClasses(
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008947 const std::set<DexCacheResolvedClasses>& classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08008948 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008949 std::unordered_set<std::string> ret;
8950 Thread* const self = Thread::Current();
8951 std::unordered_map<std::string, const DexFile*> location_to_dex_file;
8952 ScopedObjectAccess soa(self);
Mathieu Chartier268764d2016-09-13 12:09:38 -07008953 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Andreas Gampecc1b5352016-12-01 16:58:38 -08008954 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008955 for (const ClassLinker::DexCacheData& data : GetDexCachesData()) {
8956 if (!self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008957 ObjPtr<mirror::DexCache> dex_cache = soa.Decode<mirror::DexCache>(data.weak_root);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008958 if (dex_cache != nullptr) {
8959 const DexFile* dex_file = dex_cache->GetDexFile();
8960 // There could be duplicates if two dex files with the same location are mapped.
Mathieu Chartier046854b2017-03-01 17:16:22 -08008961 location_to_dex_file.emplace(dex_file->GetLocation(), dex_file);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008962 }
8963 }
8964 }
8965 for (const DexCacheResolvedClasses& info : classes) {
Mathieu Chartier046854b2017-03-01 17:16:22 -08008966 const std::string& location = info.GetDexLocation();
8967 auto found = location_to_dex_file.find(location);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008968 if (found != location_to_dex_file.end()) {
8969 const DexFile* dex_file = found->second;
8970 VLOG(profiler) << "Found opened dex file for " << dex_file->GetLocation() << " with "
8971 << info.GetClasses().size() << " classes";
8972 DCHECK_EQ(dex_file->GetLocationChecksum(), info.GetLocationChecksum());
Andreas Gampea5b09a62016-11-17 15:21:22 -08008973 for (dex::TypeIndex type_idx : info.GetClasses()) {
Jeff Hao54b58552016-11-16 15:15:04 -08008974 const DexFile::TypeId& type_id = dex_file->GetTypeId(type_idx);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008975 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
8976 ret.insert(descriptor);
8977 }
8978 } else {
Mathieu Chartier046854b2017-03-01 17:16:22 -08008979 VLOG(class_linker) << "Failed to find opened dex file for location " << location;
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008980 }
8981 }
8982 return ret;
8983}
8984
Mathieu Chartier65975772016-08-05 10:46:36 -07008985class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
8986 public:
8987 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
8988 : method_(method),
8989 pointer_size_(pointer_size) {}
8990
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008991 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier65975772016-08-05 10:46:36 -07008992 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
8993 holder_ = klass;
8994 }
8995 // Return false to stop searching if holder_ is not null.
8996 return holder_ == nullptr;
8997 }
8998
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008999 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009000 const ArtMethod* const method_;
9001 const PointerSize pointer_size_;
9002};
9003
9004mirror::Class* ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
9005 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9006 CHECK(method->IsCopied());
9007 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9008 VisitClasses(&visitor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009009 return visitor.holder_.Ptr();
Mathieu Chartier65975772016-08-05 10:46:36 -07009010}
9011
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009012mirror::IfTable* ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9013 return down_cast<mirror::IfTable*>(
9014 mirror::IfTable::Alloc(self,
9015 GetClassRoot(kObjectArrayClass),
9016 ifcount * mirror::IfTable::kMax));
9017}
9018
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009019// Instantiate ResolveMethod.
9020template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::kForceICCECheck>(
9021 const DexFile& dex_file,
9022 uint32_t method_idx,
9023 Handle<mirror::DexCache> dex_cache,
9024 Handle<mirror::ClassLoader> class_loader,
9025 ArtMethod* referrer,
9026 InvokeType type);
9027template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::kNoICCECheckForCache>(
9028 const DexFile& dex_file,
9029 uint32_t method_idx,
9030 Handle<mirror::DexCache> dex_cache,
9031 Handle<mirror::ClassLoader> class_loader,
9032 ArtMethod* referrer,
9033 InvokeType type);
9034
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009035} // namespace art