blob: 0cf5231b0b2aaa30248a46ccd9e9ca8e48b2820e [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>
Ian Rogers700a4022014-05-19 16:49:03 -070022#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070023#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070024#include <string>
Alex Lighteb7c1442015-08-31 13:17:42 -070025#include <tuple>
Andreas Gampea696c0a2014-12-10 20:51:45 -080026#include <unistd.h>
Alex Lighteb7c1442015-08-31 13:17:42 -070027#include <unordered_map>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070028#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070029#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070030
Mathieu Chartierc7853442015-03-27 14:35:38 -070031#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070032#include "art_method-inl.h"
33#include "base/arena_allocator.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080034#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080035#include "base/logging.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070036#include "base/scoped_arena_containers.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010037#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080038#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080039#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010040#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080041#include "base/unix_file/fd_file.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070042#include "base/value_object.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "class_linker-inl.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070044#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000045#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080046#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070047#include "dex_file-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070048#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070049#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070050#include "experimental_flags.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070051#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070052#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080053#include "gc/accounting/heap_bitmap-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070054#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070055#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070056#include "gc/space/image_space.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070057#include "handle_scope-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080058#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070059#include "imt_conflict_table.h"
60#include "imtable-inl.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070061#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070062#include "interpreter/interpreter.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080063#include "jit/jit.h"
64#include "jit/jit_code_cache.h"
Mathieu Chartierc5dd3192015-12-09 16:38:30 -080065#include "jit/offline_profiling_info.h"
Ian Rogers0571d352011-11-03 19:51:38 -070066#include "leb128.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070067#include "linear_alloc.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080068#include "mirror/class.h"
69#include "mirror/class-inl.h"
70#include "mirror/class_loader.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070071#include "mirror/dex_cache.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070072#include "mirror/dex_cache-inl.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070073#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080074#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070075#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +010076#include "mirror/method_type.h"
77#include "mirror/method_handle_impl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080078#include "mirror/object-inl.h"
79#include "mirror/object_array-inl.h"
80#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070081#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080082#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070083#include "mirror/string-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070084#include "native/dalvik_system_DexFile.h"
85#include "oat.h"
86#include "oat_file.h"
87#include "oat_file-inl.h"
88#include "oat_file_assistant.h"
89#include "oat_file_manager.h"
90#include "object_lock.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080091#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070092#include "runtime.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070093#include "ScopedLocalRef.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070094#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070095#include "thread-inl.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -070096#include "trace.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070097#include "utils.h"
Vladimir Marko05792b92015-08-03 11:56:49 +010098#include "utils/dex_cache_arrays_layout-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080099#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700100#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700101
102namespace art {
103
Mathieu Chartierc7853442015-03-27 14:35:38 -0700104static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700105static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700106
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700107static void ThrowNoClassDefFoundError(const char* fmt, ...)
108 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700109 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700110static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700111 va_list args;
112 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800113 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000114 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800115 va_end(args);
116}
117
Andreas Gampe99babb62015-11-02 16:20:00 -0800118static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700119 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700120 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700121 StackHandleScope<1> hs(self);
122 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700123 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Andreas Gampe99babb62015-11-02 16:20:00 -0800124 mirror::Class* exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700125
126 if (exception_class == nullptr) {
127 // No exc class ~ no <init>-with-string.
128 CHECK(self->IsExceptionPending());
129 self->ClearException();
130 return false;
131 }
132
Mathieu Chartiere401d142015-04-22 13:56:20 -0700133 ArtMethod* exception_init_method = exception_class->FindDeclaredDirectMethod(
Andreas Gampe99babb62015-11-02 16:20:00 -0800134 "<init>", "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700135 return exception_init_method != nullptr;
136}
137
Andreas Gampe99babb62015-11-02 16:20:00 -0800138// Helper for ThrowEarlierClassFailure. Throws the stored error.
139static void HandleEarlierVerifyError(Thread* self, ClassLinker* class_linker, mirror::Class* c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700140 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe99babb62015-11-02 16:20:00 -0800141 mirror::Object* obj = c->GetVerifyError();
142 DCHECK(obj != nullptr);
143 self->AssertNoPendingException();
144 if (obj->IsClass()) {
145 // Previous error has been stored as class. Create a new exception of that type.
146
147 // It's possible the exception doesn't have a <init>(String).
148 std::string temp;
149 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
150
151 if (HasInitWithString(self, class_linker, descriptor)) {
152 self->ThrowNewException(descriptor, PrettyDescriptor(c).c_str());
153 } else {
154 self->ThrowNewException(descriptor, nullptr);
155 }
156 } else {
157 // Previous error has been stored as an instance. Just rethrow.
158 mirror::Class* throwable_class =
159 self->DecodeJObject(WellKnownClasses::java_lang_Throwable)->AsClass();
160 mirror::Class* error_class = obj->GetClass();
161 CHECK(throwable_class->IsAssignableFrom(error_class));
162 self->SetException(obj->AsThrowable());
163 }
164 self->AssertPendingException();
165}
166
Andreas Gampecb086952015-11-02 16:20:00 -0800167void ClassLinker::ThrowEarlierClassFailure(mirror::Class* c, bool wrap_in_no_class_def) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700168 // The class failed to initialize on a previous attempt, so we want to throw
169 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
170 // failed in verification, in which case v2 5.4.1 says we need to re-throw
171 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800172 Runtime* const runtime = Runtime::Current();
173 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700174 std::string extra;
Andreas Gampe99babb62015-11-02 16:20:00 -0800175 if (c->GetVerifyError() != nullptr) {
Andreas Gampe369c8512016-01-28 15:31:39 -0800176 mirror::Object* verify_error = c->GetVerifyError();
177 if (verify_error->IsClass()) {
178 extra = PrettyDescriptor(verify_error->AsClass());
179 } else {
180 extra = verify_error->AsThrowable()->Dump();
181 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700182 }
183 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c) << ": " << extra;
Ian Rogers87e552d2012-08-31 15:54:48 -0700184 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700185
Elliott Hughes5c599942012-06-13 16:45:05 -0700186 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800187 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800188 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700189 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
190 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000191 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700192 } else {
Andreas Gampe99babb62015-11-02 16:20:00 -0800193 if (c->GetVerifyError() != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800194 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800195 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800196 }
197 if (c->GetVerifyError() == nullptr || wrap_in_no_class_def) {
198 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
199 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
200 // exception will be a cause.
201 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
202 PrettyDescriptor(c).c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700203 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700204 }
205}
206
Brian Carlstromb23eab12014-10-08 17:55:21 -0700207static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700208 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700209 if (VLOG_IS_ON(class_linker)) {
210 std::string temp;
211 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000212 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700213 }
214}
215
216static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700217 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700218 Thread* self = Thread::Current();
219 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700220
221 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700222 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700223
224 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700225 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
226 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700227
Elliott Hughesa4f94742012-05-29 16:28:38 -0700228 // We only wrap non-Error exceptions; an Error can just be used as-is.
229 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000230 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700231 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700232 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700233}
234
Fred Shih381e4ca2014-08-25 17:24:27 -0700235// Gap between two fields in object layout.
236struct FieldGap {
237 uint32_t start_offset; // The offset from the start of the object.
238 uint32_t size; // The gap size of 1, 2, or 4 bytes.
239};
240struct FieldGapsComparator {
241 explicit FieldGapsComparator() {
242 }
243 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
244 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800245 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700246 // Note that the priority queue returns the largest element, so operator()
247 // should return true if lhs is less than rhs.
248 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700249 }
250};
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700251typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
Fred Shih381e4ca2014-08-25 17:24:27 -0700252
253// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800254static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700255 DCHECK(gaps != nullptr);
256
257 uint32_t current_offset = gap_start;
258 while (current_offset != gap_end) {
259 size_t remaining = gap_end - current_offset;
260 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
261 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
262 current_offset += sizeof(uint32_t);
263 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
264 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
265 current_offset += sizeof(uint16_t);
266 } else {
267 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
268 current_offset += sizeof(uint8_t);
269 }
270 DCHECK_LE(current_offset, gap_end) << "Overran gap";
271 }
272}
273// Shuffle fields forward, making use of gaps whenever possible.
274template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000275static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700276 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700277 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700278 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700279 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700280 DCHECK(current_field_idx != nullptr);
281 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700282 DCHECK(gaps != nullptr);
283 DCHECK(field_offset != nullptr);
284
285 DCHECK(IsPowerOfTwo(n));
286 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700287 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700288 Primitive::Type type = field->GetTypeAsPrimitiveType();
289 if (Primitive::ComponentSize(type) < n) {
290 break;
291 }
292 if (!IsAligned<n>(field_offset->Uint32Value())) {
293 MemberOffset old_offset = *field_offset;
294 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
295 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
296 }
297 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
298 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700299 if (!gaps->empty() && gaps->top().size >= n) {
300 FieldGap gap = gaps->top();
301 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100302 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700303 field->SetOffset(MemberOffset(gap.start_offset));
304 if (gap.size > n) {
305 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
306 }
307 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100308 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700309 field->SetOffset(*field_offset);
310 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
311 }
312 ++(*current_field_idx);
313 }
314}
315
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800316ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700317 // dex_lock_ is recursive as it may be used in stack dumping.
Mathieu Chartier6c60d842016-09-15 10:24:43 -0700318 : dex_lock_("ClassLinker dex lock", kDexLock),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700319 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800320 class_roots_(nullptr),
321 array_iftable_(nullptr),
322 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700323 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800324 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700325 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800326 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800327 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100328 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800329 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampe542451c2016-07-26 09:02:02 -0700330 image_pointer_size_(kRuntimePointerSize) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700331 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700332 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
333 "Array cache size wrong.");
334 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700335}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700336
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800337void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
338 mirror::Class* c2 = FindSystemClass(self, descriptor);
339 if (c2 == nullptr) {
340 LOG(FATAL) << "Could not find class " << descriptor;
341 UNREACHABLE();
342 }
343 if (c1.Get() != c2) {
344 std::ostringstream os1, os2;
345 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
346 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
347 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
348 << ". This is most likely the result of a broken build. Make sure that "
349 << "libcore and art projects match.\n\n"
350 << os1.str() << "\n\n" << os2.str();
351 UNREACHABLE();
352 }
353}
354
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800355bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
356 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800357 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700358
Mathieu Chartiere401d142015-04-22 13:56:20 -0700359 Thread* const self = Thread::Current();
360 Runtime* const runtime = Runtime::Current();
361 gc::Heap* const heap = runtime->GetHeap();
362
Jeff Haodcdc85b2015-12-04 14:06:18 -0800363 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700364 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700365
Mathieu Chartiere401d142015-04-22 13:56:20 -0700366 // Use the pointer size from the runtime since we are probably creating the image.
367 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
368
Elliott Hughes30646832011-10-13 16:59:46 -0700369 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700370 // 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 -0800371 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700372 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700373 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700374 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700375 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700376 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700377 mirror::Class::SetClassClass(java_lang_Class.Get());
378 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700379 if (kUseBakerOrBrooksReadBarrier) {
380 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800381 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700382 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700383 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800384 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800385 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700386
Elliott Hughes418d20f2011-09-22 14:00:39 -0700387 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700388 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700389 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700390 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700391 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700392
Ian Rogers23435d02012-09-24 11:23:12 -0700393 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700394 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700395 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700396 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700397 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700398 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700399 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700400
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700401 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800402 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
403 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
404 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
405 java_lang_Object.Get(),
406 java_lang_Object->GetObjectSize(),
407 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700408
Ian Rogers23435d02012-09-24 11:23:12 -0700409 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700410 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700411 AllocClass(self, java_lang_Class.Get(),
412 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700413 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700414
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700415 // Setup the char (primitive) class to be used for char[].
416 Handle<mirror::Class> char_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700417 AllocClass(self, java_lang_Class.Get(),
418 mirror::Class::PrimitiveClassSize(image_pointer_size_))));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700419 // The primitive char class won't be initialized by
420 // InitializePrimitiveClass until line 459, but strings (and
421 // internal char arrays) will be allocated before that and the
422 // component size, which is computed from the primitive type, needs
423 // to be set here.
424 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700425
Ian Rogers23435d02012-09-24 11:23:12 -0700426 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700427 Handle<mirror::Class> char_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700428 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700429 char_array_class->SetComponentType(char_class.Get());
430 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700431
Ian Rogers23435d02012-09-24 11:23:12 -0700432 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700433 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700434 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700435 java_lang_String->SetStringClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700436 mirror::String::SetClass(java_lang_String.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700437 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400438
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700439 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700440 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700441 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700442 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
443 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700444 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700445
Ian Rogers23435d02012-09-24 11:23:12 -0700446 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700447 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700448 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
449 kClassRootsMax));
450 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700451 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
452 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
453 SetClassRoot(kClassArrayClass, class_array_class.Get());
454 SetClassRoot(kObjectArrayClass, object_array_class.Get());
455 SetClassRoot(kCharArrayClass, char_array_class.Get());
456 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700457 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700458
459 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700460 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
461 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
462 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
463 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
464 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
465 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
466 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
467 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700468
Ian Rogers23435d02012-09-24 11:23:12 -0700469 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700470 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700471
Ian Rogers23435d02012-09-24 11:23:12 -0700472 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700473 Handle<mirror::Class> int_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700474 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700475 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700476 mirror::IntArray::SetArrayClass(int_array_class.Get());
477 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700478
Mathieu Chartierc7853442015-03-27 14:35:38 -0700479 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
480 Handle<mirror::Class> long_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700481 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700482 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
483 mirror::LongArray::SetArrayClass(long_array_class.Get());
484 SetClassRoot(kLongArrayClass, long_array_class.Get());
485
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700486 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700487
Ian Rogers52813c92012-10-11 11:50:38 -0700488 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700489 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700490 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700491 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100492 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700493 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700494 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700495
Mathieu Chartier66f19252012-09-18 08:57:04 -0700496 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700497 Handle<mirror::Class> object_array_string(hs.NewHandle(
498 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700499 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700500 object_array_string->SetComponentType(java_lang_String.Get());
501 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700502
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000503 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700504 // Create runtime resolution and imt conflict methods.
505 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000506 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
507 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700508
Ian Rogers23435d02012-09-24 11:23:12 -0700509 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
510 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
511 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800512 if (boot_class_path.empty()) {
513 *error_msg = "Boot classpath is empty.";
514 return false;
515 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800516 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800517 if (dex_file.get() == nullptr) {
518 *error_msg = "Null dex file.";
519 return false;
520 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700521 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800522 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700523 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700524
525 // now we can use FindSystemClass
526
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700527 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700528 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
529 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700530
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700531 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
532 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700533 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800534 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700535 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700536 quick_resolution_trampoline_ = GetQuickResolutionStub();
537 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
538 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700539 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700540
Mathieu Chartier66f19252012-09-18 08:57:04 -0700541 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700542 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800543 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700544 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700545 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800546 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700547 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800548 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700549 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700550
Ian Rogers23435d02012-09-24 11:23:12 -0700551 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800552 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800553 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700554
Ian Rogers98379392014-02-24 16:53:16 -0800555 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800556 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700557
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800558 CheckSystemClass(self, char_array_class, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559
Ian Rogers98379392014-02-24 16:53:16 -0800560 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800561 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700562
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800563 CheckSystemClass(self, int_array_class, "[I");
564 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700565
Ian Rogers98379392014-02-24 16:53:16 -0800566 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800567 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700568
Ian Rogers98379392014-02-24 16:53:16 -0800569 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800570 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700571
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800572 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
573 // in class_table_.
574 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700575
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800576 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
577 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700578
Ian Rogers23435d02012-09-24 11:23:12 -0700579 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700580 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
581 CHECK(java_lang_Cloneable.Get() != nullptr);
582 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
583 CHECK(java_io_Serializable.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700584 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
585 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700586 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
587 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700588
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700589 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
590 // suspension.
591 CHECK_EQ(java_lang_Cloneable.Get(),
592 mirror::Class::GetDirectInterface(self, class_array_class, 0));
593 CHECK_EQ(java_io_Serializable.Get(),
594 mirror::Class::GetDirectInterface(self, class_array_class, 1));
595 CHECK_EQ(java_lang_Cloneable.Get(),
596 mirror::Class::GetDirectInterface(self, object_array_class, 0));
597 CHECK_EQ(java_io_Serializable.Get(),
598 mirror::Class::GetDirectInterface(self, object_array_class, 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700599
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700600 CHECK_EQ(object_array_string.Get(),
601 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700602
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800603 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700604
Ian Rogers23435d02012-09-24 11:23:12 -0700605 // Create java.lang.reflect.Proxy root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700606 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700607
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700608 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700609 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
610 CHECK(class_root != nullptr);
611 SetClassRoot(kJavaLangReflectField, class_root);
612 mirror::Field::SetClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700613
614 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700615 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
616 CHECK(class_root != nullptr);
617 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
618 mirror::Field::SetArrayClass(class_root);
619
620 // Create java.lang.reflect.Constructor.class root and array root.
621 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
622 CHECK(class_root != nullptr);
623 SetClassRoot(kJavaLangReflectConstructor, class_root);
624 mirror::Constructor::SetClass(class_root);
625 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
626 CHECK(class_root != nullptr);
627 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
628 mirror::Constructor::SetArrayClass(class_root);
629
630 // Create java.lang.reflect.Method.class root and array root.
631 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
632 CHECK(class_root != nullptr);
633 SetClassRoot(kJavaLangReflectMethod, class_root);
634 mirror::Method::SetClass(class_root);
635 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
636 CHECK(class_root != nullptr);
637 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
638 mirror::Method::SetArrayClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700639
Narayan Kamathafa48272016-08-03 12:46:58 +0100640 // Create java.lang.invoke.MethodType.class root
641 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
642 CHECK(class_root != nullptr);
643 SetClassRoot(kJavaLangInvokeMethodType, class_root);
644 mirror::MethodType::SetClass(class_root);
645
646 // Create java.lang.invoke.MethodHandleImpl.class root
647 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
648 CHECK(class_root != nullptr);
649 SetClassRoot(kJavaLangInvokeMethodHandleImpl, class_root);
650 mirror::MethodHandleImpl::SetClass(class_root);
651
Brian Carlstrom1f870082011-08-23 16:02:11 -0700652 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700653 // finish initializing Reference class
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700654 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800655 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700656 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700657 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
658 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700659 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700660 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700661 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700662 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700663 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700664 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700665 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700666 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700667 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700668 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700669 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700670 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700671
Ian Rogers23435d02012-09-24 11:23:12 -0700672 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700673 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700674 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700675 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
676 SetClassRoot(kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700677
jeffhao8cd6dda2012-02-22 10:15:34 -0800678 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700679 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800680 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800681 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700682 SetClassRoot(kJavaLangClassNotFoundException,
683 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800684 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700685 SetClassRoot(kJavaLangStackTraceElementArrayClass,
686 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800687 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700688
Andreas Gampe76bd8802014-12-10 16:43:58 -0800689 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
690 // initialized.
691 {
692 const DexFile& dex_file = java_lang_Object->GetDexFile();
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700693 const DexFile::TypeId* void_type_id = dex_file.FindTypeId("V");
Andreas Gampe76bd8802014-12-10 16:43:58 -0800694 CHECK(void_type_id != nullptr);
695 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
696 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
697 // as referrer so the used dex cache is core's one.
698 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
699 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
700 self->AssertNoPendingException();
701 }
702
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700703 // Create conflict tables that depend on the class linker.
704 runtime->FixupConflictTables();
705
Ian Rogers98379392014-02-24 16:53:16 -0800706 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700707
Brian Carlstroma004aa92012-02-08 18:05:09 -0800708 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800709
710 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700711}
712
Ian Rogers98379392014-02-24 16:53:16 -0800713void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800714 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700715
716 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700717 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700718 // as the types of the field can't be resolved prior to the runtime being
719 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800720 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700721 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800722 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800723
Mathieu Chartierc7853442015-03-27 14:35:38 -0700724 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700725 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
726 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700727
Mathieu Chartierc7853442015-03-27 14:35:38 -0700728 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700729 CHECK_STREQ(queue->GetName(), "queue");
730 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700731
Mathieu Chartierc7853442015-03-27 14:35:38 -0700732 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700733 CHECK_STREQ(queueNext->GetName(), "queueNext");
734 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700735
Mathieu Chartierc7853442015-03-27 14:35:38 -0700736 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700737 CHECK_STREQ(referent->GetName(), "referent");
738 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700739
Mathieu Chartierc7853442015-03-27 14:35:38 -0700740 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700741 CHECK_STREQ(zombie->GetName(), "zombie");
742 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700743
Brian Carlstroma663ea52011-08-19 23:33:41 -0700744 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700745 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700746 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800747 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700748 CHECK(klass != nullptr);
749 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700750 // note SetClassRoot does additional validation.
751 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700752 }
753
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700754 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700755
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700756 // disable the slow paths in FindClass and CreatePrimitiveClass now
757 // that Object, Class, and Object[] are setup
758 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700759
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800760 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700761}
762
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700763void ClassLinker::RunRootClinits() {
764 Thread* self = Thread::Current();
765 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800766 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700767 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700768 StackHandleScope<1> hs(self);
769 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700770 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700771 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700772 }
773 }
774}
775
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -0700776static void SanityCheckArtMethod(ArtMethod* m,
777 mirror::Class* expected_class,
Jeff Haoacd7a6a2016-01-08 10:44:20 -0800778 const std::vector<gc::space::ImageSpace*>& spaces)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700779 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700780 if (m->IsRuntimeMethod()) {
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700781 mirror::Class* declaring_class = m->GetDeclaringClassUnchecked();
782 CHECK(declaring_class == nullptr) << declaring_class << " " << PrettyMethod(m);
Alex Light36121492016-02-22 13:43:29 -0800783 } else if (m->IsCopied()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700784 CHECK(m->GetDeclaringClass() != nullptr) << PrettyMethod(m);
785 } else if (expected_class != nullptr) {
786 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << PrettyMethod(m);
787 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800788 if (!spaces.empty()) {
789 bool contains = false;
790 for (gc::space::ImageSpace* space : spaces) {
791 auto& header = space->GetImageHeader();
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700792 size_t offset = reinterpret_cast<uint8_t*>(m) - space->Begin();
793
794 const ImageSection& methods = header.GetMethodsSection();
795 contains = contains || methods.Contains(offset);
796
797 const ImageSection& runtime_methods = header.GetRuntimeMethodsSection();
798 contains = contains || runtime_methods.Contains(offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800799 }
800 CHECK(contains) << m << " not found";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700801 }
802}
803
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -0700804static void SanityCheckArtMethodPointerArray(mirror::PointerArray* arr,
805 mirror::Class* expected_class,
Andreas Gampe542451c2016-07-26 09:02:02 -0700806 PointerSize pointer_size,
Jeff Haoacd7a6a2016-01-08 10:44:20 -0800807 const std::vector<gc::space::ImageSpace*>& spaces)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700808 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700809 CHECK(arr != nullptr);
810 for (int32_t j = 0; j < arr->GetLength(); ++j) {
811 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size);
812 // expected_class == null means we are a dex cache.
813 if (expected_class != nullptr) {
814 CHECK(method != nullptr);
815 }
816 if (method != nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800817 SanityCheckArtMethod(method, expected_class, spaces);
Ian Rogers848871b2013-08-05 10:56:33 -0700818 }
819 }
820}
821
Jeff Hao1c1a3422016-01-05 14:13:00 -0800822static void SanityCheckArtMethodPointerArray(ArtMethod** arr,
823 size_t size,
Andreas Gampe542451c2016-07-26 09:02:02 -0700824 PointerSize pointer_size,
Jeff Haoacd7a6a2016-01-08 10:44:20 -0800825 const std::vector<gc::space::ImageSpace*>& spaces)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700826 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100827 CHECK_EQ(arr != nullptr, size != 0u);
828 if (arr != nullptr) {
Jeff Hao1c1a3422016-01-05 14:13:00 -0800829 bool contains = false;
830 for (auto space : spaces) {
831 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
832 if (space->GetImageHeader().GetImageSection(
833 ImageHeader::kSectionDexCacheArrays).Contains(offset)) {
834 contains = true;
835 break;
836 }
837 }
838 CHECK(contains);
Vladimir Marko05792b92015-08-03 11:56:49 +0100839 }
840 for (size_t j = 0; j < size; ++j) {
841 ArtMethod* method = mirror::DexCache::GetElementPtrSize(arr, j, pointer_size);
842 // expected_class == null means we are a dex cache.
843 if (method != nullptr) {
Jeff Hao1c1a3422016-01-05 14:13:00 -0800844 SanityCheckArtMethod(method, nullptr, spaces);
Vladimir Marko05792b92015-08-03 11:56:49 +0100845 }
846 }
847}
848
Mathieu Chartiere401d142015-04-22 13:56:20 -0700849static void SanityCheckObjectsCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700850 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700851 DCHECK(obj != nullptr);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700852 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700853 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
854 if (obj->IsClass()) {
855 auto klass = obj->AsClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700856 for (ArtField& field : klass->GetIFields()) {
857 CHECK_EQ(field.GetDeclaringClass(), klass);
858 }
859 for (ArtField& field : klass->GetSFields()) {
860 CHECK_EQ(field.GetDeclaringClass(), klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700861 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700862 auto* runtime = Runtime::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800863 auto image_spaces = runtime->GetHeap()->GetBootImageSpaces();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700864 auto pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
Alex Lighte64300b2015-12-15 15:02:47 -0800865 for (auto& m : klass->GetMethods(pointer_size)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800866 SanityCheckArtMethod(&m, klass, image_spaces);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700867 }
868 auto* vtable = klass->GetVTable();
869 if (vtable != nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800870 SanityCheckArtMethodPointerArray(vtable, nullptr, pointer_size, image_spaces);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700871 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000872 if (klass->ShouldHaveImt()) {
873 ImTable* imt = klass->GetImt(pointer_size);
874 for (size_t i = 0; i < ImTable::kSize; ++i) {
875 SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr, image_spaces);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700876 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000877 }
878 if (klass->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700879 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800880 SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr, image_spaces);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700881 }
882 }
883 auto* iftable = klass->GetIfTable();
884 if (iftable != nullptr) {
885 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
886 if (iftable->GetMethodArrayCount(i) > 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800887 SanityCheckArtMethodPointerArray(
888 iftable->GetMethodArray(i), nullptr, pointer_size, image_spaces);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700889 }
890 }
891 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700892 }
893}
894
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200895// Set image methods' entry point to interpreter.
896class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
897 public:
Andreas Gampe542451c2016-07-26 09:02:02 -0700898 explicit SetInterpreterEntrypointArtMethodVisitor(PointerSize image_pointer_size)
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200899 : image_pointer_size_(image_pointer_size) {}
900
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700901 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200902 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
903 CHECK(method->GetDeclaringClass() != nullptr);
904 }
905 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
906 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
907 image_pointer_size_);
908 }
909 }
910
911 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700912 const PointerSize image_pointer_size_;
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200913
914 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
915};
916
Jeff Haodcdc85b2015-12-04 14:06:18 -0800917struct TrampolineCheckData {
918 const void* quick_resolution_trampoline;
919 const void* quick_imt_conflict_trampoline;
920 const void* quick_generic_jni_trampoline;
921 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700922 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800923 ArtMethod* m;
924 bool error;
925};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800926
Jeff Haodcdc85b2015-12-04 14:06:18 -0800927static void CheckTrampolines(mirror::Object* obj, void* arg) NO_THREAD_SAFETY_ANALYSIS {
928 if (obj->IsClass()) {
929 mirror::Class* klass = obj->AsClass();
930 TrampolineCheckData* d = reinterpret_cast<TrampolineCheckData*>(arg);
931 for (ArtMethod& m : klass->GetMethods(d->pointer_size)) {
932 const void* entrypoint = m.GetEntryPointFromQuickCompiledCodePtrSize(d->pointer_size);
933 if (entrypoint == d->quick_resolution_trampoline ||
934 entrypoint == d->quick_imt_conflict_trampoline ||
935 entrypoint == d->quick_generic_jni_trampoline ||
936 entrypoint == d->quick_to_interpreter_bridge_trampoline) {
937 d->m = &m;
938 d->error = true;
939 return;
940 }
941 }
942 }
943}
944
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800945bool ClassLinker::InitFromBootImage(std::string* error_msg) {
946 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700947 CHECK(!init_done_);
948
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700949 Runtime* const runtime = Runtime::Current();
950 Thread* const self = Thread::Current();
951 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800952 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
953 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700954 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
955 if (!ValidPointerSize(pointer_size_unchecked)) {
956 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800957 return false;
958 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700959 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800960 if (!runtime->IsAotCompiler()) {
961 // Only the Aot compiler supports having an image with a different pointer size than the
962 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
963 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700964 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800965 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700966 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800967 sizeof(void*));
968 return false;
969 }
970 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800971 std::vector<const OatFile*> oat_files =
972 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
973 DCHECK(!oat_files.empty());
974 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
975 CHECK_EQ(default_oat_header.GetImageFileLocationOatChecksum(), 0U);
976 CHECK_EQ(default_oat_header.GetImageFileLocationOatDataBegin(), 0U);
977 const char* image_file_location = oat_files[0]->GetOatHeader().
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700978 GetStoreValueByKey(OatHeader::kImageLocationKey);
979 CHECK(image_file_location == nullptr || *image_file_location == 0);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800980 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
981 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
982 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
983 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
984 if (kIsDebugBuild) {
985 // Check that the other images use the same trampoline.
986 for (size_t i = 1; i < oat_files.size(); ++i) {
987 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
988 const void* ith_quick_resolution_trampoline =
989 ith_oat_header.GetQuickResolutionTrampoline();
990 const void* ith_quick_imt_conflict_trampoline =
991 ith_oat_header.GetQuickImtConflictTrampoline();
992 const void* ith_quick_generic_jni_trampoline =
993 ith_oat_header.GetQuickGenericJniTrampoline();
994 const void* ith_quick_to_interpreter_bridge_trampoline =
995 ith_oat_header.GetQuickToInterpreterBridge();
996 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
997 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
998 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
999 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1000 // Make sure that all methods in this image do not contain those trampolines as
1001 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1002 TrampolineCheckData data;
1003 data.error = false;
1004 data.pointer_size = GetImagePointerSize();
1005 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1006 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1007 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1008 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1009 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1010 spaces[i]->GetLiveBitmap()->Walk(CheckTrampolines, &data);
1011 if (data.error) {
1012 ArtMethod* m = data.m;
1013 LOG(ERROR) << "Found a broken ArtMethod: " << PrettyMethod(m);
1014 *error_msg = "Found an ArtMethod with a bad entrypoint";
1015 return false;
1016 }
1017 }
1018 }
1019 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001020
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001021 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
1022 down_cast<mirror::ObjectArray<mirror::Class>*>(
1023 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)));
1024 mirror::Class::SetClassClass(class_roots_.Read()->Get(kJavaLangClass));
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001025
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001026 // Special case of setting up the String class early so that we can test arbitrary objects
1027 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001028 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001029
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001030 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
1031 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001032 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1033 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001034 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1035 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001036
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001037 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001038 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001039 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001040 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001041 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
1042 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001043 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
1044 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
1045 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
1046 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
Narayan Kamathafa48272016-08-03 12:46:58 +01001047 mirror::MethodType::SetClass(GetClassRoot(kJavaLangInvokeMethodType));
1048 mirror::MethodHandleImpl::SetClass(GetClassRoot(kJavaLangInvokeMethodHandleImpl));
Fred Shih4ee7a662014-07-11 09:59:27 -07001049 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001050 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1051 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1052 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1053 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1054 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1055 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1056 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1057 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1058 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1059 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001060
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001061 for (gc::space::ImageSpace* image_space : spaces) {
1062 // Boot class loader, use a null handle.
1063 std::vector<std::unique_ptr<const DexFile>> dex_files;
1064 if (!AddImageSpace(image_space,
1065 ScopedNullHandle<mirror::ClassLoader>(),
1066 /*dex_elements*/nullptr,
1067 /*dex_location*/nullptr,
1068 /*out*/&dex_files,
1069 error_msg)) {
1070 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001071 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001072 // Append opened dex files at the end.
1073 boot_dex_files_.insert(boot_dex_files_.end(),
1074 std::make_move_iterator(dex_files.begin()),
1075 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001076 }
Ian Rogers98379392014-02-24 16:53:16 -08001077 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001078
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001079 VLOG(startup) << __FUNCTION__ << " exiting";
1080 return true;
1081}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001082
Jeff Hao5872d7c2016-04-27 11:07:41 -07001083bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1084 mirror::ClassLoader* class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001085 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001086 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1087 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001088}
1089
1090static mirror::String* GetDexPathListElementName(ScopedObjectAccessUnchecked& soa,
Mathieu Chartier3398c782016-09-30 10:27:43 -07001091 ObjPtr<mirror::Object> element)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001092 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001093 ArtField* const dex_file_field =
1094 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
1095 ArtField* const dex_file_name_field =
1096 soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_fileName);
1097 DCHECK(dex_file_field != nullptr);
1098 DCHECK(dex_file_name_field != nullptr);
1099 DCHECK(element != nullptr);
1100 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << PrettyTypeOf(element);
Mathieu Chartier3398c782016-09-30 10:27:43 -07001101 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001102 if (dex_file == nullptr) {
1103 return nullptr;
1104 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001105 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001106 if (name_object != nullptr) {
1107 return name_object->AsString();
1108 }
1109 return nullptr;
1110}
1111
1112static bool FlattenPathClassLoader(mirror::ClassLoader* class_loader,
1113 std::list<mirror::String*>* out_dex_file_names,
1114 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001115 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001116 DCHECK(out_dex_file_names != nullptr);
1117 DCHECK(error_msg != nullptr);
1118 ScopedObjectAccessUnchecked soa(Thread::Current());
1119 ArtField* const dex_path_list_field =
1120 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList);
1121 ArtField* const dex_elements_field =
1122 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
1123 CHECK(dex_path_list_field != nullptr);
1124 CHECK(dex_elements_field != nullptr);
Jeff Hao5872d7c2016-04-27 11:07:41 -07001125 while (!ClassLinker::IsBootClassLoader(soa, class_loader)) {
Mathieu Chartier0795f232016-09-27 18:43:30 -07001126 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1127 class_loader->GetClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001128 *error_msg = StringPrintf("Unknown class loader type %s", PrettyTypeOf(class_loader).c_str());
1129 // Unsupported class loader.
1130 return false;
1131 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001132 ObjPtr<mirror::Object> dex_path_list = dex_path_list_field->GetObject(class_loader);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001133 if (dex_path_list != nullptr) {
1134 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
Mathieu Chartier3398c782016-09-30 10:27:43 -07001135 ObjPtr<mirror::Object> dex_elements_obj = dex_elements_field->GetObject(dex_path_list);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001136 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1137 // at the mCookie which is a DexFile vector.
1138 if (dex_elements_obj != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001139 ObjPtr<mirror::ObjectArray<mirror::Object>> dex_elements =
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001140 dex_elements_obj->AsObjectArray<mirror::Object>();
1141 // Reverse order since we insert the parent at the front.
1142 for (int32_t i = dex_elements->GetLength() - 1; i >= 0; --i) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07001143 ObjPtr<mirror::Object> element = dex_elements->GetWithoutChecks(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001144 if (element == nullptr) {
1145 *error_msg = StringPrintf("Null dex element at index %d", i);
1146 return false;
1147 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001148 ObjPtr<mirror::String> const name = GetDexPathListElementName(soa, element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001149 if (name == nullptr) {
1150 *error_msg = StringPrintf("Null name for dex element at index %d", i);
1151 return false;
1152 }
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001153 out_dex_file_names->push_front(name.Ptr());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001154 }
1155 }
1156 }
1157 class_loader = class_loader->GetParent();
1158 }
1159 return true;
1160}
1161
1162class FixupArtMethodArrayVisitor : public ArtMethodVisitor {
1163 public:
1164 explicit FixupArtMethodArrayVisitor(const ImageHeader& header) : header_(header) {}
1165
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001166 virtual void Visit(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001167 GcRoot<mirror::Class>* resolved_types = method->GetDexCacheResolvedTypes(kRuntimePointerSize);
Alex Light36121492016-02-22 13:43:29 -08001168 const bool is_copied = method->IsCopied();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001169 if (resolved_types != nullptr) {
1170 bool in_image_space = false;
Alex Light36121492016-02-22 13:43:29 -08001171 if (kIsDebugBuild || is_copied) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001172 in_image_space = header_.GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains(
1173 reinterpret_cast<const uint8_t*>(resolved_types) - header_.GetImageBegin());
1174 }
1175 // Must be in image space for non-miranda method.
Alex Light36121492016-02-22 13:43:29 -08001176 DCHECK(is_copied || in_image_space)
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001177 << resolved_types << " is not in image starting at "
1178 << reinterpret_cast<void*>(header_.GetImageBegin());
Alex Light36121492016-02-22 13:43:29 -08001179 if (!is_copied || in_image_space) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001180 // Go through the array so that we don't need to do a slow map lookup.
1181 method->SetDexCacheResolvedTypes(*reinterpret_cast<GcRoot<mirror::Class>**>(resolved_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07001182 kRuntimePointerSize);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001183 }
1184 }
Andreas Gampe542451c2016-07-26 09:02:02 -07001185 ArtMethod** resolved_methods = method->GetDexCacheResolvedMethods(kRuntimePointerSize);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001186 if (resolved_methods != nullptr) {
1187 bool in_image_space = false;
Alex Light36121492016-02-22 13:43:29 -08001188 if (kIsDebugBuild || is_copied) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001189 in_image_space = header_.GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains(
1190 reinterpret_cast<const uint8_t*>(resolved_methods) - header_.GetImageBegin());
1191 }
1192 // Must be in image space for non-miranda method.
Alex Light36121492016-02-22 13:43:29 -08001193 DCHECK(is_copied || in_image_space)
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001194 << resolved_methods << " is not in image starting at "
1195 << reinterpret_cast<void*>(header_.GetImageBegin());
Alex Light36121492016-02-22 13:43:29 -08001196 if (!is_copied || in_image_space) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001197 // Go through the array so that we don't need to do a slow map lookup.
1198 method->SetDexCacheResolvedMethods(*reinterpret_cast<ArtMethod***>(resolved_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07001199 kRuntimePointerSize);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001200 }
1201 }
1202 }
1203
1204 private:
1205 const ImageHeader& header_;
1206};
1207
1208class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1209 public:
1210 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1211
1212 virtual void Visit(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001213 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001214 mirror::Class* klass = method->GetDeclaringClass();
1215 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1216 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << PrettyClass(klass);
1217 }
1218 }
1219
1220 private:
1221 ClassTable* const table_;
1222};
1223
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001224class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1225 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001226 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001227 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1228
1229 virtual void Visit(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001230 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001231 mirror::Class* klass = method->GetDeclaringClassUnchecked();
1232 if (klass != nullptr) {
1233 CHECK(live_bitmap_->Test(klass)) << "Image method has unmarked declaring class";
1234 }
1235 }
1236
1237 private:
1238 gc::accounting::HeapBitmap* const live_bitmap_;
1239};
1240
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001241bool ClassLinker::UpdateAppImageClassLoadersAndDexCaches(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001242 gc::space::ImageSpace* space,
1243 Handle<mirror::ClassLoader> class_loader,
1244 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Mathieu Chartier69731002016-03-02 16:08:31 -08001245 ClassTable::ClassSet* new_class_set,
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001246 bool* out_forward_dex_cache_array,
1247 std::string* out_error_msg) {
1248 DCHECK(out_forward_dex_cache_array != nullptr);
1249 DCHECK(out_error_msg != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001250 Thread* const self = Thread::Current();
1251 gc::Heap* const heap = Runtime::Current()->GetHeap();
1252 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001253 {
1254 // Add image classes into the class table for the class loader, and fixup the dex caches and
1255 // class loader fields.
1256 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001257 // Dex cache array fixup is all or nothing, we must reject app images that have mixed since we
1258 // rely on clobering the dex cache arrays in the image to forward to bss.
1259 size_t num_dex_caches_with_bss_arrays = 0;
1260 const size_t num_dex_caches = dex_caches->GetLength();
1261 for (size_t i = 0; i < num_dex_caches; i++) {
1262 mirror::DexCache* const dex_cache = dex_caches->Get(i);
1263 const DexFile* const dex_file = dex_cache->GetDexFile();
1264 const OatFile::OatDexFile* oat_dex_file = dex_file->GetOatDexFile();
1265 if (oat_dex_file != nullptr && oat_dex_file->GetDexCacheArrays() != nullptr) {
1266 ++num_dex_caches_with_bss_arrays;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001267 }
1268 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001269 *out_forward_dex_cache_array = num_dex_caches_with_bss_arrays != 0;
1270 if (*out_forward_dex_cache_array) {
1271 if (num_dex_caches_with_bss_arrays != num_dex_caches) {
1272 // Reject application image since we cannot forward only some of the dex cache arrays.
1273 // TODO: We could get around this by having a dedicated forwarding slot. It should be an
1274 // uncommon case.
1275 *out_error_msg = StringPrintf("Dex caches in bss does not match total: %zu vs %zu",
1276 num_dex_caches_with_bss_arrays,
1277 num_dex_caches);
1278 return false;
1279 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001280 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001281 // Only add the classes to the class loader after the points where we can return false.
1282 for (size_t i = 0; i < num_dex_caches; i++) {
1283 mirror::DexCache* const dex_cache = dex_caches->Get(i);
1284 const DexFile* const dex_file = dex_cache->GetDexFile();
1285 const OatFile::OatDexFile* oat_dex_file = dex_file->GetOatDexFile();
1286 if (oat_dex_file != nullptr && oat_dex_file->GetDexCacheArrays() != nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01001287 // 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 -08001288 // copy over the arrays.
1289 DCHECK(dex_file != nullptr);
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001290 size_t num_strings = mirror::DexCache::kDexCacheStringCacheSize;
1291 if (dex_file->NumStringIds() < num_strings) {
1292 num_strings = dex_file->NumStringIds();
1293 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001294 const size_t num_types = dex_file->NumTypeIds();
1295 const size_t num_methods = dex_file->NumMethodIds();
1296 const size_t num_fields = dex_file->NumFieldIds();
Narayan Kamath25352fc2016-08-03 12:46:58 +01001297 size_t num_method_types = 0;
1298 if (Runtime::Current()->IsMethodHandlesEnabled()) {
1299 num_method_types = mirror::DexCache::kDexCacheMethodTypeCacheSize;
1300 if (dex_file->NumProtoIds() < num_method_types) {
1301 num_method_types = dex_file->NumProtoIds();
1302 }
1303 }
1304
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001305 CHECK_EQ(num_strings, dex_cache->NumStrings());
1306 CHECK_EQ(num_types, dex_cache->NumResolvedTypes());
1307 CHECK_EQ(num_methods, dex_cache->NumResolvedMethods());
1308 CHECK_EQ(num_fields, dex_cache->NumResolvedFields());
Narayan Kamath25352fc2016-08-03 12:46:58 +01001309 CHECK_EQ(num_method_types, dex_cache->NumResolvedMethodTypes());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001310 DexCacheArraysLayout layout(image_pointer_size_, dex_file);
1311 uint8_t* const raw_arrays = oat_dex_file->GetDexCacheArrays();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001312 if (num_strings != 0u) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001313 mirror::StringDexCacheType* const image_resolved_strings = dex_cache->GetStrings();
1314 mirror::StringDexCacheType* const strings =
1315 reinterpret_cast<mirror::StringDexCacheType*>(raw_arrays + layout.StringsOffset());
1316 for (size_t j = 0; j < num_strings; ++j) {
Narayan Kamathc38a6f82016-09-29 17:07:20 +01001317 DCHECK_EQ(strings[j].load(std::memory_order_relaxed).index, 0u);
1318 DCHECK(strings[j].load(std::memory_order_relaxed).object.IsNull());
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001319 strings[j].store(image_resolved_strings[j].load(std::memory_order_relaxed),
1320 std::memory_order_relaxed);
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -08001321 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001322 mirror::StringDexCachePair::Initialize(strings);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001323 dex_cache->SetStrings(strings);
1324 }
1325 if (num_types != 0u) {
1326 GcRoot<mirror::Class>* const image_resolved_types = dex_cache->GetResolvedTypes();
1327 GcRoot<mirror::Class>* const types =
1328 reinterpret_cast<GcRoot<mirror::Class>*>(raw_arrays + layout.TypesOffset());
1329 for (size_t j = 0; kIsDebugBuild && j < num_types; ++j) {
1330 DCHECK(types[j].IsNull());
1331 }
1332 std::copy_n(image_resolved_types, num_types, types);
1333 // Store a pointer to the new location for fast ArtMethod patching without requiring map.
1334 // This leaves random garbage at the start of the dex cache array, but nobody should ever
1335 // read from it again.
1336 *reinterpret_cast<GcRoot<mirror::Class>**>(image_resolved_types) = types;
1337 dex_cache->SetResolvedTypes(types);
1338 }
1339 if (num_methods != 0u) {
1340 ArtMethod** const methods = reinterpret_cast<ArtMethod**>(
1341 raw_arrays + layout.MethodsOffset());
1342 ArtMethod** const image_resolved_methods = dex_cache->GetResolvedMethods();
1343 for (size_t j = 0; kIsDebugBuild && j < num_methods; ++j) {
1344 DCHECK(methods[j] == nullptr);
1345 }
1346 std::copy_n(image_resolved_methods, num_methods, methods);
1347 // Store a pointer to the new location for fast ArtMethod patching without requiring map.
1348 *reinterpret_cast<ArtMethod***>(image_resolved_methods) = methods;
1349 dex_cache->SetResolvedMethods(methods);
1350 }
1351 if (num_fields != 0u) {
1352 ArtField** const fields =
1353 reinterpret_cast<ArtField**>(raw_arrays + layout.FieldsOffset());
1354 for (size_t j = 0; kIsDebugBuild && j < num_fields; ++j) {
1355 DCHECK(fields[j] == nullptr);
1356 }
1357 std::copy_n(dex_cache->GetResolvedFields(), num_fields, fields);
1358 dex_cache->SetResolvedFields(fields);
1359 }
Narayan Kamath25352fc2016-08-03 12:46:58 +01001360 if (num_method_types != 0u) {
1361 // NOTE: We currently (Sep 2016) do not resolve any method types at
1362 // compile time, but plan to in the future. This code exists for the
1363 // sake of completeness.
1364 mirror::MethodTypeDexCacheType* const image_resolved_method_types =
1365 dex_cache->GetResolvedMethodTypes();
1366 mirror::MethodTypeDexCacheType* const method_types =
1367 reinterpret_cast<mirror::MethodTypeDexCacheType*>(
1368 raw_arrays + layout.MethodTypesOffset());
1369 for (size_t j = 0; j < num_method_types; ++j) {
1370 DCHECK_EQ(method_types[j].load(std::memory_order_relaxed).index, 0u);
1371 DCHECK(method_types[j].load(std::memory_order_relaxed).object.IsNull());
1372 method_types[j].store(
1373 image_resolved_method_types[j].load(std::memory_order_relaxed),
1374 std::memory_order_relaxed);
1375 }
1376
1377 dex_cache->SetResolvedMethodTypes(method_types);
1378 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001379 }
1380 {
1381 WriterMutexLock mu2(self, dex_lock_);
1382 // Make sure to do this after we update the arrays since we store the resolved types array
1383 // in DexCacheData in RegisterDexFileLocked. We need the array pointer to be the one in the
1384 // BSS.
1385 mirror::DexCache* existing_dex_cache = FindDexCacheLocked(self,
1386 *dex_file,
1387 /*allow_failure*/true);
1388 CHECK(existing_dex_cache == nullptr);
1389 StackHandleScope<1> hs3(self);
1390 RegisterDexFileLocked(*dex_file, hs3.NewHandle(dex_cache));
1391 }
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001392 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001393 CHECK(new_class_set != nullptr);
1394 GcRoot<mirror::Class>* const types = dex_cache->GetResolvedTypes();
1395 const size_t num_types = dex_cache->NumResolvedTypes();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001396 for (int32_t j = 0; j < static_cast<int32_t>(num_types); j++) {
1397 // The image space is not yet added to the heap, avoid read barriers.
1398 mirror::Class* klass = types[j].Read();
Mathieu Chartier55accd52016-05-24 17:41:21 -07001399 if (space->HasAddress(klass)) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001400 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
Vladimir Marko1a1de672016-10-13 12:53:15 +01001401 auto it = new_class_set->Find(GcRoot<mirror::Class>(klass));
1402 DCHECK(it != new_class_set->end());
1403 DCHECK_EQ(it->Read(), klass);
1404 mirror::Class* super_class = klass->GetSuperClass();
1405 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
1406 auto it2 = new_class_set->Find(GcRoot<mirror::Class>(super_class));
1407 DCHECK(it2 != new_class_set->end());
1408 DCHECK_EQ(it2->Read(), super_class);
1409 }
1410 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1411 const void* code = m.GetEntryPointFromQuickCompiledCode();
1412 const void* oat_code = m.IsInvokable() ? GetQuickOatCodeFor(&m) : code;
1413 if (!IsQuickResolutionStub(code) &&
1414 !IsQuickGenericJniStub(code) &&
1415 !IsQuickToInterpreterBridge(code) &&
1416 !m.IsNative()) {
1417 DCHECK_EQ(code, oat_code) << PrettyMethod(&m);
Mathieu Chartier69731002016-03-02 16:08:31 -08001418 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001419 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01001420 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1421 const void* code = m.GetEntryPointFromQuickCompiledCode();
1422 const void* oat_code = m.IsInvokable() ? GetQuickOatCodeFor(&m) : code;
1423 if (!IsQuickResolutionStub(code) &&
1424 !IsQuickGenericJniStub(code) &&
1425 !IsQuickToInterpreterBridge(code) &&
1426 !m.IsNative()) {
1427 DCHECK_EQ(code, oat_code) << PrettyMethod(&m);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001428 }
1429 }
1430 }
1431 }
1432 }
1433 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001434 }
1435 if (*out_forward_dex_cache_array) {
1436 ScopedTrace timing("Fixup ArtMethod dex cache arrays");
1437 FixupArtMethodArrayVisitor visitor(header);
Andreas Gampe542451c2016-07-26 09:02:02 -07001438 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001439 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get());
1440 }
1441 if (kVerifyArtMethodDeclaringClasses) {
1442 ScopedTrace timing("Verify declaring classes");
1443 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1444 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001445 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001446 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001447 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001448}
1449
Mathieu Chartier69731002016-03-02 16:08:31 -08001450// Update the class loader and resolved string dex cache array of classes. Should only be used on
1451// classes in the image space.
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001452class UpdateClassLoaderAndResolvedStringsVisitor {
1453 public:
1454 UpdateClassLoaderAndResolvedStringsVisitor(gc::space::ImageSpace* space,
1455 mirror::ClassLoader* class_loader,
1456 bool forward_strings)
1457 : space_(space),
1458 class_loader_(class_loader),
1459 forward_strings_(forward_strings) {}
1460
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001461 bool operator()(mirror::Class* klass) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001462 if (forward_strings_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001463 mirror::StringDexCacheType* strings = klass->GetDexCacheStrings();
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001464 if (strings != nullptr) {
Vladimir Marko69a04052016-02-02 14:43:28 +00001465 DCHECK(
1466 space_->GetImageHeader().GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains(
1467 reinterpret_cast<uint8_t*>(strings) - space_->Begin()))
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001468 << "String dex cache array for " << PrettyClass(klass) << " is not in app image";
Vladimir Marko69a04052016-02-02 14:43:28 +00001469 // Dex caches have already been updated, so take the strings pointer from there.
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001470 mirror::StringDexCacheType* new_strings = klass->GetDexCache()->GetStrings();
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001471 DCHECK_NE(strings, new_strings);
1472 klass->SetDexCacheStrings(new_strings);
1473 }
1474 }
1475 // Finally, update class loader.
1476 klass->SetClassLoader(class_loader_);
1477 return true;
1478 }
1479
1480 gc::space::ImageSpace* const space_;
1481 mirror::ClassLoader* const class_loader_;
1482 const bool forward_strings_;
1483};
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();
1520 mirror::Object* dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
1521 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++) {
1526 mirror::DexCache* dex_cache = dex_caches->Get(i);
1527 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
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001540bool ClassLinker::AddImageSpace(
1541 gc::space::ImageSpace* space,
1542 Handle<mirror::ClassLoader> class_loader,
1543 jobjectArray dex_elements,
1544 const char* dex_location,
1545 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1546 std::string* error_msg) {
1547 DCHECK(out_dex_files != nullptr);
1548 DCHECK(error_msg != nullptr);
1549 const uint64_t start_time = NanoTime();
1550 const bool app_image = class_loader.Get() != nullptr;
1551 const ImageHeader& header = space->GetImageHeader();
1552 mirror::Object* dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
1553 DCHECK(dex_caches_object != nullptr);
1554 Runtime* const runtime = Runtime::Current();
1555 gc::Heap* const heap = runtime->GetHeap();
1556 Thread* const self = Thread::Current();
1557 StackHandleScope<2> hs(self);
1558 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1559 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1560 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1561 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
1562 const OatFile* oat_file = space->GetOatFile();
1563 std::unordered_set<mirror::ClassLoader*> image_class_loaders;
1564 // Check that the image is what we are expecting.
1565 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1566 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1567 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1568 image_pointer_size_);
1569 return false;
1570 }
1571 DCHECK(class_roots.Get() != nullptr);
1572 if (class_roots->GetLength() != static_cast<int32_t>(kClassRootsMax)) {
1573 *error_msg = StringPrintf("Expected %d class roots but got %d",
1574 class_roots->GetLength(),
1575 static_cast<int32_t>(kClassRootsMax));
1576 return false;
1577 }
1578 // Check against existing class roots to make sure they match the ones in the boot image.
1579 for (size_t i = 0; i < kClassRootsMax; i++) {
1580 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i))) {
1581 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1582 return false;
1583 }
1584 }
1585 if (oat_file->GetOatHeader().GetDexFileCount() !=
1586 static_cast<uint32_t>(dex_caches->GetLength())) {
1587 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1588 "image";
1589 return false;
1590 }
1591
1592 StackHandleScope<1> hs2(self);
1593 MutableHandle<mirror::DexCache> h_dex_cache(hs2.NewHandle<mirror::DexCache>(nullptr));
1594 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1595 h_dex_cache.Assign(dex_caches->Get(i));
1596 std::string dex_file_location(h_dex_cache->GetLocation()->ToModifiedUtf8());
1597 // TODO: Only store qualified paths.
1598 // If non qualified, qualify it.
1599 if (dex_file_location.find('/') == std::string::npos) {
1600 std::string dex_location_path = dex_location;
1601 const size_t pos = dex_location_path.find_last_of('/');
1602 CHECK_NE(pos, std::string::npos);
1603 dex_location_path = dex_location_path.substr(0, pos + 1); // Keep trailing '/'
1604 dex_file_location = dex_location_path + dex_file_location;
1605 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001606 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1607 dex_file_location.c_str(),
1608 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001609 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001610 return false;
1611 }
1612
1613 if (app_image) {
1614 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
1615 // loop below.
1616 h_dex_cache->SetDexFile(dex_file.get());
1617 // Check that each class loader resolved the same way.
1618 // TODO: Store image class loaders as image roots.
1619 GcRoot<mirror::Class>* const types = h_dex_cache->GetResolvedTypes();
1620 for (int32_t j = 0, num_types = h_dex_cache->NumResolvedTypes(); j < num_types; j++) {
1621 mirror::Class* klass = types[j].Read();
1622 if (klass != nullptr) {
1623 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1624 mirror::ClassLoader* image_class_loader = klass->GetClassLoader();
1625 image_class_loaders.insert(image_class_loader);
1626 }
1627 }
1628 } else {
1629 if (kSanityCheckObjects) {
1630 SanityCheckArtMethodPointerArray(h_dex_cache->GetResolvedMethods(),
1631 h_dex_cache->NumResolvedMethods(),
1632 image_pointer_size_,
1633 heap->GetBootImageSpaces());
1634 }
1635 // Register dex files, keep track of existing ones that are conflicts.
1636 AppendToBootClassPath(*dex_file.get(), h_dex_cache);
1637 }
1638 out_dex_files->push_back(std::move(dex_file));
1639 }
1640
1641 if (app_image) {
1642 ScopedObjectAccessUnchecked soa(Thread::Current());
1643 // Check that the class loader resolves the same way as the ones in the image.
1644 // Image class loader [A][B][C][image dex files]
1645 // Class loader = [???][dex_elements][image dex files]
1646 // Need to ensure that [???][dex_elements] == [A][B][C].
1647 // For each class loader, PathClassLoader, the laoder checks the parent first. Also the logic
1648 // for PathClassLoader does this by looping through the array of dex files. To ensure they
1649 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
1650 // and check that the dex file names are the same.
1651 for (mirror::ClassLoader* image_class_loader : image_class_loaders) {
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01001652 if (IsBootClassLoader(soa, image_class_loader)) {
1653 // The dex cache can reference types from the boot class loader.
1654 continue;
1655 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001656 std::list<mirror::String*> image_dex_file_names;
1657 std::string temp_error_msg;
1658 if (!FlattenPathClassLoader(image_class_loader, &image_dex_file_names, &temp_error_msg)) {
1659 *error_msg = StringPrintf("Failed to flatten image class loader hierarchy '%s'",
1660 temp_error_msg.c_str());
1661 return false;
1662 }
1663 std::list<mirror::String*> loader_dex_file_names;
1664 if (!FlattenPathClassLoader(class_loader.Get(), &loader_dex_file_names, &temp_error_msg)) {
1665 *error_msg = StringPrintf("Failed to flatten class loader hierarchy '%s'",
1666 temp_error_msg.c_str());
1667 return false;
1668 }
1669 // Add the temporary dex path list elements at the end.
Mathieu Chartier0795f232016-09-27 18:43:30 -07001670 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001671 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
1672 mirror::Object* element = elements->GetWithoutChecks(i);
1673 if (element != nullptr) {
1674 // If we are somewhere in the middle of the array, there may be nulls at the end.
1675 loader_dex_file_names.push_back(GetDexPathListElementName(soa, element));
1676 }
1677 }
1678 // Ignore the number of image dex files since we are adding those to the class loader anyways.
1679 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
1680 static_cast<size_t>(dex_caches->GetLength()));
1681 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
1682 // Check that the dex file names match.
1683 bool equal = image_count == loader_dex_file_names.size();
1684 if (equal) {
1685 auto it1 = image_dex_file_names.begin();
1686 auto it2 = loader_dex_file_names.begin();
1687 for (size_t i = 0; equal && i < image_count; ++i, ++it1, ++it2) {
1688 equal = equal && (*it1)->Equals(*it2);
1689 }
1690 }
1691 if (!equal) {
Mathieu Chartierd329a3b2016-01-27 15:30:10 -08001692 VLOG(image) << "Image dex files " << image_dex_file_names.size();
1693 for (mirror::String* name : image_dex_file_names) {
1694 VLOG(image) << name->ToModifiedUtf8();
1695 }
1696 VLOG(image) << "Loader dex files " << loader_dex_file_names.size();
1697 for (mirror::String* name : loader_dex_file_names) {
1698 VLOG(image) << name->ToModifiedUtf8();
1699 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001700 *error_msg = "Rejecting application image due to class loader mismatch";
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001701 // Ignore class loader mismatch for now since these would just use possibly incorrect
1702 // oat code anyways. The structural class check should be done in the parent.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001703 }
1704 }
1705 }
1706
1707 if (kSanityCheckObjects) {
1708 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1709 auto* dex_cache = dex_caches->Get(i);
1710 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
1711 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
1712 if (field != nullptr) {
1713 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
1714 }
1715 }
1716 }
1717 if (!app_image) {
1718 heap->VisitObjects(SanityCheckObjectsCallback, nullptr);
1719 }
1720 }
1721
1722 // Set entry point to interpreter if in InterpretOnly mode.
1723 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001724 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001725 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001726 }
1727
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001728 ClassTable* class_table = nullptr;
1729 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001730 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001731 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08001732 }
1733 // If we have a class table section, read it and use it for verification in
1734 // UpdateAppImageClassLoadersAndDexCaches.
1735 ClassTable::ClassSet temp_set;
1736 const ImageSection& class_table_section = header.GetImageSection(ImageHeader::kSectionClassTable);
1737 const bool added_class_table = class_table_section.Size() > 0u;
1738 if (added_class_table) {
1739 const uint64_t start_time2 = NanoTime();
1740 size_t read_count = 0;
1741 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
1742 /*make copy*/false,
1743 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08001744 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001745 }
1746 if (app_image) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001747 bool forward_dex_cache_arrays = false;
1748 if (!UpdateAppImageClassLoadersAndDexCaches(space,
1749 class_loader,
1750 dex_caches,
Vladimir Marko1a1de672016-10-13 12:53:15 +01001751 &temp_set,
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001752 /*out*/&forward_dex_cache_arrays,
1753 /*out*/error_msg)) {
1754 return false;
1755 }
Mathieu Chartier69731002016-03-02 16:08:31 -08001756 // Update class loader and resolved strings. If added_class_table is false, the resolved
1757 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
1758 UpdateClassLoaderAndResolvedStringsVisitor visitor(space,
1759 class_loader.Get(),
1760 forward_dex_cache_arrays);
Vladimir Marko1a1de672016-10-13 12:53:15 +01001761 for (GcRoot<mirror::Class>& root : temp_set) {
1762 visitor(root.Read());
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001763 }
Mathieu Chartier8c4f0412016-02-03 16:40:20 -08001764 // forward_dex_cache_arrays is true iff we copied all of the dex cache arrays into the .bss.
1765 // In this case, madvise away the dex cache arrays section of the image to reduce RAM usage and
1766 // mark as PROT_NONE to catch any invalid accesses.
1767 if (forward_dex_cache_arrays) {
1768 const ImageSection& dex_cache_section = header.GetImageSection(
1769 ImageHeader::kSectionDexCacheArrays);
1770 uint8_t* section_begin = AlignUp(space->Begin() + dex_cache_section.Offset(), kPageSize);
1771 uint8_t* section_end = AlignDown(space->Begin() + dex_cache_section.End(), kPageSize);
1772 if (section_begin < section_end) {
1773 madvise(section_begin, section_end - section_begin, MADV_DONTNEED);
1774 mprotect(section_begin, section_end - section_begin, PROT_NONE);
1775 VLOG(image) << "Released and protected dex cache array image section from "
1776 << reinterpret_cast<const void*>(section_begin) << "-"
1777 << reinterpret_cast<const void*>(section_end);
1778 }
1779 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001780 }
Mathieu Chartier69731002016-03-02 16:08:31 -08001781 if (added_class_table) {
1782 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1783 class_table->AddClassSet(std::move(temp_set));
1784 }
1785 if (kIsDebugBuild && app_image) {
1786 // This verification needs to happen after the classes have been added to the class loader.
1787 // Since it ensures classes are in the class table.
1788 VerifyClassInTableArtMethodVisitor visitor2(class_table);
Andreas Gampe542451c2016-07-26 09:02:02 -07001789 header.VisitPackedArtMethods(&visitor2, space->Begin(), kRuntimePointerSize);
Mathieu Chartier69731002016-03-02 16:08:31 -08001790 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001791 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001792 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001793}
1794
Mathieu Chartiere401d142015-04-22 13:56:20 -07001795bool ClassLinker::ClassInClassTable(mirror::Class* klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001796 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
1797 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001798}
1799
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001800void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07001801 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
1802 // enabling tracing requires the mutator lock, there are no race conditions here.
1803 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001804 Thread* const self = Thread::Current();
1805 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001806 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
1807 visitor, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001808 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001809 // Argument for how root visiting deals with ArtField and ArtMethod roots.
1810 // There is 3 GC cases to handle:
1811 // Non moving concurrent:
1812 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001813 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001814 //
1815 // Moving non-concurrent:
1816 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
1817 // To prevent missing roots, this case needs to ensure that there is no
1818 // suspend points between the point which we allocate ArtMethod arrays and place them in a
1819 // class which is in the class table.
1820 //
1821 // Moving concurrent:
1822 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
1823 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001824 boot_class_table_.VisitRoots(buffered_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07001825
1826 // If tracing is enabled, then mark all the class loaders to prevent unloading.
1827 if (tracing_enabled) {
1828 for (const ClassLoaderData& data : class_loaders_) {
1829 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
1830 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
1831 }
1832 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001833 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001834 for (auto& root : new_class_roots_) {
1835 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001836 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001837 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001838 // Concurrent moving GC marked new roots through the to-space invariant.
1839 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001840 }
1841 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001842 buffered_visitor.Flush(); // Flush before clearing new_class_roots_.
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001843 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1844 new_class_roots_.clear();
1845 }
1846 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1847 log_new_class_table_roots_ = true;
1848 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1849 log_new_class_table_roots_ = false;
1850 }
1851 // We deliberately ignore the class roots in the image since we
1852 // handle image roots by using the MS/CMS rescanning of dirty cards.
1853}
1854
Brian Carlstroma663ea52011-08-19 23:33:41 -07001855// Keep in sync with InitCallback. Anything we visit, we need to
1856// reinit references to when reinitializing a ClassLinker from a
1857// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001858void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07001859 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001860 VisitClassRoots(visitor, flags);
Mathieu Chartier31000802015-06-14 14:14:37 -07001861 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07001862 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
1863 // unloading if we are marking roots.
1864 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001865}
1866
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001867class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
1868 public:
1869 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
1870 : visitor_(visitor),
1871 done_(false) {}
1872
1873 void Visit(mirror::ClassLoader* class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001874 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001875 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001876 if (!done_ && class_table != nullptr && !class_table->Visit(*visitor_)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001877 // If the visitor ClassTable returns false it means that we don't need to continue.
1878 done_ = true;
1879 }
1880 }
1881
1882 private:
1883 ClassVisitor* const visitor_;
1884 // If done is true then we don't need to do any more visiting.
1885 bool done_;
1886};
1887
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001888void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001889 if (boot_class_table_.Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001890 VisitClassLoaderClassesVisitor loader_visitor(visitor);
1891 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001892 }
1893}
1894
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001895void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001896 Thread* const self = Thread::Current();
1897 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1898 // Not safe to have thread suspension when we are holding a lock.
1899 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001900 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001901 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001902 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001903 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08001904 }
1905}
1906
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001907class GetClassesInToVector : public ClassVisitor {
1908 public:
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001909 bool operator()(mirror::Class* klass) OVERRIDE {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001910 classes_.push_back(klass);
1911 return true;
1912 }
1913 std::vector<mirror::Class*> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07001914};
1915
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001916class GetClassInToObjectArray : public ClassVisitor {
1917 public:
1918 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
1919 : arr_(arr), index_(0) {}
1920
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001921 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001922 ++index_;
1923 if (index_ <= arr_->GetLength()) {
1924 arr_->Set(index_ - 1, klass);
1925 return true;
1926 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001927 return false;
1928 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001929
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001930 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001931 return index_ <= arr_->GetLength();
1932 }
1933
1934 private:
1935 mirror::ObjectArray<mirror::Class>* const arr_;
1936 int32_t index_;
1937};
1938
1939void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001940 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1941 // is avoiding duplicates.
1942 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001943 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001944 GetClassesInToVector accumulator;
1945 VisitClasses(&accumulator);
1946 for (mirror::Class* klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001947 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001948 return;
1949 }
1950 }
1951 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001952 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001953 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001954 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07001955 // We size the array assuming classes won't be added to the class table during the visit.
1956 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001957 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001958 size_t class_table_size;
1959 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001960 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001961 // Add 100 in case new classes get loaded when we are filling in the object array.
1962 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07001963 }
1964 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1965 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1966 classes.Assign(
1967 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1968 CHECK(classes.Get() != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001969 GetClassInToObjectArray accumulator(classes.Get());
1970 VisitClasses(&accumulator);
1971 if (accumulator.Succeeded()) {
1972 break;
1973 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001974 }
1975 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1976 // If the class table shrank during creation of the clases array we expect null elements. If
1977 // the class table grew then the loop repeats. If classes are created after the loop has
1978 // finished then we don't visit.
1979 mirror::Class* klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001980 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001981 return;
1982 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001983 }
1984 }
1985}
1986
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001987ClassLinker::~ClassLinker() {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001988 mirror::Class::ResetClass();
1989 mirror::Constructor::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001990 mirror::Field::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001991 mirror::Method::ResetClass();
1992 mirror::Reference::ResetClass();
1993 mirror::StackTraceElement::ResetClass();
1994 mirror::String::ResetClass();
1995 mirror::Throwable::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001996 mirror::BooleanArray::ResetArrayClass();
1997 mirror::ByteArray::ResetArrayClass();
1998 mirror::CharArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001999 mirror::Constructor::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002000 mirror::DoubleArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002001 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002002 mirror::FloatArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002003 mirror::Method::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002004 mirror::IntArray::ResetArrayClass();
2005 mirror::LongArray::ResetArrayClass();
2006 mirror::ShortArray::ResetArrayClass();
Narayan Kamathafa48272016-08-03 12:46:58 +01002007 mirror::MethodType::ResetClass();
2008 mirror::MethodHandleImpl::ResetClass();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002009 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002010 for (const ClassLoaderData& data : class_loaders_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002011 DeleteClassLoader(self, data);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002012 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002013 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002014}
2015
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002016void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data) {
2017 Runtime* const runtime = Runtime::Current();
2018 JavaVMExt* const vm = runtime->GetJavaVM();
2019 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002020 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002021 if (runtime->GetJit() != nullptr) {
2022 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2023 if (code_cache != nullptr) {
2024 code_cache->RemoveMethodsIn(self, *data.allocator);
2025 }
2026 }
2027 delete data.allocator;
2028 delete data.class_table;
2029}
2030
Mathieu Chartiere401d142015-04-22 13:56:20 -07002031mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) {
Andreas Gampe542451c2016-07-26 09:02:02 -07002032 return down_cast<mirror::PointerArray*>(
2033 image_pointer_size_ == PointerSize::k64
2034 ? static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length))
2035 : static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002036}
2037
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002038void ClassLinker::InitializeDexCache(Thread* self,
2039 mirror::DexCache* dex_cache,
2040 mirror::String* location,
2041 const DexFile& dex_file,
2042 LinearAlloc* linear_alloc) {
2043 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Marko05792b92015-08-03 11:56:49 +01002044 DexCacheArraysLayout layout(image_pointer_size_, &dex_file);
2045 uint8_t* raw_arrays = nullptr;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002046
2047 const OatDexFile* const oat_dex = dex_file.GetOatDexFile();
2048 if (oat_dex != nullptr && oat_dex->GetDexCacheArrays() != nullptr) {
2049 raw_arrays = oat_dex->GetDexCacheArrays();
2050 } else if (dex_file.NumStringIds() != 0u ||
2051 dex_file.NumTypeIds() != 0u ||
2052 dex_file.NumMethodIds() != 0u ||
2053 dex_file.NumFieldIds() != 0u) {
Mathieu Chartier32cc9ee2015-10-15 09:19:15 -07002054 // Zero-initialized.
2055 raw_arrays = reinterpret_cast<uint8_t*>(linear_alloc->Alloc(self, layout.Size()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002056 }
Narayan Kamath25352fc2016-08-03 12:46:58 +01002057
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002058 mirror::StringDexCacheType* strings = (dex_file.NumStringIds() == 0u) ? nullptr :
2059 reinterpret_cast<mirror::StringDexCacheType*>(raw_arrays + layout.StringsOffset());
Vladimir Marko05792b92015-08-03 11:56:49 +01002060 GcRoot<mirror::Class>* types = (dex_file.NumTypeIds() == 0u) ? nullptr :
2061 reinterpret_cast<GcRoot<mirror::Class>*>(raw_arrays + layout.TypesOffset());
2062 ArtMethod** methods = (dex_file.NumMethodIds() == 0u) ? nullptr :
2063 reinterpret_cast<ArtMethod**>(raw_arrays + layout.MethodsOffset());
2064 ArtField** fields = (dex_file.NumFieldIds() == 0u) ? nullptr :
2065 reinterpret_cast<ArtField**>(raw_arrays + layout.FieldsOffset());
Narayan Kamath25352fc2016-08-03 12:46:58 +01002066
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002067 size_t num_strings = mirror::DexCache::kDexCacheStringCacheSize;
2068 if (dex_file.NumStringIds() < num_strings) {
2069 num_strings = dex_file.NumStringIds();
2070 }
Narayan Kamath25352fc2016-08-03 12:46:58 +01002071
2072 // Note that we allocate the method type dex caches regardless of this flag,
2073 // and we make sure here that they're not used by the runtime. This is in the
2074 // interest of simplicity and to avoid extensive compiler and layout class changes.
2075 //
2076 // If this needs to be mitigated in a production system running this code,
2077 // DexCache::kDexCacheMethodTypeCacheSize can be set to zero.
2078 const bool is_method_handles_enabled = Runtime::Current()->IsMethodHandlesEnabled();
2079 mirror::MethodTypeDexCacheType* method_types = nullptr;
2080 size_t num_method_types = 0;
2081
2082 if (is_method_handles_enabled) {
2083 if (dex_file.NumProtoIds() < mirror::DexCache::kDexCacheMethodTypeCacheSize) {
2084 num_method_types = dex_file.NumProtoIds();
2085 } else {
2086 num_method_types = mirror::DexCache::kDexCacheMethodTypeCacheSize;
2087 }
2088
2089 if (num_method_types > 0) {
2090 method_types = reinterpret_cast<mirror::MethodTypeDexCacheType*>(
2091 raw_arrays + layout.MethodTypesOffset());
2092 }
2093 }
2094
Christina Wadsworth6353a632016-08-19 15:58:05 -07002095 DCHECK_ALIGNED(raw_arrays, alignof(mirror::StringDexCacheType)) <<
2096 "Expected raw_arrays to align to StringDexCacheType.";
2097 DCHECK_ALIGNED(layout.StringsOffset(), alignof(mirror::StringDexCacheType)) <<
2098 "Expected StringsOffset() to align to StringDexCacheType.";
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002099 DCHECK_ALIGNED(strings, alignof(mirror::StringDexCacheType)) <<
Christina Wadsworth6353a632016-08-19 15:58:05 -07002100 "Expected strings to align to StringDexCacheType.";
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002101 static_assert(alignof(mirror::StringDexCacheType) == 8u,
2102 "Expected StringDexCacheType to have align of 8.");
Mathieu Chartier05005f72016-06-06 13:10:50 -07002103 if (kIsDebugBuild) {
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -07002104 // Sanity check to make sure all the dex cache arrays are empty. b/28992179
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002105 for (size_t i = 0; i < num_strings; ++i) {
Narayan Kamathc38a6f82016-09-29 17:07:20 +01002106 CHECK_EQ(strings[i].load(std::memory_order_relaxed).index, 0u);
2107 CHECK(strings[i].load(std::memory_order_relaxed).object.IsNull());
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -07002108 }
2109 for (size_t i = 0; i < dex_file.NumTypeIds(); ++i) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002110 CHECK(types[i].IsNull());
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -07002111 }
2112 for (size_t i = 0; i < dex_file.NumMethodIds(); ++i) {
2113 CHECK(mirror::DexCache::GetElementPtrSize(methods, i, image_pointer_size_) == nullptr);
2114 }
2115 for (size_t i = 0; i < dex_file.NumFieldIds(); ++i) {
2116 CHECK(mirror::DexCache::GetElementPtrSize(fields, i, image_pointer_size_) == nullptr);
2117 }
Narayan Kamath25352fc2016-08-03 12:46:58 +01002118 for (size_t i = 0; i < num_method_types; ++i) {
2119 CHECK_EQ(method_types[i].load(std::memory_order_relaxed).index, 0u);
2120 CHECK(method_types[i].load(std::memory_order_relaxed).object.IsNull());
2121 }
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -07002122 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002123 if (strings != nullptr) {
2124 mirror::StringDexCachePair::Initialize(strings);
2125 }
Narayan Kamath25352fc2016-08-03 12:46:58 +01002126 if (method_types != nullptr) {
2127 mirror::MethodTypeDexCachePair::Initialize(method_types);
2128 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002129 dex_cache->Init(&dex_file,
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002130 location,
Vladimir Marko05792b92015-08-03 11:56:49 +01002131 strings,
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002132 num_strings,
Vladimir Marko05792b92015-08-03 11:56:49 +01002133 types,
2134 dex_file.NumTypeIds(),
2135 methods,
2136 dex_file.NumMethodIds(),
2137 fields,
2138 dex_file.NumFieldIds(),
Narayan Kamath25352fc2016-08-03 12:46:58 +01002139 method_types,
2140 num_method_types,
Vladimir Marko05792b92015-08-03 11:56:49 +01002141 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002142}
2143
2144mirror::DexCache* ClassLinker::AllocDexCache(mirror::String** out_location,
2145 Thread* self,
2146 const DexFile& dex_file) {
2147 StackHandleScope<1> hs(self);
2148 DCHECK(out_location != nullptr);
2149 auto dex_cache(hs.NewHandle(down_cast<mirror::DexCache*>(
2150 GetClassRoot(kJavaLangDexCache)->AllocObject(self))));
2151 if (dex_cache.Get() == nullptr) {
2152 self->AssertPendingOOMException();
2153 return nullptr;
2154 }
2155 mirror::String* location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
2156 if (location == nullptr) {
2157 self->AssertPendingOOMException();
2158 return nullptr;
2159 }
2160 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002161 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002162}
2163
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002164mirror::DexCache* ClassLinker::AllocAndInitializeDexCache(Thread* self,
2165 const DexFile& dex_file,
2166 LinearAlloc* linear_alloc) {
2167 mirror::String* location = nullptr;
2168 mirror::DexCache* dex_cache = AllocDexCache(&location, self, dex_file);
2169 if (dex_cache != nullptr) {
2170 WriterMutexLock mu(self, dex_lock_);
2171 DCHECK(location != nullptr);
2172 InitializeDexCache(self, dex_cache, location, dex_file, linear_alloc);
2173 }
2174 return dex_cache;
2175}
2176
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002177mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08002178 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002179 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002180 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002181 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002182 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002183 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2184 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002185 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002186 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002187 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002188 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002189 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002190}
2191
Ian Rogers6fac4472014-02-25 17:01:10 -08002192mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002193 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002194}
2195
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002196mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002197 Thread* self,
2198 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002199 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2200 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002201}
2202
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002203mirror::Class* ClassLinker::EnsureResolved(Thread* self,
2204 const char* descriptor,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002205 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002206 DCHECK(klass != nullptr);
Mathieu Chartier0795f232016-09-27 18:43:30 -07002207 Thread::PoisonObjectPointersIfDebug();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002208
2209 // For temporary classes we must wait for them to be retired.
2210 if (init_done_ && klass->IsTemp()) {
2211 CHECK(!klass->IsResolved());
2212 if (klass->IsErroneous()) {
2213 ThrowEarlierClassFailure(klass);
2214 return nullptr;
2215 }
2216 StackHandleScope<1> hs(self);
2217 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2218 ObjectLock<mirror::Class> lock(self, h_class);
2219 // Loop and wait for the resolving thread to retire this class.
2220 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2221 lock.WaitIgnoringInterrupts();
2222 }
2223 if (h_class->IsErroneous()) {
2224 ThrowEarlierClassFailure(h_class.Get());
2225 return nullptr;
2226 }
2227 CHECK(h_class->IsRetired());
2228 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002229 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2230 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002231 }
2232
Brian Carlstromaded5f72011-10-07 17:15:04 -07002233 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002234 size_t index = 0;
2235 // Maximum number of yield iterations until we start sleeping.
2236 static const size_t kNumYieldIterations = 1000;
2237 // How long each sleep is in us.
2238 static const size_t kSleepDurationUS = 1000; // 1 ms.
2239 while (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002240 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002241 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002242 {
2243 ObjectTryLock<mirror::Class> lock(self, h_class);
2244 // Can not use a monitor wait here since it may block when returning and deadlock if another
2245 // thread has locked klass.
2246 if (lock.Acquired()) {
2247 // Check for circular dependencies between classes, the lock is required for SetStatus.
2248 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2249 ThrowClassCircularityError(h_class.Get());
2250 mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self);
2251 return nullptr;
2252 }
2253 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002254 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002255 {
2256 // Handle wrapper deals with klass moving.
2257 ScopedThreadSuspension sts(self, kSuspended);
2258 if (index < kNumYieldIterations) {
2259 sched_yield();
2260 } else {
2261 usleep(kSleepDurationUS);
2262 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002263 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002264 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002265 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002266
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002267 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002268 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002269 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002270 }
2271 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002272 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002273 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002274 return klass;
2275}
2276
Ian Rogers68b56852014-08-29 20:19:11 -07002277typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2278
2279// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002280ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002281 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002282 for (const DexFile* dex_file : class_path) {
David Sehr9aa352e2016-09-15 18:13:52 -07002283 const DexFile::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002284 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002285 return ClassPathEntry(dex_file, dex_class_def);
2286 }
2287 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002288 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002289}
2290
Andreas Gampef865ea92015-04-13 22:14:19 -07002291bool ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002292 Thread* self,
2293 const char* descriptor,
Andreas Gampef865ea92015-04-13 22:14:19 -07002294 size_t hash,
2295 Handle<mirror::ClassLoader> class_loader,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002296 mirror::Class** result) {
Andreas Gampef865ea92015-04-13 22:14:19 -07002297 // Termination case: boot class-loader.
2298 if (IsBootClassLoader(soa, class_loader.Get())) {
2299 // The boot class loader, search the boot class path.
2300 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2301 if (pair.second != nullptr) {
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002302 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Andreas Gampef865ea92015-04-13 22:14:19 -07002303 if (klass != nullptr) {
2304 *result = EnsureResolved(self, descriptor, klass);
2305 } else {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002306 *result = DefineClass(self,
2307 descriptor,
2308 hash,
2309 ScopedNullHandle<mirror::ClassLoader>(),
2310 *pair.first,
2311 *pair.second);
Andreas Gampef865ea92015-04-13 22:14:19 -07002312 }
2313 if (*result == nullptr) {
2314 CHECK(self->IsExceptionPending()) << descriptor;
2315 self->ClearException();
2316 }
Ian Rogers32427292014-11-19 14:05:21 -08002317 } else {
Andreas Gampef865ea92015-04-13 22:14:19 -07002318 *result = nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002319 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002320 return true;
2321 }
2322
2323 // Unsupported class-loader?
Mathieu Chartier0795f232016-09-27 18:43:30 -07002324 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
2325 class_loader->GetClass()) {
Andreas Gampef865ea92015-04-13 22:14:19 -07002326 *result = nullptr;
2327 return false;
2328 }
2329
2330 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2331 StackHandleScope<4> hs(self);
2332 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2333 bool recursive_result = FindClassInPathClassLoader(soa, self, descriptor, hash, h_parent, result);
2334
2335 if (!recursive_result) {
2336 // Something wrong up the chain.
2337 return false;
2338 }
2339
2340 if (*result != nullptr) {
2341 // Found the class up the chain.
2342 return true;
2343 }
2344
2345 // Handle this step.
2346 // Handle as if this is the child PathClassLoader.
2347 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2348 // We need to get the DexPathList and loop through it.
2349 ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
2350 ArtField* const dex_file_field =
2351 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartier3398c782016-09-30 10:27:43 -07002352 ObjPtr<mirror::Object> dex_path_list =
Andreas Gampef865ea92015-04-13 22:14:19 -07002353 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2354 GetObject(class_loader.Get());
2355 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
2356 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002357 ObjPtr<mirror::Object> dex_elements_obj =
Andreas Gampef865ea92015-04-13 22:14:19 -07002358 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2359 GetObject(dex_path_list);
2360 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2361 // at the mCookie which is a DexFile vector.
2362 if (dex_elements_obj != nullptr) {
2363 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2364 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2365 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002366 ObjPtr<mirror::Object> element = dex_elements->GetWithoutChecks(i);
Andreas Gampef865ea92015-04-13 22:14:19 -07002367 if (element == nullptr) {
2368 // Should never happen, fall back to java code to throw a NPE.
2369 break;
2370 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07002371 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Andreas Gampef865ea92015-04-13 22:14:19 -07002372 if (dex_file != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07002373 ObjPtr<mirror::LongArray> long_array = cookie_field->GetObject(dex_file)->AsLongArray();
Andreas Gampef865ea92015-04-13 22:14:19 -07002374 if (long_array == nullptr) {
2375 // This should never happen so log a warning.
2376 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002377 break;
2378 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002379 int32_t long_array_size = long_array->GetLength();
Mathieu Chartiere58991b2015-10-13 07:59:34 -07002380 // First element is the oat file.
2381 for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) {
Andreas Gampef865ea92015-04-13 22:14:19 -07002382 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
2383 long_array->GetWithoutChecks(j)));
David Sehr9aa352e2016-09-15 18:13:52 -07002384 const DexFile::ClassDef* dex_class_def =
2385 OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002386 if (dex_class_def != nullptr) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -07002387 mirror::Class* klass = DefineClass(self,
2388 descriptor,
2389 hash,
2390 class_loader,
2391 *cp_dex_file,
2392 *dex_class_def);
Andreas Gampef865ea92015-04-13 22:14:19 -07002393 if (klass == nullptr) {
2394 CHECK(self->IsExceptionPending()) << descriptor;
2395 self->ClearException();
2396 // TODO: Is it really right to break here, and not check the other dex files?
2397 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002398 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002399 *result = klass;
2400 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002401 }
2402 }
2403 }
2404 }
2405 }
Ian Rogers32427292014-11-19 14:05:21 -08002406 self->AssertNoPendingException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002407 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002408
2409 // Result is still null from the parent call, no need to set it again...
2410 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002411}
2412
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002413mirror::Class* ClassLinker::FindClass(Thread* self,
2414 const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002415 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002416 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002417 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002418 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002419 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002420 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002421 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2422 // for primitive classes that aren't backed by dex files.
2423 return FindPrimitiveClass(descriptor[0]);
2424 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002425 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002426 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002427 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002428 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002429 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002430 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002431 // Class is not yet loaded.
2432 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002433 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002434 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002435 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002436 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002437 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002438 return DefineClass(self,
2439 descriptor,
2440 hash,
2441 ScopedNullHandle<mirror::ClassLoader>(),
2442 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002443 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002444 } else {
2445 // The boot class loader is searched ahead of the application class loader, failures are
2446 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2447 // trigger the chaining with a proper stack trace.
2448 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002449 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002450 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002451 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002452 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002453 ScopedObjectAccessUnchecked soa(self);
Andreas Gampef865ea92015-04-13 22:14:19 -07002454 mirror::Class* cp_klass;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002455 if (FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader, &cp_klass)) {
Andreas Gampef865ea92015-04-13 22:14:19 -07002456 // The chain was understood. So the value in cp_klass is either the class we were looking
2457 // for, or not found.
2458 if (cp_klass != nullptr) {
2459 return cp_klass;
2460 }
2461 // TODO: We handle the boot classpath loader in FindClassInPathClassLoader. Try to unify this
2462 // and the branch above. TODO: throw the right exception here.
2463
2464 // We'll let the Java-side rediscover all this and throw the exception with the right stack
2465 // trace.
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002466 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002467
2468 if (Runtime::Current()->IsAotCompiler()) {
2469 // Oops, compile-time, can't run actual class-loader code.
2470 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2471 self->SetException(pre_allocated);
2472 return nullptr;
2473 }
2474
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002475 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002476 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002477 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002478 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002479 {
2480 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002481 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2482 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002483 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002484 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002485 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002486 }
Ian Rogers68b56852014-08-29 20:19:11 -07002487 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002488 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2489 WellKnownClasses::java_lang_ClassLoader_loadClass,
2490 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002491 }
Ian Rogers98379392014-02-24 16:53:16 -08002492 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002493 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002494 return nullptr;
2495 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002496 // broken loader - throw NPE to be compatible with Dalvik
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00002497 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2498 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002499 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002500 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002501 // success, return mirror::Class*
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07002502 return soa.Decode<mirror::Class>(result.get()).Ptr();
Ian Rogers6b0870d2011-12-15 19:38:12 -08002503 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002504 }
Ian Rogers07140832014-09-30 15:43:59 -07002505 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002506}
2507
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002508mirror::Class* ClassLinker::DefineClass(Thread* self,
2509 const char* descriptor,
2510 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002511 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002512 const DexFile& dex_file,
2513 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002514 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002515 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002516
Brian Carlstromaded5f72011-10-07 17:15:04 -07002517 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002518 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002519 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002520 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002521 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002522 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002523 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002524 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002525 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002526 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2527 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002528 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002529 klass.Assign(GetClassRoot(kJavaLangDexCache));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002530 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002531 }
2532
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002533 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002534 // Allocate a class with the status of not ready.
2535 // Interface object should get the right size here. Regular class will
2536 // figure out the right size later and be replaced with one of the right
2537 // size when the class becomes resolved.
2538 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002539 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002540 if (UNLIKELY(klass.Get() == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002541 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07002542 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002543 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07002544 mirror::DexCache* dex_cache = RegisterDexFile(dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002545 if (dex_cache == nullptr) {
2546 self->AssertPendingOOMException();
2547 return nullptr;
2548 }
2549 klass->SetDexCache(dex_cache);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002550 SetupClass(dex_file, dex_class_def, klass, class_loader.Get());
2551
Jeff Hao848f70a2014-01-15 13:49:50 -08002552 // Mark the string class by setting its access flag.
2553 if (UNLIKELY(!init_done_)) {
2554 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2555 klass->SetStringClass();
2556 }
2557 }
2558
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002559 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002560 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002561
Mathieu Chartier590fee92013-09-13 13:46:47 -07002562 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002563 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002564 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002565 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2566 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002567 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002568 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002569
Mathieu Chartierc7853442015-03-27 14:35:38 -07002570 // Load the fields and other things after we are inserted in the table. This is so that we don't
2571 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
2572 // other reason is that the field roots are only visited from the class table. So we need to be
2573 // inserted before we allocate / fill in these fields.
2574 LoadClass(self, dex_file, dex_class_def, klass);
2575 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002576 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07002577 // An exception occured during load, set status to erroneous while holding klass' lock in case
2578 // notification is necessary.
2579 if (!klass->IsErroneous()) {
2580 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
2581 }
2582 return nullptr;
2583 }
2584
Brian Carlstromaded5f72011-10-07 17:15:04 -07002585 // Finish loading (if necessary) by finding parents
2586 CHECK(!klass->IsLoaded());
2587 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2588 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002589 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002590 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002591 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002592 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002593 }
2594 CHECK(klass->IsLoaded());
2595 // Link the class (if necessary)
2596 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002597 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002598 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002599
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002600 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002601 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002602 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002603 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002604 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002605 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002606 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002607 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002608 self->AssertNoPendingException();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002609 CHECK(h_new_class.Get() != nullptr) << descriptor;
2610 CHECK(h_new_class->IsResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002611
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +01002612 // Update the dex cache of where the class is defined. Inlining depends on having
2613 // this filled.
2614 h_new_class->GetDexCache()->SetResolvedType(h_new_class->GetDexTypeIndex(), h_new_class.Get());
2615
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002616 // Instrumentation may have updated entrypoints for all methods of all
2617 // classes. However it could not update methods of this class while we
2618 // were loading it. Now the class is resolved, we can update entrypoints
2619 // as required by instrumentation.
2620 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2621 // We must be in the kRunnable state to prevent instrumentation from
2622 // suspending all threads to update entrypoints while we are doing it
2623 // for this class.
2624 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002625 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002626 }
2627
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002628 /*
2629 * We send CLASS_PREPARE events to the debugger from here. The
2630 * definition of "preparation" is creating the static fields for a
2631 * class and initializing them to the standard default values, but not
2632 * executing any code (that comes later, during "initialization").
2633 *
2634 * We did the static preparation in LinkClass.
2635 *
2636 * The class has been prepared and resolved but possibly not yet verified
2637 * at this point.
2638 */
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002639 Dbg::PostClassPrepare(h_new_class.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002640
Tamas Berghammer160e6df2016-01-05 14:29:02 +00002641 // Notify native debugger of the new class and its layout.
2642 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
2643
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07002644 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002645}
2646
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002647uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2648 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002649 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002650 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002651 size_t num_8 = 0;
2652 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002653 size_t num_32 = 0;
2654 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002655 if (class_data != nullptr) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002656 // We allow duplicate definitions of the same field in a class_data_item
2657 // but ignore the repeated indexes here, b/21868015.
2658 uint32_t last_field_idx = DexFile::kDexNoIndex;
Ian Rogers0571d352011-11-03 19:51:38 -07002659 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
Vladimir Marko879d27b2016-03-15 20:31:50 +00002660 uint32_t field_idx = it.GetMemberIndex();
2661 // Ordering enforced by DexFileVerifier.
2662 DCHECK(last_field_idx == DexFile::kDexNoIndex || last_field_idx <= field_idx);
2663 if (UNLIKELY(field_idx == last_field_idx)) {
2664 continue;
2665 }
2666 last_field_idx = field_idx;
2667 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002668 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002669 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002670 switch (c) {
2671 case 'L':
2672 case '[':
2673 num_ref++;
2674 break;
2675 case 'J':
2676 case 'D':
2677 num_64++;
2678 break;
2679 case 'I':
2680 case 'F':
2681 num_32++;
2682 break;
2683 case 'S':
2684 case 'C':
2685 num_16++;
2686 break;
2687 case 'B':
2688 case 'Z':
2689 num_8++;
2690 break;
2691 default:
2692 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002693 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002694 }
2695 }
2696 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002697 return mirror::Class::ComputeClassSize(false,
2698 0,
2699 num_8,
2700 num_16,
2701 num_32,
2702 num_64,
2703 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07002704 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002705}
2706
TDYa12785321912012-04-01 15:24:56 -07002707// Special case to get oat code without overwriting a trampoline.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002708const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07002709 CHECK(method->IsInvokable()) << PrettyMethod(method);
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00002710 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002711 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002712 }
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002713 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
2714 if (code != nullptr) {
2715 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08002716 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002717 if (method->IsNative()) {
2718 // No code and native? Use generic trampoline.
2719 return GetQuickGenericJniStub();
2720 }
2721 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07002722}
2723
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002724bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
2725 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
2726 return false;
2727 }
2728
Elliott Hughes956af0f2014-12-11 14:34:28 -08002729 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002730 return true;
2731 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002732
2733 Runtime* runtime = Runtime::Current();
2734 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
2735 if (instr->InterpretOnly()) {
2736 return true;
2737 }
2738
2739 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
2740 // Doing this check avoids doing compiled/interpreter transitions.
2741 return true;
2742 }
2743
2744 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
2745 // Force the use of interpreter when it is required by the debugger.
2746 return true;
2747 }
2748
David Srbeckyf4480162016-03-16 00:06:24 +00002749 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01002750 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00002751 // If we are doing native debugging, ignore application's AOT code,
2752 // since we want to JIT it with extra stackmaps for native debugging.
2753 // On the other hand, keep all AOT code from the boot image, since the
2754 // blocking JIT would results in non-negligible performance impact.
2755 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002756 }
2757
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -08002758 if (Dbg::IsDebuggerActive()) {
David Srbeckyf4480162016-03-16 00:06:24 +00002759 // Boot image classes may be AOT-compiled as non-debuggable.
2760 // This is not suitable for the Java debugger, so ignore the AOT code.
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -08002761 return runtime->GetHeap()->IsInBootImageOatFile(quick_code);
2762 }
2763
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002764 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002765}
2766
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002767void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002768 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002769 if (klass->NumDirectMethods() == 0) {
2770 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002771 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002772 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002773 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002774 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002775 return; // OAT file unavailable.
2776 }
Ian Rogers19846512012-02-24 11:42:47 -08002777 }
Alex Light64ad14d2014-08-19 14:23:13 -07002778
Mathieu Chartierf8322842014-05-16 10:59:25 -07002779 const DexFile& dex_file = klass->GetDexFile();
2780 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002781 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002782 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002783 // There should always be class data if there were direct methods.
2784 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002785 ClassDataItemIterator it(dex_file, class_data);
2786 // Skip fields
2787 while (it.HasNextStaticField()) {
2788 it.Next();
2789 }
2790 while (it.HasNextInstanceField()) {
2791 it.Next();
2792 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002793 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002794 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
2795 klass->GetDexClassDefIndex(),
2796 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002797 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002798 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002799 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002800 if (!method->IsStatic()) {
2801 // Only update static methods.
2802 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002803 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002804 const void* quick_code = nullptr;
2805 if (has_oat_class) {
2806 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002807 quick_code = oat_method.GetQuickCode();
2808 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002809 // Check whether the method is native, in which case it's generic JNI.
2810 if (quick_code == nullptr && method->IsNative()) {
2811 quick_code = GetQuickGenericJniStub();
2812 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002813 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002814 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002815 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002816 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08002817 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002818 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002819}
2820
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002821// Does anything needed to make sure that the compiler will not generate a direct invoke to this
2822// method. Should only be called on non-invokable methods.
2823inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07002824 DCHECK(method != nullptr);
2825 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002826 method->SetEntryPointFromQuickCompiledCodePtrSize(
2827 class_linker->GetQuickToInterpreterBridgeTrampoline(),
2828 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07002829}
2830
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002831static void LinkCode(ClassLinker* class_linker,
2832 ArtMethod* method,
2833 const OatFile::OatClass* oat_class,
2834 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002835 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002836 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002837 // The following code only applies to a non-compiler runtime.
2838 return;
2839 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002840 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002841 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002842 if (oat_class != nullptr) {
2843 // Every kind of method should at least get an invoke stub from the oat_method.
2844 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002845 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002846 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002847 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002848
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00002849 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002850 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002851 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07002852
Alex Light9139e002015-10-09 15:59:48 -07002853 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002854 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002855 return;
2856 }
Ian Rogers19846512012-02-24 11:42:47 -08002857
2858 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002859 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002860 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2861 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002862 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002863 } else if (quick_code == nullptr && method->IsNative()) {
2864 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00002865 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002866 // Set entry point from compiled code if there's no code or in interpreter only mode.
2867 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002868 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002869
Ian Rogers62d6c772013-02-27 08:32:07 -08002870 if (method->IsNative()) {
2871 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002872 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002873
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00002874 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002875 // We have a native method here without code. Then it should have either the generic JNI
2876 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2877 // TODO: this doesn't handle all the cases where trampolines may be installed.
2878 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002879 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
2880 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002881 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002882 }
2883}
2884
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002885void ClassLinker::SetupClass(const DexFile& dex_file,
2886 const DexFile::ClassDef& dex_class_def,
2887 Handle<mirror::Class> klass,
2888 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002889 CHECK(klass.Get() != nullptr);
2890 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002891 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002892 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002893 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002894
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002895 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07002896 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002897 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002898 klass->SetAccessFlags(access_flags);
2899 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002900 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002901 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002902
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002903 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002904 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002905 CHECK(klass->GetDexCacheStrings() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002906}
Brian Carlstrom934486c2011-07-12 23:42:50 -07002907
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002908void ClassLinker::LoadClass(Thread* self,
2909 const DexFile& dex_file,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002910 const DexFile::ClassDef& dex_class_def,
2911 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07002912 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002913 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002914 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002915 }
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002916 LoadClassMembers(self, dex_file, class_data, klass);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002917}
2918
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002919LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
2920 LinearAlloc* allocator,
2921 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002922 if (length == 0) {
2923 return nullptr;
2924 }
Vladimir Markocf36d492015-08-12 19:27:26 +01002925 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
2926 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
2927 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002928 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01002929 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002930 CHECK(ret != nullptr);
2931 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
2932 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002933}
2934
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002935LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
2936 LinearAlloc* allocator,
2937 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002938 if (length == 0) {
2939 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002940 }
Vladimir Marko14632852015-08-17 12:07:23 +01002941 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
2942 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01002943 const size_t storage_size =
2944 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002945 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01002946 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002947 CHECK(ret != nullptr);
2948 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01002949 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002950 }
2951 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002952}
2953
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002954LinearAlloc* ClassLinker::GetAllocatorForClassLoader(mirror::ClassLoader* class_loader) {
2955 if (class_loader == nullptr) {
2956 return Runtime::Current()->GetLinearAlloc();
2957 }
2958 LinearAlloc* allocator = class_loader->GetAllocator();
2959 DCHECK(allocator != nullptr);
2960 return allocator;
2961}
2962
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002963LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(mirror::ClassLoader* class_loader) {
2964 if (class_loader == nullptr) {
2965 return Runtime::Current()->GetLinearAlloc();
2966 }
2967 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2968 LinearAlloc* allocator = class_loader->GetAllocator();
2969 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08002970 RegisterClassLoader(class_loader);
2971 allocator = class_loader->GetAllocator();
2972 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002973 }
2974 return allocator;
2975}
2976
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002977void ClassLinker::LoadClassMembers(Thread* self,
2978 const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002979 const uint8_t* class_data,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002980 Handle<mirror::Class> klass) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002981 {
2982 // Note: We cannot have thread suspension until the field and method arrays are setup or else
2983 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07002984 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002985 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01002986 // We allow duplicate definitions of the same field in a class_data_item
2987 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002988 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002989 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002990 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
2991 allocator,
2992 it.NumStaticFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01002993 size_t num_sfields = 0;
2994 uint32_t last_field_idx = 0u;
2995 for (; it.HasNextStaticField(); it.Next()) {
2996 uint32_t field_idx = it.GetMemberIndex();
2997 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
2998 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
2999 DCHECK_LT(num_sfields, it.NumStaticFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003000 LoadField(it, klass, &sfields->At(num_sfields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003001 ++num_sfields;
3002 last_field_idx = field_idx;
3003 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003004 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003005 // Load instance fields.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003006 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3007 allocator,
3008 it.NumInstanceFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01003009 size_t num_ifields = 0u;
3010 last_field_idx = 0u;
3011 for (; it.HasNextInstanceField(); it.Next()) {
3012 uint32_t field_idx = it.GetMemberIndex();
3013 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3014 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
3015 DCHECK_LT(num_ifields, it.NumInstanceFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003016 LoadField(it, klass, &ifields->At(num_ifields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01003017 ++num_ifields;
3018 last_field_idx = field_idx;
3019 }
3020 }
3021 if (UNLIKELY(num_sfields != it.NumStaticFields()) ||
3022 UNLIKELY(num_ifields != it.NumInstanceFields())) {
3023 LOG(WARNING) << "Duplicate fields in class " << PrettyDescriptor(klass.Get())
3024 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields()
3025 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003026 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3027 if (sfields != nullptr) {
3028 sfields->SetSize(num_sfields);
3029 }
3030 if (ifields != nullptr) {
3031 ifields->SetSize(num_ifields);
3032 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003033 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003034 // Set the field arrays.
3035 klass->SetSFieldsPtr(sfields);
3036 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003037 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003038 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
3039 // Load methods.
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003040 bool has_oat_class = false;
3041 const OatFile::OatClass oat_class =
3042 (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler())
3043 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3044 : OatFile::OatClass::Invalid();
3045 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
Alex Lighte64300b2015-12-15 15:02:47 -08003046 klass->SetMethodsPtr(
3047 AllocArtMethodArray(self, allocator, it.NumDirectMethods() + it.NumVirtualMethods()),
3048 it.NumDirectMethods(),
3049 it.NumVirtualMethods());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003050 size_t class_def_method_index = 0;
3051 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
3052 size_t last_class_def_method_index = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08003053 // TODO These should really use the iterators.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003054 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
3055 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003056 LoadMethod(dex_file, it, klass, method);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003057 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003058 uint32_t it_method_index = it.GetMemberIndex();
3059 if (last_dex_method_index == it_method_index) {
3060 // duplicate case
3061 method->SetMethodIndex(last_class_def_method_index);
3062 } else {
3063 method->SetMethodIndex(class_def_method_index);
3064 last_dex_method_index = it_method_index;
3065 last_class_def_method_index = class_def_method_index;
3066 }
3067 class_def_method_index++;
3068 }
3069 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
3070 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartier268764d2016-09-13 12:09:38 -07003071 LoadMethod(dex_file, it, klass, method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003072 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003073 LinkCode(this, method, oat_class_ptr, class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003074 class_def_method_index++;
3075 }
3076 DCHECK(!it.HasNext());
Ian Rogers0571d352011-11-03 19:51:38 -07003077 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003078 // Ensure that the card is marked so that remembered sets pick up native roots.
3079 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003080 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003081}
3082
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003083void ClassLinker::LoadField(const ClassDataItemIterator& it,
3084 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003085 ArtField* dst) {
3086 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003087 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003088 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07003089 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003090}
3091
Mathieu Chartier268764d2016-09-13 12:09:38 -07003092void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003093 const ClassDataItemIterator& it,
3094 Handle<mirror::Class> klass,
3095 ArtMethod* dst) {
Ian Rogers19846512012-02-24 11:42:47 -08003096 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08003097 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003098 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003099
Mathieu Chartier268764d2016-09-13 12:09:38 -07003100 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003101 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003102 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07003103 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003104
Vladimir Marko05792b92015-08-03 11:56:49 +01003105 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods(), image_pointer_size_);
3106 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes(), image_pointer_size_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003107
Andreas Gampe51829322014-08-25 15:05:04 -07003108 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07003109
Ian Rogersdfb325e2013-10-30 01:00:44 -07003110 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003111 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003112 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3113 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003114 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003115 klass->SetFinalizable();
3116 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003117 std::string temp;
3118 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003119 // The Enum class declares a "final" finalize() method to prevent subclasses from
3120 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3121 // subclasses, so we exclude it here.
3122 // We also want to avoid setting the flag on Object, where we know that finalize() is
3123 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003124 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3125 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003126 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003127 }
3128 }
3129 }
3130 } else if (method_name[0] == '<') {
3131 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003132 bool is_init = (strcmp("<init>", method_name) == 0);
3133 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003134 if (UNLIKELY(!is_init && !is_clinit)) {
3135 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3136 } else {
3137 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3138 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003139 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003140 access_flags |= kAccConstructor;
3141 }
3142 }
3143 }
3144 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003145}
3146
Ian Rogers7b078e82014-09-10 14:44:24 -07003147void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003148 StackHandleScope<1> hs(self);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003149 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003150 self,
3151 dex_file,
3152 Runtime::Current()->GetLinearAlloc())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003153 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3154 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003155 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003156}
3157
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003158void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003159 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003160 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003161 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003162 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003163}
3164
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003165void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003166 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003167 Thread* const self = Thread::Current();
3168 dex_lock_.AssertExclusiveHeld(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003169 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003170 // For app images, the dex cache location may be a suffix of the dex file location since the
3171 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003172 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3173 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003174 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3175 std::string dex_file_location = dex_file.GetLocation();
3176 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003177 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003178 // Take suffix.
3179 const std::string dex_file_suffix = dex_file_location.substr(
3180 dex_file_location.length() - dex_cache_length,
3181 dex_cache_length);
3182 // Example dex_cache location is SettingsProvider.apk and
3183 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003184 CHECK_EQ(dex_cache_location, dex_file_suffix);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003185 // Clean up pass to remove null dex caches.
3186 // Null dex caches can occur due to class unloading and we are lazily removing null entries.
3187 JavaVMExt* const vm = self->GetJniEnv()->vm;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003188 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3189 DexCacheData data = *it;
3190 if (self->IsJWeakCleared(data.weak_root)) {
3191 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003192 it = dex_caches_.erase(it);
3193 } else {
3194 ++it;
3195 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003196 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003197 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003198 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003199 DexCacheData data;
3200 data.weak_root = dex_cache_jweak;
3201 data.dex_file = dex_cache->GetDexFile();
3202 data.resolved_types = dex_cache->GetResolvedTypes();
3203 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003204}
3205
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003206mirror::DexCache* ClassLinker::RegisterDexFile(const DexFile& dex_file,
3207 mirror::ClassLoader* class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003208 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003209 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003210 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003211 mirror::DexCache* dex_cache = FindDexCacheLocked(self, dex_file, true);
3212 if (dex_cache != nullptr) {
3213 return dex_cache;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003214 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003215 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003216 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3217 DCHECK(linear_alloc != nullptr);
3218 ClassTable* table;
3219 {
3220 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3221 table = InsertClassTableForClassLoader(class_loader);
3222 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003223 // Don't alloc while holding the lock, since allocation may need to
3224 // suspend all threads and another thread may need the dex_lock_ to
3225 // get to a suspend point.
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003226 StackHandleScope<2> hs(self);
3227 mirror::String* location;
3228 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3229 self,
3230 dex_file)));
3231 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003232 {
3233 WriterMutexLock mu(self, dex_lock_);
3234 mirror::DexCache* dex_cache = FindDexCacheLocked(self, dex_file, true);
3235 if (dex_cache != nullptr) {
3236 return dex_cache;
3237 }
3238 if (h_dex_cache.Get() == nullptr) {
3239 self->AssertPendingOOMException();
3240 return nullptr;
3241 }
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003242 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3243 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3244 // that the arrays are null.
3245 InitializeDexCache(self, h_dex_cache.Get(), h_location.Get(), dex_file, linear_alloc);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003246 RegisterDexFileLocked(dex_file, h_dex_cache);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003247 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003248 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003249 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003250}
3251
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003252void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003253 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003254 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003255 RegisterDexFileLocked(dex_file, dex_cache);
3256}
3257
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003258mirror::DexCache* ClassLinker::FindDexCache(Thread* self,
3259 const DexFile& dex_file,
3260 bool allow_failure) {
3261 ReaderMutexLock mu(self, dex_lock_);
3262 return FindDexCacheLocked(self, dex_file, allow_failure);
3263}
3264
3265mirror::DexCache* ClassLinker::FindDexCacheLocked(Thread* self,
3266 const DexFile& dex_file,
3267 bool allow_failure) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003268 // Search assuming unique-ness of dex file.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003269 for (const DexCacheData& data : dex_caches_) {
3270 // Avoid decoding (and read barriers) other unrelated dex caches.
3271 if (data.dex_file == &dex_file) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07003272 ObjPtr<mirror::DexCache> dex_cache =
3273 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003274 if (dex_cache != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07003275 return dex_cache.Ptr();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003276 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -07003277 break;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003278 }
3279 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003280 if (allow_failure) {
3281 return nullptr;
3282 }
Mathieu Chartierac8f4392015-08-27 13:54:20 -07003283 std::string location(dex_file.GetLocation());
Brian Carlstrom81a90872015-08-28 09:07:14 -07003284 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003285 for (const DexCacheData& data : dex_caches_) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07003286 ObjPtr<mirror::DexCache> dex_cache =
3287 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003288 if (dex_cache != nullptr) {
3289 LOG(ERROR) << "Registered dex file " << dex_cache->GetDexFile()->GetLocation();
3290 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003291 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003292 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003293 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003294}
3295
Mathieu Chartiere401d142015-04-22 13:56:20 -07003296void ClassLinker::FixupDexCaches(ArtMethod* resolution_method) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003297 Thread* const self = Thread::Current();
3298 ReaderMutexLock mu(self, dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003299 for (const DexCacheData& data : dex_caches_) {
3300 if (!self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07003301 ObjPtr<mirror::DexCache> dex_cache = ObjPtr<mirror::DexCache>::DownCast(
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003302 self->DecodeJObject(data.weak_root));
3303 if (dex_cache != nullptr) {
3304 dex_cache->Fixup(resolution_method, image_pointer_size_);
3305 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003306 }
Ian Rogers19846512012-02-24 11:42:47 -08003307 }
3308}
3309
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003310mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003311 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003312 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003313 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003314 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003315 }
3316 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003317}
3318
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003319mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3320 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003321 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003322 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003323 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003324 StackHandleScope<1> hs(self);
3325 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003326 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003327 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3328 h_class->SetPrimitiveType(type);
3329 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003330 const char* descriptor = Primitive::Descriptor(type);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003331 mirror::Class* existing = InsertClass(descriptor, h_class.Get(),
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003332 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003333 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003334 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003335}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003336
Brian Carlstrombe977852011-07-19 14:54:54 -07003337// Create an array class (i.e. the class object for the array, not the
3338// array itself). "descriptor" looks like "[C" or "[[[[B" or
3339// "[Ljava/lang/String;".
3340//
3341// If "descriptor" refers to an array of primitives, look up the
3342// primitive type's internally-generated class object.
3343//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003344// "class_loader" is the class loader of the class that's referring to
3345// us. It's used to ensure that we're looking for the element type in
3346// the right context. It does NOT become the class loader for the
3347// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003348//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003349// Returns null with an exception raised on failure.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003350mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003351 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003352 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003353 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003354 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003355 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3356 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003357 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003358 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003359 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003360 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3361 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003362 if (component_type.Get() == nullptr) {
3363 DCHECK(self->IsExceptionPending());
3364 return nullptr;
3365 } else {
3366 self->ClearException();
3367 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003368 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003369 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3370 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3371 return nullptr;
3372 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003373 // See if the component type is already loaded. Array classes are
3374 // always associated with the class loader of their underlying
3375 // element type -- an array of Strings goes with the loader for
3376 // java/lang/String -- so we need to look for it there. (The
3377 // caller should have checked for the existence of the class
3378 // before calling here, but they did so with *their* class loader,
3379 // not the component type's loader.)
3380 //
3381 // If we find it, the caller adds "loader" to the class' initiating
3382 // loader list, which should prevent us from going through this again.
3383 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003384 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003385 // are the same, because our caller (FindClass) just did the
3386 // lookup. (Even if we get this wrong we still have correct behavior,
3387 // because we effectively do this lookup again when we add the new
3388 // class to the hash table --- necessary because of possible races with
3389 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003390 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003391 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003392 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003393 return new_class;
3394 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003395 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003396
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003397 // Fill out the fields in the Class.
3398 //
3399 // It is possible to execute some methods against arrays, because
3400 // all arrays are subclasses of java_lang_Object_, so we need to set
3401 // up a vtable. We can just point at the one in java_lang_Object_.
3402 //
3403 // Array classes are simple enough that we don't need to do a full
3404 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003405 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003406 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003407 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003408 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003409 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003410 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003411 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003412 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003413 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003414 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003415 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003416 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003417 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07003418 } else if (strcmp(descriptor, "[J") == 0) {
3419 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003420 }
3421 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003422 if (new_class.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003423 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003424 if (new_class.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003425 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003426 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003427 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003428 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003429 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003430 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003431 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003432 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003433 new_class->SetSuperClass(java_lang_Object);
3434 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003435 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003436 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07003437 if (component_type->IsPrimitive()) {
3438 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
3439 } else {
3440 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
3441 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003442 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00003443 new_class->PopulateEmbeddedVTable(image_pointer_size_);
3444 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
3445 new_class->SetImt(object_imt, image_pointer_size_);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003446 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003447 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003448 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003449
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003450 // All arrays have java/lang/Cloneable and java/io/Serializable as
3451 // interfaces. We need to set that up here, so that stuff like
3452 // "instanceof" works right.
3453 //
3454 // Note: The GC could run during the call to FindSystemClass,
3455 // so we need to make sure the class object is GC-valid while we're in
3456 // there. Do this by clearing the interface list so the GC will just
3457 // think that the entries are null.
3458
3459
3460 // Use the single, global copies of "interfaces" and "iftable"
3461 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003462 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003463 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003464 CHECK(array_iftable != nullptr);
3465 new_class->SetIfTable(array_iftable);
3466 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003467
Elliott Hughes00626c22013-06-14 15:04:14 -07003468 // Inherit access flags from the component type.
3469 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3470 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3471 access_flags &= kAccJavaFlagsMask;
3472 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003473 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003474 access_flags |= kAccAbstract | kAccFinal;
3475 access_flags &= ~kAccInterface;
3476
3477 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003478
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003479 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003480 if (existing == nullptr) {
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003481 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003482 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003483 }
3484 // Another thread must have loaded the class after we
3485 // started but before we finished. Abandon what we've
3486 // done.
3487 //
3488 // (Yes, this happens.)
3489
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003490 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003491}
3492
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003493mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003494 switch (type) {
3495 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003496 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003497 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003498 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003499 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003500 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003501 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003502 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003503 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003504 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003505 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003506 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003507 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003508 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003509 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003510 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003511 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003512 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003513 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003514 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003515 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003516 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003517 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003518 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003519}
3520
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003521mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass, size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003522 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003523 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003524 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003525 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003526 source += " from ";
3527 source += dex_cache->GetLocation()->ToModifiedUtf8();
3528 }
3529 LOG(INFO) << "Loaded class " << descriptor << source;
3530 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003531 {
3532 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3533 mirror::ClassLoader* const class_loader = klass->GetClassLoader();
3534 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
3535 mirror::Class* existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003536 if (existing != nullptr) {
Mathieu Chartier65975772016-08-05 10:46:36 -07003537 return existing;
3538 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003539 VerifyObject(klass);
3540 class_table->InsertWithHash(klass, hash);
3541 if (class_loader != nullptr) {
3542 // This is necessary because we need to have the card dirtied for remembered sets.
3543 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3544 }
3545 if (log_new_class_table_roots_) {
3546 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003547 }
3548 }
Mathieu Chartier65975772016-08-05 10:46:36 -07003549 if (kIsDebugBuild) {
3550 // Test that copied methods correctly can find their holder.
3551 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
3552 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
3553 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08003554 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003555 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003556}
3557
Alex Lighte64300b2015-12-15 15:02:47 -08003558// TODO This should really be in mirror::Class.
3559void ClassLinker::UpdateClassMethods(mirror::Class* klass,
3560 LengthPrefixedArray<ArtMethod>* new_methods) {
3561 klass->SetMethodsPtrUnchecked(new_methods,
3562 klass->NumDirectMethods(),
3563 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003564 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003565 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003566}
3567
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003568bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003569 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003570 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3571 return class_table != nullptr && class_table->Remove(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08003572}
3573
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003574mirror::Class* ClassLinker::LookupClass(Thread* self,
3575 const char* descriptor,
3576 size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003577 mirror::ClassLoader* class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01003578 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3579 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3580 if (class_table != nullptr) {
3581 mirror::Class* result = class_table->Lookup(descriptor, hash);
3582 if (result != nullptr) {
3583 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003584 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003585 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01003586 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003587}
3588
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003589class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
3590 public:
3591 explicit MoveClassTableToPreZygoteVisitor() {}
3592
3593 void Visit(mirror::ClassLoader* class_loader)
3594 REQUIRES(Locks::classlinker_classes_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003595 REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003596 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07003597 if (class_table != nullptr) {
3598 class_table->FreezeSnapshot();
3599 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003600 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003601};
3602
3603void ClassLinker::MoveClassTableToPreZygote() {
3604 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3605 boot_class_table_.FreezeSnapshot();
3606 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003607 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003608}
3609
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003610// Look up classes by hash and descriptor and put all matching ones in the result array.
3611class LookupClassesVisitor : public ClassLoaderVisitor {
3612 public:
3613 LookupClassesVisitor(const char* descriptor, size_t hash, std::vector<mirror::Class*>* result)
3614 : descriptor_(descriptor),
3615 hash_(hash),
3616 result_(result) {}
3617
3618 void Visit(mirror::ClassLoader* class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003619 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003620 ClassTable* const class_table = class_loader->GetClassTable();
3621 mirror::Class* klass = class_table->Lookup(descriptor_, hash_);
3622 if (klass != nullptr) {
3623 result_->push_back(klass);
3624 }
3625 }
3626
3627 private:
3628 const char* const descriptor_;
3629 const size_t hash_;
3630 std::vector<mirror::Class*>* const result_;
3631};
3632
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003633void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003634 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003635 Thread* const self = Thread::Current();
3636 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003637 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
3638 mirror::Class* klass = boot_class_table_.Lookup(descriptor, hash);
3639 if (klass != nullptr) {
3640 result.push_back(klass);
3641 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003642 LookupClassesVisitor visitor(descriptor, hash, &result);
3643 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003644}
3645
Alex Lightf1f10492015-10-07 16:08:36 -07003646bool ClassLinker::AttemptSupertypeVerification(Thread* self,
3647 Handle<mirror::Class> klass,
3648 Handle<mirror::Class> supertype) {
3649 DCHECK(self != nullptr);
3650 DCHECK(klass.Get() != nullptr);
3651 DCHECK(supertype.Get() != nullptr);
3652
Alex Lightf1f10492015-10-07 16:08:36 -07003653 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
3654 VerifyClass(self, supertype);
3655 }
3656 if (supertype->IsCompileTimeVerified()) {
3657 // Either we are verified or we soft failed and need to retry at runtime.
3658 return true;
3659 }
3660 // If we got this far then we have a hard failure.
3661 std::string error_msg =
3662 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
3663 PrettyDescriptor(klass.Get()).c_str(),
3664 PrettyDescriptor(supertype.Get()).c_str());
3665 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003666 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07003667 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
3668 if (cause.Get() != nullptr) {
3669 // Set during VerifyClass call (if at all).
3670 self->ClearException();
3671 }
3672 // Change into a verify error.
3673 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3674 if (cause.Get() != nullptr) {
3675 self->GetException()->SetCause(cause.Get());
3676 }
3677 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
3678 if (Runtime::Current()->IsAotCompiler()) {
3679 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3680 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07003681 // Need to grab the lock to change status.
3682 ObjectLock<mirror::Class> super_lock(self, klass);
Alex Lightf1f10492015-10-07 16:08:36 -07003683 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
3684 return false;
3685}
3686
Andreas Gampe5fd66d02016-09-12 20:22:19 -07003687void ClassLinker::VerifyClass(Thread* self,
3688 Handle<mirror::Class> klass,
3689 verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07003690 {
3691 // TODO: assert that the monitor on the Class is held
3692 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003693
Andreas Gampe884f3b82016-03-30 19:52:58 -07003694 // Is somebody verifying this now?
3695 mirror::Class::Status old_status = klass->GetStatus();
3696 while (old_status == mirror::Class::kStatusVerifying ||
3697 old_status == mirror::Class::kStatusVerifyingAtRuntime) {
3698 lock.WaitIgnoringInterrupts();
Alex Light06039ba2016-04-04 13:23:14 -07003699 CHECK(klass->IsErroneous() || (klass->GetStatus() > old_status))
3700 << "Class '" << PrettyClass(klass.Get()) << "' performed an illegal verification state "
3701 << "transition from " << old_status << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07003702 old_status = klass->GetStatus();
3703 }
jeffhao98eacac2011-09-14 16:11:53 -07003704
Andreas Gampe884f3b82016-03-30 19:52:58 -07003705 // The class might already be erroneous, for example at compile time if we attempted to verify
3706 // this class as a parent to another.
3707 if (klass->IsErroneous()) {
3708 ThrowEarlierClassFailure(klass.Get());
3709 return;
3710 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003711
Andreas Gampe884f3b82016-03-30 19:52:58 -07003712 // Don't attempt to re-verify if already sufficiently verified.
3713 if (klass->IsVerified()) {
3714 EnsureSkipAccessChecksMethods(klass);
3715 return;
3716 }
3717 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
3718 return;
3719 }
jeffhao98eacac2011-09-14 16:11:53 -07003720
Andreas Gampe884f3b82016-03-30 19:52:58 -07003721 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
3722 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
3723 } else {
3724 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
3725 << PrettyClass(klass.Get());
3726 CHECK(!Runtime::Current()->IsAotCompiler());
3727 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
3728 }
3729
3730 // Skip verification if disabled.
3731 if (!Runtime::Current()->IsVerificationEnabled()) {
3732 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
3733 EnsureSkipAccessChecksMethods(klass);
3734 return;
3735 }
Jeff Hao4a200f52014-04-01 14:58:49 -07003736 }
3737
Ian Rogers9ffb0392012-09-10 11:56:50 -07003738 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003739 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07003740 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
3741 // If we have a superclass and we get a hard verification failure we can return immediately.
3742 if (supertype.Get() != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
3743 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
3744 return;
3745 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08003746
Alex Lightf1f10492015-10-07 16:08:36 -07003747 // Verify all default super-interfaces.
3748 //
3749 // (1) Don't bother if the superclass has already had a soft verification failure.
3750 //
3751 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
3752 // recursive initialization by themselves. This is because when an interface is initialized
3753 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
3754 // but choose not to for an optimization. If the interfaces is being verified due to a class
3755 // initialization (which would need all the default interfaces to be verified) the class code
3756 // will trigger the recursive verification anyway.
3757 if ((supertype.Get() == nullptr || supertype->IsVerified()) // See (1)
3758 && !klass->IsInterface()) { // See (2)
3759 int32_t iftable_count = klass->GetIfTableCount();
3760 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
3761 // Loop through all interfaces this class has defined. It doesn't matter the order.
3762 for (int32_t i = 0; i < iftable_count; i++) {
3763 iface.Assign(klass->GetIfTable()->GetInterface(i));
3764 DCHECK(iface.Get() != nullptr);
3765 // We only care if we have default interfaces and can skip if we are already verified...
3766 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
3767 continue;
3768 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
3769 // We had a hard failure while verifying this interface. Just return immediately.
3770 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
3771 return;
3772 } else if (UNLIKELY(!iface->IsVerified())) {
3773 // We softly failed to verify the iface. Stop checking and clean up.
3774 // Put the iface into the supertype handle so we know what caused us to fail.
3775 supertype.Assign(iface.Get());
3776 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08003777 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08003778 }
3779 }
3780
Alex Lightf1f10492015-10-07 16:08:36 -07003781 // At this point if verification failed, then supertype is the "first" supertype that failed
3782 // verification (without a specific order). If verification succeeded, then supertype is either
3783 // null or the original superclass of klass and is verified.
3784 DCHECK(supertype.Get() == nullptr ||
3785 supertype.Get() == klass->GetSuperClass() ||
3786 !supertype->IsVerified());
3787
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003788 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003789 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003790 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003791 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08003792 // If the oat file says the class had an error, re-run the verifier. That way we will get a
3793 // precise error message. To ensure a rerun, test:
3794 // oat_file_class_status == mirror::Class::kStatusError => !preverified
3795 DCHECK(!(oat_file_class_status == mirror::Class::kStatusError) || !preverified);
3796
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003797 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003798 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003799 if (!preverified) {
Andreas Gampe53e32d12015-12-09 21:03:23 -08003800 Runtime* runtime = Runtime::Current();
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003801 verifier_failure = verifier::MethodVerifier::VerifyClass(self,
3802 klass.Get(),
Andreas Gampe53e32d12015-12-09 21:03:23 -08003803 runtime->GetCompilerCallbacks(),
3804 runtime->IsAotCompiler(),
Andreas Gampe7fe30232016-03-25 16:58:00 -07003805 log_level,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003806 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003807 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07003808
3809 // Verification is done, grab the lock again.
3810 ObjectLock<mirror::Class> lock(self, klass);
3811
jeffhaof1e6b7c2012-06-05 18:33:30 -07003812 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003813 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003814 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003815 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3816 << " because: " << error_msg;
3817 }
Ian Rogers1f539342012-10-03 21:09:42 -07003818 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003819 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08003820 ResolveClassExceptionHandlerTypes(klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003821 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07003822 // Even though there were no verifier failures we need to respect whether the super-class and
3823 // super-default-interfaces were verified or requiring runtime reverification.
3824 if (supertype.Get() == nullptr || supertype->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003825 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003826 } else {
Alex Lightf1f10492015-10-07 16:08:36 -07003827 CHECK_EQ(supertype->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003828 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07003829 // Pretend a soft failure occurred so that we don't consider the class verified below.
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003830 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003831 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003832 } else {
3833 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3834 // Soft failures at compile time should be retried at runtime. Soft
3835 // failures at runtime will be handled by slow paths in the generated
3836 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003837 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003838 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003839 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003840 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08003841 // As this is a fake verified status, make sure the methods are _not_ marked
3842 // kAccSkipAccessChecks later.
3843 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003844 }
3845 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003846 } else {
Andreas Gampeec6e6c12015-11-05 20:39:56 -08003847 VLOG(verifier) << "Verification failed on class " << PrettyDescriptor(klass.Get())
3848 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3849 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003850 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003851 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003852 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003853 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003854 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003855 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08003856 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003857 // method.
3858 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08003859 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003860 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08003861
3862 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
3863 // Never skip access checks if the verification soft fail is forced.
3864 // Mark the class as having a verification attempt to avoid re-running the verifier.
3865 klass->SetVerificationAttempted();
3866 } else {
3867 EnsureSkipAccessChecksMethods(klass);
3868 }
Andreas Gampe48498592014-09-10 19:48:05 -07003869 }
3870}
3871
Igor Murashkindf707e42016-02-02 16:56:50 -08003872void ClassLinker::EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass) {
3873 if (!klass->WasVerificationAttempted()) {
3874 klass->SetSkipAccessChecksFlagOnAllMethods(image_pointer_size_);
3875 klass->SetVerificationAttempted();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003876 }
jeffhao98eacac2011-09-14 16:11:53 -07003877}
3878
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003879bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
3880 mirror::Class* klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003881 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003882 // If we're compiling, we can only verify the class using the oat file if
3883 // we are not compiling the image or if the class we're verifying is not part of
3884 // the app. In other words, we will only check for preverification of bootclasspath
3885 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003886 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003887 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003888 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003889 return false;
3890 }
3891 // We are compiling an app (not the image).
3892
3893 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003894 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003895 return false;
3896 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003897 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003898
Richard Uhler07b3c232015-03-31 15:57:54 -07003899 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003900 // In case we run without an image there won't be a backing oat file.
3901 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003902 return false;
3903 }
3904
Andreas Gampe76bd8802014-12-10 16:43:58 -08003905 // We may be running with a preopted oat file but without image. In this case,
Igor Murashkindf707e42016-02-02 16:56:50 -08003906 // we don't skip verification of skip_access_checks classes to ensure we initialize
Andreas Gampe76bd8802014-12-10 16:43:58 -08003907 // dex caches with all types resolved during verification.
3908 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
3909 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
3910 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
3911 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003912 if (!Runtime::Current()->IsAotCompiler() &&
Jeff Haodcdc85b2015-12-04 14:06:18 -08003913 !Runtime::Current()->GetHeap()->HasBootImageSpace() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08003914 klass->GetClassLoader() != nullptr) {
3915 return false;
3916 }
3917
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003918 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003919 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003920 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3921 oat_file_class_status == mirror::Class::kStatusInitialized) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07003922 return true;
3923 }
3924 // If we only verified a subset of the classes at compile time, we can end up with classes that
3925 // were resolved by the verifier.
3926 if (oat_file_class_status == mirror::Class::kStatusResolved) {
3927 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003928 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003929 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003930 // Compile time verification failed with a soft error. Compile time verification can fail
3931 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003932 // class ... {
3933 // Foo x;
3934 // .... () {
3935 // if (...) {
3936 // v1 gets assigned a type of resolved class Foo
3937 // } else {
3938 // v1 gets assigned a type of unresolved class Bar
3939 // }
3940 // iput x = v1
3941 // } }
3942 // when we merge v1 following the if-the-else it results in Conflict
3943 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3944 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3945 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3946 // at compile time).
3947 return false;
3948 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003949 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003950 // Compile time verification failed with a hard error. This is caused by invalid instructions
3951 // in the class. These errors are unrecoverable.
3952 return false;
3953 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003954 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003955 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3956 // not loading the class.
3957 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3958 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003959 return false;
3960 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003961 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003962 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003963 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003964 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003965 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003966}
3967
Alex Light5a559862016-01-29 12:24:48 -08003968void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08003969 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08003970 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003971 }
3972}
3973
Alex Light5a559862016-01-29 12:24:48 -08003974void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003975 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
Alex Light5a559862016-01-29 12:24:48 -08003976 const DexFile::CodeItem* code_item =
3977 method->GetDexFile()->GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003978 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003979 return; // native or abstract method
3980 }
3981 if (code_item->tries_size_ == 0) {
3982 return; // nothing to process
3983 }
Ian Rogers13735952014-10-08 12:43:28 -07003984 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003985 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003986 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3987 CatchHandlerIterator iterator(handlers_ptr);
3988 for (; iterator.HasNext(); iterator.Next()) {
3989 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3990 // unresolved exception types will be ignored by exception delivery
3991 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Mathieu Chartier90443472015-07-16 20:32:27 -07003992 mirror::Class* exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003993 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003994 DCHECK(Thread::Current()->IsExceptionPending());
3995 Thread::Current()->ClearException();
3996 }
3997 }
3998 }
3999 handlers_ptr = iterator.EndDataPointer();
4000 }
4001}
4002
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004003mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4004 jstring name,
4005 jobjectArray interfaces,
4006 jobject loader,
4007 jobjectArray methods,
4008 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004009 Thread* self = soa.Self();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004010 StackHandleScope<10> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004011 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004012 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004013 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004014 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004015 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004016 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004017 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004018 klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004019 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4020 // the methods.
4021 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07004022 klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader).Ptr());
Ian Rogersc2b44472011-12-14 21:17:17 -08004023 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07004024 klass->SetName(soa.Decode<mirror::String>(name).Ptr());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004025 klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004026 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004027 std::string descriptor(GetDescriptorForProxy(klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004028 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004029
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004030 // Needs to be before we insert the class so that the allocator field is set.
4031 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(klass->GetClassLoader());
4032
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004033 // Insert the class before loading the fields as the field roots
4034 // (ArtField::declaring_class_) are only visited from the class
4035 // table. There can't be any suspend points between inserting the
4036 // class and setting the field arrays below.
4037 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), hash);
4038 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004039
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004040 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004041 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004042 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004043 klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004044
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004045 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4046 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004047 ArtField& interfaces_sfield = sfields->At(0);
4048 interfaces_sfield.SetDexFieldIndex(0);
4049 interfaces_sfield.SetDeclaringClass(klass.Get());
4050 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004051
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004052 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004053 ArtField& throws_sfield = sfields->At(1);
4054 throws_sfield.SetDexFieldIndex(1);
4055 throws_sfield.SetDeclaringClass(klass.Get());
4056 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004057
Ian Rogers466bb252011-10-14 03:29:56 -07004058 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004059 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004060
Alex Lighte64300b2015-12-15 15:02:47 -08004061 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004062 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004063 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004064 << PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004065 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004066
4067 // Create the methods array.
4068 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4069 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004070 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4071 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004072 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004073 self->AssertPendingOOMException();
4074 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004075 }
Alex Lighte64300b2015-12-15 15:02:47 -08004076 klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
4077
4078 // Create the single direct method.
4079 CreateProxyConstructor(klass, klass->GetDirectMethodUnchecked(0, image_pointer_size_));
4080
4081 // Create virtual method using specified prototypes.
4082 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004083 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004084 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4085 auto* prototype = h_methods->Get(i)->GetArtMethod();
4086 CreateProxyMethod(klass, prototype, virtual_method);
4087 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4088 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004089 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004090
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004091 // The super class is java.lang.reflect.Proxy
4092 klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy));
4093 // Now effectively in the loaded state.
4094 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004095 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004096
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004097 MutableHandle<mirror::Class> new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004098 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004099 // Must hold lock on object when resolved.
4100 ObjectLock<mirror::Class> resolution_lock(self, klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004101 // Link the fields and virtual methods, creating vtable and iftables.
4102 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004103 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004104 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004105 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004106 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004107 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004108 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004109 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004110 CHECK(klass->IsRetired());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004111 CHECK_NE(klass.Get(), new_class.Get());
4112 klass.Assign(new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004113
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004114 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004115 interfaces_sfield.SetObject<false>(
4116 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004117 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004118 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4119 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004120 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004121 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004122
4123 {
4124 // Lock on klass is released. Lock new class object.
4125 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004126 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004127 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004128
4129 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004130 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004131 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004132 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4133
Ian Rogersc2b44472011-12-14 21:17:17 -08004134 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004135 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4136 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004137 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004138 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004139
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004140 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004141 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004142 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004143 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004144 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
4145
4146 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004147 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004148 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004149
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004150 CHECK_EQ(klass.Get()->GetInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004151 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004152 CHECK_EQ(klass.Get()->GetThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004153 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004154 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004155 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004156}
4157
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004158std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
4159 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004160 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004161 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004162 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4163}
4164
Mathieu Chartiere401d142015-04-22 13:56:20 -07004165void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4166 // Create constructor for Proxy that must initialize the method.
Igor Murashkine3d4ff52016-02-02 10:46:42 -08004167 CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 18u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004168 ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->GetDirectMethodUnchecked(
4169 2, image_pointer_size_);
Igor Murashkine3d4ff52016-02-02 10:46:42 -08004170 DCHECK_EQ(std::string(proxy_constructor->GetName()), "<init>");
Sebastien Hertzae94e352014-08-27 15:32:56 +02004171 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4172 // constructor method.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004173 GetClassRoot(kJavaLangReflectProxy)->GetDexCache()->SetResolvedMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -07004174 proxy_constructor->GetDexMethodIndex(), proxy_constructor, image_pointer_size_);
Jeff Haodb8a6642014-08-14 17:18:52 -07004175 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4176 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004177 DCHECK(out != nullptr);
4178 out->CopyFrom(proxy_constructor, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004179 // Make this constructor public and fix the class to be our Proxy version
Mathieu Chartiere401d142015-04-22 13:56:20 -07004180 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) | kAccPublic);
4181 out->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004182}
4183
Mathieu Chartiere401d142015-04-22 13:56:20 -07004184void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004185 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004186 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4187 CHECK_STREQ(np->GetName(), "<init>");
4188 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004189 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004190}
4191
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004192void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004193 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004194 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4195 // prototype method
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004196 auto* dex_cache = prototype->GetDeclaringClass()->GetDexCache();
4197 // Avoid dirtying the dex cache unless we need to.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004198 if (dex_cache->GetResolvedMethod(prototype->GetDexMethodIndex(), image_pointer_size_) !=
4199 prototype) {
4200 dex_cache->SetResolvedMethod(
4201 prototype->GetDexMethodIndex(), prototype, image_pointer_size_);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004202 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004203 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004204 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004205 DCHECK(out != nullptr);
4206 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004207
Alex Lighte9dd04f2016-03-16 16:09:45 -07004208 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004209 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004210 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4211 // preference to the invocation handler.
4212 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4213 // Make the method final.
4214 const uint32_t kAddFlags = kAccFinal;
4215 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4216
4217 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4218 // method they copy might (if it's a default method).
4219 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004220
Ian Rogers466bb252011-10-14 03:29:56 -07004221 // At runtime the method looks like a reference and argument saving method, clone the code
4222 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004223 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004224}
Jesse Wilson95caa792011-10-12 18:14:17 -04004225
Mathieu Chartiere401d142015-04-22 13:56:20 -07004226void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004227 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004228 CHECK(!prototype->IsFinal());
4229 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004230 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004231
4232 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4233 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Vladimir Marko05792b92015-08-03 11:56:49 +01004234 CHECK(prototype->HasSameDexCacheResolvedMethods(method, image_pointer_size_));
4235 CHECK(prototype->HasSameDexCacheResolvedTypes(method, image_pointer_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07004236 auto* np = method->GetInterfaceMethodIfProxy(image_pointer_size_);
4237 CHECK_EQ(prototype->GetDeclaringClass()->GetDexCache(), np->GetDexCache());
Ian Rogers19846512012-02-24 11:42:47 -08004238 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4239
Mathieu Chartiere401d142015-04-22 13:56:20 -07004240 CHECK_STREQ(np->GetName(), prototype->GetName());
4241 CHECK_STREQ(np->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004242 // More complex sanity - via dex cache
Vladimir Marko05792b92015-08-03 11:56:49 +01004243 CHECK_EQ(np->GetReturnType(true /* resolve */, image_pointer_size_),
4244 prototype->GetReturnType(true /* resolve */, image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004245}
4246
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004247bool ClassLinker::CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004248 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004249 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004250 return true;
4251 }
4252 if (!can_init_statics) {
4253 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004254 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004255 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004256 return false;
4257 }
4258 // Check if there are encoded static values needing initialization.
4259 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004260 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004261 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004262 if (dex_class_def->static_values_off_ != 0) {
4263 return false;
4264 }
4265 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004266 // If we are a class we need to initialize all interfaces with default methods when we are
4267 // initialized. Check all of them.
4268 if (!klass->IsInterface()) {
4269 size_t num_interfaces = klass->GetIfTableCount();
4270 for (size_t i = 0; i < num_interfaces; i++) {
4271 mirror::Class* iface = klass->GetIfTable()->GetInterface(i);
4272 if (iface->HasDefaultMethods() &&
4273 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
4274 return false;
4275 }
4276 }
4277 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004278 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004279 if (klass->IsInterface() || !klass->HasSuperClass()) {
4280 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004281 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004282 mirror::Class* super_class = klass->GetSuperClass();
4283 if (!can_init_parents && !super_class->IsInitialized()) {
4284 return false;
4285 }
4286 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004287}
4288
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004289bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
4290 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004291 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4292
4293 // Are we already initialized and therefore done?
4294 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4295 // an initialized class will never change its state.
4296 if (klass->IsInitialized()) {
4297 return true;
4298 }
4299
4300 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004301 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004302 return false;
4303 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004304
Ian Rogers7b078e82014-09-10 14:44:24 -07004305 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004306 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004307 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004308 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004309
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004310 // Re-check under the lock in case another thread initialized ahead of us.
4311 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004312 return true;
4313 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004314
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004315 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004316 if (klass->IsErroneous()) {
Andreas Gampecb086952015-11-02 16:20:00 -08004317 ThrowEarlierClassFailure(klass.Get(), true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07004318 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004319 return false;
4320 }
4321
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004322 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004323
4324 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004325 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004326 if (!klass->IsVerified()) {
4327 // We failed to verify, expect either the klass to be erroneous or verification failed at
4328 // compile time.
4329 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07004330 // The class is erroneous. This may be a verifier error, or another thread attempted
4331 // verification and/or initialization and failed. We can distinguish those cases by
4332 // whether an exception is already pending.
4333 if (self->IsExceptionPending()) {
4334 // Check that it's a VerifyError.
4335 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
4336 PrettyClass(self->GetException()->GetClass()));
4337 } else {
4338 // Check that another thread attempted initialization.
4339 DCHECK_NE(0, klass->GetClinitThreadId());
4340 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
4341 // Need to rethrow the previous failure now.
4342 ThrowEarlierClassFailure(klass.Get(), true);
4343 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07004344 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004345 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004346 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004347 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004348 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004349 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004350 } else {
4351 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004352 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07004353
4354 // A separate thread could have moved us all the way to initialized. A "simple" example
4355 // involves a subclass of the current class being initialized at the same time (which
4356 // will implicitly initialize the superclass, if scheduled that way). b/28254258
4357 DCHECK_NE(mirror::Class::kStatusError, klass->GetStatus());
4358 if (klass->IsInitialized()) {
4359 return true;
4360 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004361 }
4362
Brian Carlstromd1422f82011-09-28 11:37:09 -07004363 // If the class is kStatusInitializing, either this thread is
4364 // initializing higher up the stack or another thread has beat us
4365 // to initializing and we need to wait. Either way, this
4366 // invocation of InitializeClass will not be responsible for
4367 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004368 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004369 // Could have got an exception during verification.
4370 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004371 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004372 return false;
4373 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004374 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004375 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004376 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004377 return true;
4378 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004379 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004380 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004381 }
4382
4383 if (!ValidateSuperClassDescriptors(klass)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004384 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004385 return false;
4386 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004387 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004388
Andreas Gampe9510ccd2016-04-20 09:55:25 -07004389 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get())
4390 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004391
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004392 // From here out other threads may observe that we're initializing and so changes of state
4393 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004394 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004395 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004396
4397 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004398 }
4399
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004400 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004401 if (!klass->IsInterface() && klass->HasSuperClass()) {
4402 mirror::Class* super_class = klass->GetSuperClass();
4403 if (!super_class->IsInitialized()) {
4404 CHECK(!super_class->IsInterface());
4405 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004406 StackHandleScope<1> hs(self);
4407 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004408 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004409 if (!super_initialized) {
4410 // The super class was verified ahead of entering initializing, we should only be here if
4411 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004412 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004413 << "Super class initialization failed for "
4414 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004415 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004416 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004417 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004418 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004419 // Initialization failed because the super-class is erroneous.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004420 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004421 return false;
4422 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004423 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004424 }
4425
Alex Lighteb7c1442015-08-31 13:17:42 -07004426 if (!klass->IsInterface()) {
4427 // Initialize interfaces with default methods for the JLS.
4428 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004429 // Only setup the (expensive) handle scope if we actually need to.
4430 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07004431 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07004432 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
4433 for (size_t i = 0; i < num_direct_interfaces; i++) {
4434 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass, i));
4435 CHECK(handle_scope_iface.Get() != nullptr);
4436 CHECK(handle_scope_iface->IsInterface());
4437 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
4438 // We have already done this for this interface. Skip it.
4439 continue;
4440 }
4441 // We cannot just call initialize class directly because we need to ensure that ALL
4442 // interfaces with default methods are initialized. Non-default interface initialization
4443 // will not affect other non-default super-interfaces.
4444 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
4445 handle_scope_iface,
4446 can_init_statics,
4447 can_init_parents);
4448 if (!iface_initialized) {
4449 ObjectLock<mirror::Class> lock(self, klass);
4450 // Initialization failed because one of our interfaces with default methods is erroneous.
4451 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4452 return false;
4453 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004454 }
4455 }
4456 }
4457
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004458 const size_t num_static_fields = klass->NumStaticFields();
4459 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004460 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004461 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004462 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004463 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004464 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004465 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004466
4467 // Eagerly fill in static fields so that the we don't have to do as many expensive
4468 // Class::FindStaticField in ResolveField.
4469 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004470 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004471 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004472 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004473 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004474 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004475 } else {
4476 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004477 }
4478 }
4479
David Sehr9323e6e2016-09-13 08:58:35 -07004480 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_file,
4481 &dex_cache,
4482 &class_loader,
4483 this,
4484 *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004485 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004486 ClassDataItemIterator field_it(dex_file, class_data);
4487 if (value_it.HasNext()) {
4488 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004489 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004490 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004491 ArtField* field = ResolveField(
4492 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004493 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004494 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004495 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004496 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004497 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07004498 if (self->IsExceptionPending()) {
4499 break;
4500 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004501 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004502 }
4503 }
4504 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004505
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004506
Mathieu Chartierda595be2016-08-10 13:57:39 -07004507 if (!self->IsExceptionPending()) {
4508 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4509 if (clinit != nullptr) {
4510 CHECK(can_init_statics);
4511 JValue result;
4512 clinit->Invoke(self, nullptr, 0, &result, "V");
4513 }
4514 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004515 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004516 uint64_t t1 = NanoTime();
4517
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004518 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004519 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004520 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004521
4522 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004523 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004524 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004525 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004526 } else if (Runtime::Current()->IsTransactionAborted()) {
4527 // The exception thrown when the transaction aborted has been caught and cleared
4528 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01004529 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
4530 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02004531 Runtime::Current()->ThrowTransactionAbortError(self);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004532 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004533 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004534 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004535 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4536 RuntimeStats* thread_stats = self->GetStats();
4537 ++global_stats->class_init_count;
4538 ++thread_stats->class_init_count;
4539 global_stats->class_init_time_ns += (t1 - t0);
4540 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004541 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004542 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004543 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004544 std::string temp;
4545 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004546 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004547 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004548 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004549 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004550 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004551 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004552 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004553}
4554
Alex Lighteb7c1442015-08-31 13:17:42 -07004555// We recursively run down the tree of interfaces. We need to do this in the order they are declared
4556// and perform the initialization only on those interfaces that contain default methods.
4557bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
4558 Handle<mirror::Class> iface,
4559 bool can_init_statics,
4560 bool can_init_parents) {
4561 CHECK(iface->IsInterface());
4562 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07004563 // Only create the (expensive) handle scope if we need it.
4564 if (UNLIKELY(num_direct_ifaces > 0)) {
4565 StackHandleScope<1> hs(self);
4566 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
4567 // First we initialize all of iface's super-interfaces recursively.
4568 for (size_t i = 0; i < num_direct_ifaces; i++) {
4569 mirror::Class* super_iface = mirror::Class::GetDirectInterface(self, iface, i);
4570 if (!super_iface->HasBeenRecursivelyInitialized()) {
4571 // Recursive step
4572 handle_super_iface.Assign(super_iface);
4573 if (!InitializeDefaultInterfaceRecursive(self,
4574 handle_super_iface,
4575 can_init_statics,
4576 can_init_parents)) {
4577 return false;
4578 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004579 }
4580 }
4581 }
4582
4583 bool result = true;
4584 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
4585 // initialize if we don't have default methods.
4586 if (iface->HasDefaultMethods()) {
4587 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
4588 }
4589
4590 // Mark that this interface has undergone recursive default interface initialization so we know we
4591 // can skip it on any later class initializations. We do this even if we are not a default
4592 // interface since we can still avoid the traversal. This is purely a performance optimization.
4593 if (result) {
4594 // TODO This should be done in a better way
4595 ObjectLock<mirror::Class> lock(self, iface);
4596 iface->SetRecursivelyInitialized();
4597 }
4598 return result;
4599}
4600
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004601bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
4602 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004603 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004604 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004605 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004606 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004607 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004608 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004609
4610 // When we wake up, repeat the test for init-in-progress. If
4611 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004612 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004613 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004614 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004615 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004616 return false;
4617 }
4618 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004619 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004620 continue;
4621 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004622 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
4623 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004624 // Compile time initialization failed.
4625 return false;
4626 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004627 if (klass->IsErroneous()) {
4628 // The caller wants an exception, but it was thrown in a
4629 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004630 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004631 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004632 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004633 return false;
4634 }
4635 if (klass->IsInitialized()) {
4636 return true;
4637 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004638 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004639 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004640 }
Ian Rogers07140832014-09-30 15:43:59 -07004641 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004642}
4643
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004644static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
4645 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004646 ArtMethod* method,
4647 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004648 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004649 DCHECK(Thread::Current()->IsExceptionPending());
4650 DCHECK(!m->IsProxyMethod());
4651 const DexFile* dex_file = m->GetDexFile();
4652 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
4653 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
4654 uint16_t return_type_idx = proto_id.return_type_idx_;
4655 std::string return_type = PrettyType(return_type_idx, *dex_file);
4656 std::string class_loader = PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
4657 ThrowWrappedLinkageError(klass.Get(),
4658 "While checking class %s method %s signature against %s %s: "
4659 "Failed to resolve return type %s with %s",
4660 PrettyDescriptor(klass.Get()).c_str(),
Mathieu Chartiere401d142015-04-22 13:56:20 -07004661 PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004662 super_klass->IsInterface() ? "interface" : "superclass",
4663 PrettyDescriptor(super_klass.Get()).c_str(),
4664 return_type.c_str(), class_loader.c_str());
4665}
4666
4667static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
4668 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004669 ArtMethod* method,
4670 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004671 uint32_t index,
4672 uint32_t arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004673 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004674 DCHECK(Thread::Current()->IsExceptionPending());
4675 DCHECK(!m->IsProxyMethod());
4676 const DexFile* dex_file = m->GetDexFile();
4677 std::string arg_type = PrettyType(arg_type_idx, *dex_file);
4678 std::string class_loader = PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
4679 ThrowWrappedLinkageError(klass.Get(),
4680 "While checking class %s method %s signature against %s %s: "
4681 "Failed to resolve arg %u type %s with %s",
4682 PrettyDescriptor(klass.Get()).c_str(),
Mathieu Chartiere401d142015-04-22 13:56:20 -07004683 PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004684 super_klass->IsInterface() ? "interface" : "superclass",
4685 PrettyDescriptor(super_klass.Get()).c_str(),
4686 index, arg_type.c_str(), class_loader.c_str());
4687}
4688
4689static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
4690 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004691 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004692 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004693 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004694 ThrowLinkageError(klass.Get(),
4695 "Class %s method %s resolves differently in %s %s: %s",
4696 PrettyDescriptor(klass.Get()).c_str(),
Mathieu Chartiere401d142015-04-22 13:56:20 -07004697 PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004698 super_klass->IsInterface() ? "interface" : "superclass",
4699 PrettyDescriptor(super_klass.Get()).c_str(),
4700 error_msg.c_str());
4701}
4702
Ian Rogersb5fb2072014-12-02 17:22:02 -08004703static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Andreas Gampe542451c2016-07-26 09:02:02 -07004704 PointerSize pointer_size,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004705 Handle<mirror::Class> klass,
4706 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004707 ArtMethod* method1,
4708 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004709 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004710 {
4711 StackHandleScope<1> hs(self);
Vladimir Marko05792b92015-08-03 11:56:49 +01004712 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType(true /* resolve */,
4713 pointer_size)));
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004714 if (UNLIKELY(return_type.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004715 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004716 return false;
4717 }
Vladimir Marko05792b92015-08-03 11:56:49 +01004718 mirror::Class* other_return_type = method2->GetReturnType(true /* resolve */,
4719 pointer_size);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004720 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004721 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004722 return false;
4723 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00004724 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004725 ThrowSignatureMismatch(klass, super_klass, method1,
4726 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
4727 PrettyClassAndClassLoader(return_type.Get()).c_str(),
4728 return_type.Get(),
4729 PrettyClassAndClassLoader(other_return_type).c_str(),
4730 other_return_type));
Ian Rogersb5fb2072014-12-02 17:22:02 -08004731 return false;
4732 }
4733 }
4734 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4735 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4736 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004737 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004738 ThrowSignatureMismatch(klass, super_klass, method1,
4739 StringPrintf("Type list mismatch with %s",
Mathieu Chartiere401d142015-04-22 13:56:20 -07004740 PrettyMethod(method2, true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004741 return false;
4742 }
4743 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08004744 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004745 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004746 ThrowSignatureMismatch(klass, super_klass, method1,
4747 StringPrintf("Type list mismatch with %s",
Mathieu Chartiere401d142015-04-22 13:56:20 -07004748 PrettyMethod(method2, true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004749 return false;
4750 }
4751 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08004752 }
4753 uint32_t num_types = types1->Size();
4754 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004755 ThrowSignatureMismatch(klass, super_klass, method1,
4756 StringPrintf("Type list mismatch with %s",
Mathieu Chartiere401d142015-04-22 13:56:20 -07004757 PrettyMethod(method2, true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08004758 return false;
4759 }
4760 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00004761 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004762 uint32_t param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00004763 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Marko05792b92015-08-03 11:56:49 +01004764 method1->GetClassFromTypeIndex(param_type_idx, true /* resolve */, pointer_size)));
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004765 if (UNLIKELY(param_type.Get() == nullptr)) {
4766 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004767 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004768 return false;
4769 }
4770 uint32_t other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Ian Rogersb5fb2072014-12-02 17:22:02 -08004771 mirror::Class* other_param_type =
Vladimir Marko05792b92015-08-03 11:56:49 +01004772 method2->GetClassFromTypeIndex(other_param_type_idx, true /* resolve */, pointer_size);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004773 if (UNLIKELY(other_param_type == nullptr)) {
4774 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004775 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004776 return false;
4777 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00004778 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004779 ThrowSignatureMismatch(klass, super_klass, method1,
4780 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
4781 i,
4782 PrettyClassAndClassLoader(param_type.Get()).c_str(),
4783 param_type.Get(),
4784 PrettyClassAndClassLoader(other_param_type).c_str(),
4785 other_param_type));
Ian Rogersb5fb2072014-12-02 17:22:02 -08004786 return false;
4787 }
4788 }
4789 return true;
4790}
4791
4792
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004793bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004794 if (klass->IsInterface()) {
4795 return true;
4796 }
Ian Rogers151f2212014-05-06 11:27:27 -07004797 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004798 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07004799 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004800 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004801 if (klass->HasSuperClass() &&
4802 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004803 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004804 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004805 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
4806 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
4807 if (m != super_m) {
Vladimir Marko05792b92015-08-03 11:56:49 +01004808 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, image_pointer_size_,
4809 klass, super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004810 m, super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004811 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004812 return false;
4813 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004814 }
4815 }
4816 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004817 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004818 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
4819 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
4820 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07004821 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004822 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
4823 j, image_pointer_size_);
4824 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
4825 if (m != super_m) {
Vladimir Marko05792b92015-08-03 11:56:49 +01004826 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, image_pointer_size_,
4827 klass, super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004828 m, super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01004829 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004830 return false;
4831 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004832 }
4833 }
4834 }
4835 }
4836 return true;
4837}
4838
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004839bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004840 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004841 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004842 if (c->IsInitialized()) {
Igor Murashkindf707e42016-02-02 16:56:50 -08004843 EnsureSkipAccessChecksMethods(c);
Mathieu Chartier8502f722016-06-08 15:09:08 -07004844 self->AssertNoPendingException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07004845 return true;
4846 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004847 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004848 if (!success) {
4849 if (can_init_fields && can_init_parents) {
4850 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4851 }
4852 } else {
4853 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004854 }
4855 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004856}
4857
Mathieu Chartiere401d142015-04-22 13:56:20 -07004858void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class,
4859 mirror::Class* new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07004860 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004861 for (ArtField& field : new_class->GetIFields()) {
4862 if (field.GetDeclaringClass() == temp_class) {
4863 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004864 }
4865 }
4866
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07004867 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004868 for (ArtField& field : new_class->GetSFields()) {
4869 if (field.GetDeclaringClass() == temp_class) {
4870 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004871 }
4872 }
4873
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07004874 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07004875 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08004876 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004877 if (method.GetDeclaringClass() == temp_class) {
4878 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004879 }
4880 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07004881
4882 // Make sure the remembered set and mod-union tables know that we updated some of the native
4883 // roots.
4884 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004885}
4886
Mathieu Chartier5b830502016-03-02 10:30:23 -08004887void ClassLinker::RegisterClassLoader(mirror::ClassLoader* class_loader) {
4888 CHECK(class_loader->GetAllocator() == nullptr);
4889 CHECK(class_loader->GetClassTable() == nullptr);
4890 Thread* const self = Thread::Current();
4891 ClassLoaderData data;
4892 data.weak_root = self->GetJniEnv()->vm->AddWeakGlobalRef(self, class_loader);
4893 // Create and set the class table.
4894 data.class_table = new ClassTable;
4895 class_loader->SetClassTable(data.class_table);
4896 // Create and set the linear allocator.
4897 data.allocator = Runtime::Current()->CreateLinearAlloc();
4898 class_loader->SetAllocator(data.allocator);
4899 // Add to the list so that we know to free the data later.
4900 class_loaders_.push_back(data);
4901}
4902
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004903ClassTable* ClassLinker::InsertClassTableForClassLoader(mirror::ClassLoader* class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07004904 if (class_loader == nullptr) {
4905 return &boot_class_table_;
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004906 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07004907 ClassTable* class_table = class_loader->GetClassTable();
4908 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08004909 RegisterClassLoader(class_loader);
4910 class_table = class_loader->GetClassTable();
4911 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004912 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004913 return class_table;
4914}
4915
4916ClassTable* ClassLinker::ClassTableForClassLoader(mirror::ClassLoader* class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07004917 return class_loader == nullptr ? &boot_class_table_ : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004918}
4919
Andreas Gampe542451c2016-07-26 09:02:02 -07004920static ImTable* FindSuperImt(mirror::Class* klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004921 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004922 while (klass->HasSuperClass()) {
4923 klass = klass->GetSuperClass();
4924 if (klass->ShouldHaveImt()) {
4925 return klass->GetImt(pointer_size);
4926 }
4927 }
4928 return nullptr;
4929}
4930
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004931bool ClassLinker::LinkClass(Thread* self,
4932 const char* descriptor,
4933 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004934 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004935 MutableHandle<mirror::Class>* h_new_class_out) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004936 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004937
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004938 if (!LinkSuperClass(klass)) {
4939 return false;
4940 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004941 ArtMethod* imt_data[ImTable::kSize];
4942 // If there are any new conflicts compared to super class.
4943 bool new_conflict = false;
4944 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
4945 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004946 return false;
4947 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004948 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004949 return false;
4950 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004951 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004952 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004953 return false;
4954 }
4955 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004956 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004957
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004958 ImTable* imt = nullptr;
4959 if (klass->ShouldHaveImt()) {
4960 // If there are any new conflicts compared to the super class we can not make a copy. There
4961 // can be cases where both will have a conflict method at the same slot without having the same
4962 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
4963 // will possibly create a table that is incorrect for either of the classes.
4964 // Same IMT with new_conflict does not happen very often.
4965 if (!new_conflict) {
4966 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
4967 if (super_imt != nullptr) {
4968 bool imt_equals = true;
4969 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
4970 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
4971 }
4972 if (imt_equals) {
4973 imt = super_imt;
4974 }
4975 }
4976 }
4977 if (imt == nullptr) {
4978 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
4979 imt = reinterpret_cast<ImTable*>(
4980 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
4981 if (imt == nullptr) {
4982 return false;
4983 }
4984 imt->Populate(imt_data, image_pointer_size_);
4985 }
4986 }
4987
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004988 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4989 // We don't need to retire this class as it has no embedded tables or it was created the
4990 // correct size during class linker initialization.
4991 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4992
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004993 if (klass->ShouldHaveEmbeddedVTable()) {
4994 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004995 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004996 if (klass->ShouldHaveImt()) {
4997 klass->SetImt(imt, image_pointer_size_);
4998 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004999 // This will notify waiters on klass that saw the not yet resolved
5000 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07005001 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005002 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005003 } else {
5004 CHECK(!klass->IsResolved());
5005 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005006 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005007 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005008 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5009 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5010 // may not see any references to the target space and clean the card for a class if another
5011 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005012 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005013 klass->SetSFieldsPtrUnchecked(nullptr);
5014 klass->SetIFieldsPtrUnchecked(nullptr);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005015 if (UNLIKELY(h_new_class.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005016 self->AssertPendingOOMException();
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07005017 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005018 return false;
5019 }
5020
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005021 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5022 ObjectLock<mirror::Class> lock(self, h_new_class);
5023 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005024
5025 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005026 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005027 mirror::ClassLoader* const class_loader = h_new_class.Get()->GetClassLoader();
5028 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
5029 mirror::Class* existing = table->UpdateClass(descriptor, h_new_class.Get(),
5030 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005031 if (class_loader != nullptr) {
5032 // We updated the class in the class table, perform the write barrier so that the GC knows
5033 // about the change.
5034 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
5035 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005036 CHECK_EQ(existing, klass.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005037 if (log_new_class_table_roots_) {
5038 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5039 }
5040 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005041
5042 // This will notify waiters on temp class that saw the not yet resolved class in the
5043 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07005044 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005045
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005046 CHECK_EQ(h_new_class->GetStatus(), mirror::Class::kStatusResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005047 // This will notify waiters on new_class that saw the not yet resolved
5048 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005049 mirror::Class::SetStatus(h_new_class, mirror::Class::kStatusResolved, self);
5050 // Return the new class.
5051 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005052 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005053 return true;
5054}
5055
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005056static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
5057 size_t* virtual_methods,
5058 size_t* direct_methods,
5059 size_t* static_fields,
5060 size_t* instance_fields) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005061 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
5062
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005063 while (dex_data.HasNextStaticField()) {
5064 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08005065 (*static_fields)++;
5066 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005067 while (dex_data.HasNextInstanceField()) {
5068 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08005069 (*instance_fields)++;
5070 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005071 while (dex_data.HasNextDirectMethod()) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005072 (*direct_methods)++;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005073 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08005074 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005075 while (dex_data.HasNextVirtualMethod()) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005076 (*virtual_methods)++;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005077 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08005078 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005079 DCHECK(!dex_data.HasNext());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005080}
5081
5082static void DumpClass(std::ostream& os,
5083 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
5084 const char* suffix) {
5085 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
5086 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
5087 os << " Static fields:\n";
5088 while (dex_data.HasNextStaticField()) {
5089 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
5090 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
5091 dex_data.Next();
5092 }
5093 os << " Instance fields:\n";
5094 while (dex_data.HasNextInstanceField()) {
5095 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
5096 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
5097 dex_data.Next();
5098 }
5099 os << " Direct methods:\n";
5100 while (dex_data.HasNextDirectMethod()) {
5101 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
5102 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
5103 dex_data.Next();
5104 }
5105 os << " Virtual methods:\n";
5106 while (dex_data.HasNextVirtualMethod()) {
5107 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
5108 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
5109 dex_data.Next();
5110 }
5111}
5112
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005113static std::string DumpClasses(const DexFile& dex_file1,
5114 const DexFile::ClassDef& dex_class_def1,
5115 const DexFile& dex_file2,
5116 const DexFile::ClassDef& dex_class_def2) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005117 std::ostringstream os;
5118 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
5119 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
5120 return os.str();
5121}
5122
5123
5124// Very simple structural check on whether the classes match. Only compares the number of
5125// methods and fields.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005126static bool SimpleStructuralCheck(const DexFile& dex_file1,
5127 const DexFile::ClassDef& dex_class_def1,
5128 const DexFile& dex_file2,
5129 const DexFile::ClassDef& dex_class_def2,
Andreas Gampefd9eb392014-11-06 16:52:58 -08005130 std::string* error_msg) {
5131 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
5132 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
5133
5134 // Counters for current dex file.
5135 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005136 CountMethodsAndFields(dex_data1,
5137 &dex_virtual_methods1,
5138 &dex_direct_methods1,
5139 &dex_static_fields1,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005140 &dex_instance_fields1);
Andreas Gampefd9eb392014-11-06 16:52:58 -08005141 // Counters for compile-time dex file.
5142 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005143 CountMethodsAndFields(dex_data2,
5144 &dex_virtual_methods2,
5145 &dex_direct_methods2,
5146 &dex_static_fields2,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005147 &dex_instance_fields2);
Andreas Gampefd9eb392014-11-06 16:52:58 -08005148
5149 if (dex_virtual_methods1 != dex_virtual_methods2) {
5150 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005151 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s",
5152 dex_virtual_methods1,
5153 dex_virtual_methods2,
5154 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005155 return false;
5156 }
5157 if (dex_direct_methods1 != dex_direct_methods2) {
5158 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005159 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s",
5160 dex_direct_methods1,
5161 dex_direct_methods2,
5162 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005163 return false;
5164 }
5165 if (dex_static_fields1 != dex_static_fields2) {
5166 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005167 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s",
5168 dex_static_fields1,
5169 dex_static_fields2,
5170 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005171 return false;
5172 }
5173 if (dex_instance_fields1 != dex_instance_fields2) {
5174 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005175 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s",
5176 dex_instance_fields1,
5177 dex_instance_fields2,
5178 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08005179 return false;
5180 }
5181
5182 return true;
5183}
5184
5185// Checks whether a the super-class changed from what we had at compile-time. This would
5186// invalidate quickening.
5187static bool CheckSuperClassChange(Handle<mirror::Class> klass,
5188 const DexFile& dex_file,
5189 const DexFile::ClassDef& class_def,
5190 mirror::Class* super_class)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005191 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08005192 // Check for unexpected changes in the superclass.
5193 // Quick check 1) is the super_class class-loader the boot class loader? This always has
5194 // precedence.
5195 if (super_class->GetClassLoader() != nullptr &&
5196 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
5197 // which is implied by different dex cache.
5198 klass->GetDexCache() != super_class->GetDexCache()) {
5199 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
5200 // definition for the super-class, and (b) the files are in separate oat files. The oat files
5201 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
Richard Uhler07b3c232015-03-31 15:57:54 -07005202 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
5203 const OatFile* class_oat_file = nullptr;
5204 if (class_oat_dex_file != nullptr) {
5205 class_oat_file = class_oat_dex_file->GetOatFile();
5206 }
5207
Andreas Gampefd9eb392014-11-06 16:52:58 -08005208 if (class_oat_file != nullptr) {
Richard Uhler07b3c232015-03-31 15:57:54 -07005209 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
5210 const OatFile* loaded_super_oat_file = nullptr;
5211 if (loaded_super_oat_dex_file != nullptr) {
5212 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
5213 }
5214
Andreas Gampefd9eb392014-11-06 16:52:58 -08005215 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
5216 // Now check (a).
5217 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
5218 if (super_class_def != nullptr) {
5219 // Uh-oh, we found something. Do our check.
5220 std::string error_msg;
5221 if (!SimpleStructuralCheck(dex_file, *super_class_def,
5222 super_class->GetDexFile(), *super_class->GetClassDef(),
5223 &error_msg)) {
5224 // Print a warning to the log. This exception might be caught, e.g., as common in test
5225 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
5226 // only save the type of the exception.
5227 LOG(WARNING) << "Incompatible structural change detected: " <<
5228 StringPrintf(
5229 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
5230 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
5231 class_oat_file->GetLocation().c_str(),
5232 loaded_super_oat_file->GetLocation().c_str(),
5233 error_msg.c_str());
5234 ThrowIncompatibleClassChangeError(klass.Get(),
5235 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
5236 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
5237 class_oat_file->GetLocation().c_str(),
5238 loaded_super_oat_file->GetLocation().c_str(),
5239 error_msg.c_str());
5240 return false;
5241 }
5242 }
5243 }
5244 }
5245 }
5246 return true;
5247}
5248
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005249bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005250 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005251 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
5252 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005253 if (super_class_idx != DexFile::kDexNoIndex16) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005254 // Check that a class does not inherit from itself directly.
5255 //
5256 // TODO: This is a cheap check to detect the straightforward case
5257 // of a class extending itself (b/28685551), but we should do a
5258 // proper cycle detection on loaded classes, to detect all cases
5259 // of class circularity errors (b/28830038).
5260 if (super_class_idx == class_def.class_idx_) {
5261 ThrowClassCircularityError(klass.Get(),
5262 "Class %s extends itself",
5263 PrettyDescriptor(klass.Get()).c_str());
5264 return false;
5265 }
5266
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005267 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005268 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005269 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005270 return false;
5271 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005272 // Verify
5273 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005274 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08005275 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005276 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005277 return false;
5278 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005279 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005280 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08005281
5282 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
5283 DCHECK(Thread::Current()->IsExceptionPending());
5284 return false;
5285 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005286 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07005287 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005288 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005289 for (size_t i = 0; i < interfaces->Size(); i++) {
5290 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005291 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005292 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005293 DCHECK(Thread::Current()->IsExceptionPending());
5294 return false;
5295 }
5296 // Verify
5297 if (!klass->CanAccess(interface)) {
5298 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005299 ThrowIllegalAccessError(klass.Get(),
5300 "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08005301 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005302 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005303 return false;
5304 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005305 }
5306 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005307 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07005308 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005309 return true;
5310}
5311
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005312bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005313 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005314 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005315 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005316 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005317 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005318 return false;
5319 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005320 return true;
5321 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005322 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005323 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
5324 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005325 return false;
5326 }
5327 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07005328 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005329 ThrowIncompatibleClassChangeError(klass.Get(),
5330 "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08005331 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005332 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005333 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005334 return false;
5335 }
5336 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005337 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08005338 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005339 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005340 return false;
5341 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005342
Brian Carlstromf3632832014-05-20 15:36:53 -07005343 // Inherit kAccClassIsFinalizable from the superclass in case this
5344 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005345 if (super->IsFinalizable()) {
5346 klass->SetFinalizable();
5347 }
5348
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005349 // Inherit class loader flag form super class.
5350 if (super->IsClassLoaderClass()) {
5351 klass->SetClassLoaderClass();
5352 }
5353
Elliott Hughes2da50362011-10-10 16:57:08 -07005354 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005355 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005356 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005357 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005358 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005359 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005360 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07005361 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005362 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005363 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005364 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005365 return false;
5366 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005367
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005368 if (kIsDebugBuild) {
5369 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005370 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005371 CHECK(super->IsResolved());
5372 super = super->GetSuperClass();
5373 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005374 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005375 return true;
5376}
5377
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005378// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005379bool ClassLinker::LinkMethods(Thread* self,
5380 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005381 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005382 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005383 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005384 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005385 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5386 // need to have default methods be in the virtuals array of each class but we don't set that up
5387 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07005388 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07005389 // Link virtual methods then interface methods.
5390 // We set up the interface lookup table first because we need it to determine if we need to update
5391 // any vtable entries with new default method implementations.
5392 return SetupInterfaceLookupTable(self, klass, interfaces)
5393 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005394 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005395}
5396
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005397// Comparator for name and signature of a method, used in finding overriding methods. Implementation
5398// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
5399// caches in the implementation below.
5400class MethodNameAndSignatureComparator FINAL : public ValueObject {
5401 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005402 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005403 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005404 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
5405 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005406 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
5407 }
5408
5409 const char* GetName() {
5410 if (name_ == nullptr) {
5411 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
5412 }
5413 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005414 }
5415
Mathieu Chartiere401d142015-04-22 13:56:20 -07005416 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005417 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005418 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
5419 const DexFile* other_dex_file = other->GetDexFile();
5420 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
5421 if (dex_file_ == other_dex_file) {
5422 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
5423 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005424 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005425 uint32_t other_name_len;
5426 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
5427 &other_name_len);
5428 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
5429 return false;
5430 }
5431 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
5432 }
5433
5434 private:
5435 // Dex file for the method to compare against.
5436 const DexFile* const dex_file_;
5437 // MethodId for the method to compare against.
5438 const DexFile::MethodId* const mid_;
5439 // Lazily computed name from the dex file's strings.
5440 const char* name_;
5441 // Lazily computed name length.
5442 uint32_t name_len_;
5443};
5444
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005445class LinkVirtualHashTable {
5446 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005447 LinkVirtualHashTable(Handle<mirror::Class> klass,
5448 size_t hash_size,
5449 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07005450 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005451 : klass_(klass),
5452 hash_size_(hash_size),
5453 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07005454 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005455 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
5456 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005457
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005458 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005459 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
5460 virtual_method_index, image_pointer_size_);
5461 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005462 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005463 uint32_t index = hash % hash_size_;
5464 // Linear probe until we have an empty slot.
5465 while (hash_table_[index] != invalid_index_) {
5466 if (++index == hash_size_) {
5467 index = 0;
5468 }
5469 }
5470 hash_table_[index] = virtual_method_index;
5471 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005472
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005473 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005474 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005475 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005476 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005477 size_t index = hash % hash_size_;
5478 while (true) {
5479 const uint32_t value = hash_table_[index];
5480 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
5481 // the block and can safely assume not found.
5482 if (value == invalid_index_) {
5483 break;
5484 }
5485 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005486 ArtMethod* virtual_method =
5487 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
5488 if (comparator->HasSameNameAndSignature(
5489 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005490 hash_table_[index] = removed_index_;
5491 return value;
5492 }
5493 }
5494 if (++index == hash_size_) {
5495 index = 0;
5496 }
5497 }
5498 return GetNotFoundIndex();
5499 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005500
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005501 static uint32_t GetNotFoundIndex() {
5502 return invalid_index_;
5503 }
5504
5505 private:
5506 static const uint32_t invalid_index_;
5507 static const uint32_t removed_index_;
5508
5509 Handle<mirror::Class> klass_;
5510 const size_t hash_size_;
5511 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07005512 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005513};
5514
5515const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
5516const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
5517
Andreas Gampe542451c2016-07-26 09:02:02 -07005518// b/30419309
5519#if defined(__i386__)
5520#define X86_OPTNONE __attribute__((optnone))
5521#else
5522#define X86_OPTNONE
5523#endif
5524
5525X86_OPTNONE bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07005526 Thread* self,
5527 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07005528 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005529 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07005530 if (klass->IsInterface()) {
5531 // No vtable.
5532 if (!IsUint<16>(num_virtual_methods)) {
5533 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
5534 return false;
5535 }
5536 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07005537 // Assign each method an IMT index and set the default flag.
5538 for (size_t i = 0; i < num_virtual_methods; ++i) {
5539 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5540 m->SetMethodIndex(i);
5541 if (!m->IsAbstract()) {
5542 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
5543 has_defaults = true;
5544 }
5545 }
5546 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
5547 // during initialization. This is a performance optimization. We could simply traverse the
5548 // virtual_methods_ array again during initialization.
5549 if (has_defaults) {
5550 klass->SetHasDefaultMethods();
5551 }
5552 return true;
5553 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005554 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
5555 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005556 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07005557 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07005558 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005559 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005560 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005561 if (UNLIKELY(vtable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005562 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005563 return false;
5564 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005565 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005566 vtable->SetElementPtrSize(
5567 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005568 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005569 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5570 // might give us new default methods). If no new interfaces then we can skip the rest since
5571 // the class cannot override any of the super-class's methods. This is required for
5572 // correctness since without it we might not update overridden default method vtable entries
5573 // correctly.
5574 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005575 klass->SetVTable(vtable.Get());
5576 return true;
5577 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005578 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07005579 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005580 auto* super_vtable = super_class->GetVTable();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005581 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07005582 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5583 // might give us new default methods). See comment above.
5584 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005585 klass->SetVTable(super_vtable);
5586 return true;
5587 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005588 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
5589 super_vtable->CopyOf(self, max_count)));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005590 if (UNLIKELY(vtable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005591 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005592 return false;
5593 }
Ian Rogersa436fde2013-08-27 23:34:06 -07005594 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005595 // How the algorithm works:
5596 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
5597 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
5598 // method which has not been matched to a vtable method, and j if the virtual method at the
5599 // index overrode the super virtual method at index j.
5600 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
5601 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
5602 // the need for the initial vtable which we later shrink back down).
5603 // 3. Add non overridden methods to the end of the vtable.
5604 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07005605 // + 1 so that even if we only have new default methods we will still be able to use this hash
5606 // table (i.e. it will never have 0 size).
5607 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005608 uint32_t* hash_table_ptr;
5609 std::unique_ptr<uint32_t[]> hash_heap_storage;
5610 if (hash_table_size <= kMaxStackHash) {
5611 hash_table_ptr = reinterpret_cast<uint32_t*>(
5612 alloca(hash_table_size * sizeof(*hash_table_ptr)));
5613 } else {
5614 hash_heap_storage.reset(new uint32_t[hash_table_size]);
5615 hash_table_ptr = hash_heap_storage.get();
5616 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005617 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005618 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005619 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005620 DCHECK(klass->GetVirtualMethodDuringLinking(
5621 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005622 hash_table.Add(i);
5623 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005624 // 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 -07005625 // the hash table.
5626 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005627 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005628 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005629 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005630 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005631 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5632 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005633 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
5634 hash_index, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005635 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
5636 super_method->GetAccessFlags())) {
5637 if (super_method->IsFinal()) {
5638 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5639 PrettyMethod(virtual_method).c_str(),
5640 super_method->GetDeclaringClassDescriptor());
5641 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005642 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005643 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005644 virtual_method->SetMethodIndex(j);
5645 } else {
5646 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005647 << " would have incorrectly overridden the package-private method in "
5648 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005649 }
Alex Light9139e002015-10-09 15:59:48 -07005650 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005651 // We didn't directly override this method but we might through default methods...
5652 // Check for default method update.
5653 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07005654 switch (FindDefaultMethodImplementation(self,
5655 super_method,
5656 klass,
5657 /*out*/&default_method)) {
5658 case DefaultMethodSearchResult::kDefaultConflict: {
5659 // A conflict was found looking for default methods. Note this (assuming it wasn't
5660 // pre-existing) in the translations map.
5661 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
5662 // Don't generate another conflict method to reduce memory use as an optimization.
5663 default_translations->insert(
5664 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
5665 }
5666 break;
5667 }
5668 case DefaultMethodSearchResult::kAbstractFound: {
5669 // No conflict but method is abstract.
5670 // We note that this vtable entry must be made abstract.
5671 if (UNLIKELY(!super_method->IsAbstract())) {
5672 default_translations->insert(
5673 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
5674 }
5675 break;
5676 }
5677 case DefaultMethodSearchResult::kDefaultFound: {
5678 if (UNLIKELY(super_method->IsDefaultConflicting() ||
5679 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
5680 // Found a default method implementation that is new.
5681 // TODO Refactor this add default methods to virtuals here and not in
5682 // LinkInterfaceMethods maybe.
5683 // The problem is default methods might override previously present
5684 // default-method or miranda-method vtable entries from the superclass.
5685 // Unfortunately we need these to be entries in this class's virtuals. We do not
5686 // give these entries there until LinkInterfaceMethods so we pass this map around
5687 // to let it know which vtable entries need to be updated.
5688 // Make a note that vtable entry j must be updated, store what it needs to be updated
5689 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
5690 // then.
5691 default_translations->insert(
5692 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
5693 VLOG(class_linker) << "Method " << PrettyMethod(super_method)
5694 << " overridden by default " << PrettyMethod(default_method)
5695 << " in " << PrettyClass(klass.Get());
5696 }
5697 break;
5698 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005699 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005700 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005701 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005702 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07005703 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005704 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005705 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005706 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5707 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07005708 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005709 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005710 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005711 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005712 local_method->SetMethodIndex(actual_count);
5713 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005714 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005715 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005716 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005717 return false;
5718 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005719 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005720 CHECK_LE(actual_count, max_count);
5721 if (actual_count < max_count) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005722 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005723 if (UNLIKELY(vtable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005724 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005725 return false;
5726 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005727 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005728 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005729 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005730 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005731 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005732 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5733 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005734 return false;
5735 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005736 auto* vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005737 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005738 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005739 return false;
5740 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005741 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005742 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5743 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005744 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005745 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005746 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005747 }
5748 return true;
5749}
5750
Alex Light9139e002015-10-09 15:59:48 -07005751// Determine if the given iface has any subinterface in the given list that declares the method
5752// specified by 'target'.
5753//
5754// Arguments
5755// - self: The thread we are running on
5756// - target: A comparator that will match any method that overrides the method we are checking for
5757// - iftable: The iftable we are searching for an overriding method on.
5758// - ifstart: The index of the interface we are checking to see if anything overrides
5759// - iface: The interface we are checking to see if anything overrides.
5760// - image_pointer_size:
5761// The image pointer size.
5762//
5763// Returns
5764// - True: There is some method that matches the target comparator defined in an interface that
5765// is a subtype of iface.
5766// - False: There is no method that matches the target comparator in any interface that is a subtype
5767// of iface.
5768static bool ContainsOverridingMethodOf(Thread* self,
5769 MethodNameAndSignatureComparator& target,
5770 Handle<mirror::IfTable> iftable,
5771 size_t ifstart,
5772 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07005773 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005774 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07005775 DCHECK(self != nullptr);
5776 DCHECK(iface.Get() != nullptr);
5777 DCHECK(iftable.Get() != nullptr);
5778 DCHECK_GE(ifstart, 0u);
5779 DCHECK_LT(ifstart, iftable->Count());
5780 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
5781 DCHECK(iface->IsInterface());
5782
5783 size_t iftable_count = iftable->Count();
5784 StackHandleScope<1> hs(self);
5785 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
5786 for (size_t k = ifstart + 1; k < iftable_count; k++) {
5787 // Skip ifstart since our current interface obviously cannot override itself.
5788 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08005789 // Iterate through every method on this interface. The order does not matter.
5790 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07005791 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08005792 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07005793 // Check if the i'th interface is a subtype of this one.
5794 if (iface->IsAssignableFrom(current_iface.Get())) {
5795 return true;
5796 }
5797 break;
5798 }
5799 }
5800 }
5801 return false;
5802}
5803
Alex Lighteb7c1442015-08-31 13:17:42 -07005804// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07005805// out_default_method and returns kDefaultFound on success. If no default method was found return
5806// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
5807// default_method conflict) it will return kDefaultConflict.
5808ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
5809 Thread* self,
5810 ArtMethod* target_method,
5811 Handle<mirror::Class> klass,
5812 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07005813 DCHECK(self != nullptr);
5814 DCHECK(target_method != nullptr);
5815 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07005816
5817 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07005818
5819 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
5820 // table. This lets us walk the table backwards when searching for default methods. The first one
5821 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
5822 // track of it and then continue checking all other interfaces, since we need to throw an error if
5823 // we encounter conflicting default method implementations (one is not a subtype of the other).
5824 //
5825 // The order of unrelated interfaces does not matter and is not defined.
5826 size_t iftable_count = klass->GetIfTableCount();
5827 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07005828 // No interfaces. We have already reset out to null so just return kAbstractFound.
5829 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07005830 }
5831
Alex Light9139e002015-10-09 15:59:48 -07005832 StackHandleScope<3> hs(self);
5833 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07005834 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07005835 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07005836 MethodNameAndSignatureComparator target_name_comparator(
5837 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
5838 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07005839 for (size_t k = iftable_count; k != 0; ) {
5840 --k;
5841
Alex Lighteb7c1442015-08-31 13:17:42 -07005842 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07005843
5844 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08005845 // Iterate through every declared method on this interface. The order does not matter.
5846 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
5847 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07005848 // Skip abstract methods and methods with different names.
5849 if (current_method->IsAbstract() ||
5850 !target_name_comparator.HasSameNameAndSignature(
5851 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
5852 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07005853 } else if (!current_method->IsPublic()) {
5854 // The verifier should have caught the non-public method for dex version 37. Just warn and
5855 // skip it since this is from before default-methods so we don't really need to care that it
5856 // has code.
5857 LOG(WARNING) << "Interface method " << PrettyMethod(current_method) << " is not public! "
5858 << "This will be a fatal error in subsequent versions of android. "
5859 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07005860 }
Alex Light9139e002015-10-09 15:59:48 -07005861 if (UNLIKELY(chosen_iface.Get() != nullptr)) {
5862 // We have multiple default impls of the same method. This is a potential default conflict.
5863 // We need to check if this possibly conflicting method is either a superclass of the chosen
5864 // default implementation or is overridden by a non-default interface method. In either case
5865 // there is no conflict.
5866 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
5867 !ContainsOverridingMethodOf(self,
5868 target_name_comparator,
5869 iftable,
5870 k,
5871 iface,
5872 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00005873 VLOG(class_linker) << "Conflicting default method implementations found: "
5874 << PrettyMethod(current_method) << " and "
5875 << PrettyMethod(*out_default_method) << " in class "
5876 << PrettyClass(klass.Get()) << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07005877 *out_default_method = nullptr;
5878 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07005879 } else {
5880 break; // Continue checking at the next interface.
5881 }
5882 } else {
Alex Light9139e002015-10-09 15:59:48 -07005883 // chosen_iface == null
5884 if (!ContainsOverridingMethodOf(self,
5885 target_name_comparator,
5886 iftable,
5887 k,
5888 iface,
5889 image_pointer_size_)) {
5890 // Don't set this as the chosen interface if something else is overriding it (because that
5891 // other interface would be potentially chosen instead if it was default). If the other
5892 // interface was abstract then we wouldn't select this interface as chosen anyway since
5893 // the abstract method masks it.
5894 *out_default_method = current_method;
5895 chosen_iface.Assign(iface.Get());
5896 // We should now finish traversing the graph to find if we have default methods that
5897 // conflict.
5898 } else {
5899 VLOG(class_linker) << "A default method '" << PrettyMethod(current_method) << "' was "
5900 << "skipped because it was overridden by an abstract method in a "
5901 << "subinterface on class '" << PrettyClass(klass.Get()) << "'";
5902 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005903 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005904 break;
5905 }
5906 }
Alex Light9139e002015-10-09 15:59:48 -07005907 if (*out_default_method != nullptr) {
5908 VLOG(class_linker) << "Default method '" << PrettyMethod(*out_default_method) << "' selected "
5909 << "as the implementation for '" << PrettyMethod(target_method) << "' "
5910 << "in '" << PrettyClass(klass.Get()) << "'";
5911 return DefaultMethodSearchResult::kDefaultFound;
5912 } else {
5913 return DefaultMethodSearchResult::kAbstractFound;
5914 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005915}
5916
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07005917ArtMethod* ClassLinker::AddMethodToConflictTable(mirror::Class* klass,
5918 ArtMethod* conflict_method,
5919 ArtMethod* interface_method,
5920 ArtMethod* method,
5921 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07005922 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07005923 Runtime* const runtime = Runtime::Current();
5924 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
5925 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
5926
5927 // Create a new entry if the existing one is the shared conflict method.
5928 ArtMethod* new_conflict_method = new_entry
5929 ? runtime->CreateImtConflictMethod(linear_alloc)
5930 : conflict_method;
5931
5932 // Allocate a new table. Note that we will leak this table at the next conflict,
5933 // but that's a tradeoff compared to making the table fixed size.
5934 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07005935 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
5936 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07005937 if (data == nullptr) {
5938 LOG(ERROR) << "Failed to allocate conflict table";
5939 return conflict_method;
5940 }
5941 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
5942 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07005943 method,
5944 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07005945
5946 // Do a fence to ensure threads see the data in the table before it is assigned
5947 // to the conflict method.
5948 // Note that there is a race in the presence of multiple threads and we may leak
5949 // memory from the LinearAlloc, but that's a tradeoff compared to using
5950 // atomic operations.
5951 QuasiAtomic::ThreadFenceRelease();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07005952 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07005953 return new_conflict_method;
5954}
5955
5956void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
5957 ArtMethod* imt_conflict_method,
5958 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005959 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07005960 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005961 // Place method in imt if entry is empty, place conflict otherwise.
5962 if (*imt_ref == unimplemented_method) {
5963 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00005964 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005965 // If we are not a conflict and we have the same signature and name as the imt
5966 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00005967 // Note that we have checked IsRuntimeMethod, as there may be multiple different
5968 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07005969 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07005970 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07005971 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07005972 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005973 *imt_ref = current_method;
5974 } else {
Alex Light9139e002015-10-09 15:59:48 -07005975 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005976 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07005977 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00005978 } else {
5979 // Place the default conflict method. Note that there may be an existing conflict
5980 // method in the IMT, but it could be one tailored to the super class, with a
5981 // specific ImtConflictTable.
5982 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005983 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07005984 }
5985}
5986
Mathieu Chartiercdca4762016-04-28 09:44:54 -07005987void ClassLinker::FillIMTAndConflictTables(mirror::Class* klass) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005988 DCHECK(klass->ShouldHaveImt()) << PrettyClass(klass);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07005989 DCHECK(!klass->IsTemp()) << PrettyClass(klass);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005990 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07005991 Runtime* const runtime = Runtime::Current();
5992 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
5993 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005994 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07005995 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005996 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07005997 FillIMTFromIfTable(klass->GetIfTable(),
5998 unimplemented_method,
5999 conflict_method,
6000 klass,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006001 /*create_conflict_tables*/true,
6002 /*ignore_copied_methods*/false,
6003 &new_conflict,
6004 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006005 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006006 if (!klass->ShouldHaveImt()) {
6007 return;
6008 }
6009 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6010 // we can just use the same pointer.
6011 ImTable* imt = nullptr;
6012 mirror::Class* super_class = klass->GetSuperClass();
6013 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6014 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6015 bool same = true;
6016 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6017 ArtMethod* method = imt_data[i];
6018 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6019 if (method != super_method) {
6020 bool is_conflict_table = method->IsRuntimeMethod() &&
6021 method != unimplemented_method &&
6022 method != conflict_method;
6023 // Verify conflict contents.
6024 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6025 super_method != unimplemented_method &&
6026 super_method != conflict_method;
6027 if (!is_conflict_table || !super_conflict_table) {
6028 same = false;
6029 } else {
6030 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6031 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6032 same = same && table1->Equals(table2, image_pointer_size_);
6033 }
6034 }
6035 }
6036 if (same) {
6037 imt = super_imt;
6038 }
6039 }
6040 if (imt == nullptr) {
6041 imt = klass->GetImt(image_pointer_size_);
6042 DCHECK(imt != nullptr);
6043 imt->Populate(imt_data, image_pointer_size_);
6044 } else {
6045 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006046 }
6047}
6048
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006049ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6050 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006051 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006052 void* data = linear_alloc->Alloc(Thread::Current(),
6053 ImtConflictTable::ComputeSize(count,
6054 image_pointer_size));
6055 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6056}
6057
6058ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6059 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6060}
6061
6062void ClassLinker::FillIMTFromIfTable(mirror::IfTable* if_table,
6063 ArtMethod* unimplemented_method,
6064 ArtMethod* imt_conflict_method,
6065 mirror::Class* klass,
6066 bool create_conflict_tables,
6067 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006068 /*out*/bool* new_conflict,
6069 /*out*/ArtMethod** imt) {
6070 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006071 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
6072 mirror::Class* interface = if_table->GetInterface(i);
6073 const size_t num_virtuals = interface->NumVirtualMethods();
6074 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6075 // Virtual methods can be larger than the if table methods if there are default methods.
6076 DCHECK_GE(num_virtuals, method_array_count);
6077 if (kIsDebugBuild) {
6078 if (klass->IsInterface()) {
6079 DCHECK_EQ(method_array_count, 0u);
6080 } else {
6081 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6082 }
6083 }
6084 if (method_array_count == 0) {
6085 continue;
6086 }
6087 auto* method_array = if_table->GetMethodArray(i);
6088 for (size_t j = 0; j < method_array_count; ++j) {
6089 ArtMethod* implementation_method =
6090 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6091 if (ignore_copied_methods && implementation_method->IsCopied()) {
6092 continue;
6093 }
6094 DCHECK(implementation_method != nullptr);
6095 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6096 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6097 // or interface methods in the IMT here they will not create extra conflicts since we compare
6098 // names and signatures in SetIMTRef.
6099 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006100 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006101
6102 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6103 // the same implementation method, keep track of this to avoid creating a conflict table in
6104 // this case.
6105
6106 // Conflict table size for each IMT slot.
6107 ++conflict_counts[imt_index];
6108
6109 SetIMTRef(unimplemented_method,
6110 imt_conflict_method,
6111 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006112 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006113 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006114 }
6115 }
6116
6117 if (create_conflict_tables) {
6118 // Create the conflict tables.
6119 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006120 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006121 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006122 if (imt[i] == imt_conflict_method) {
6123 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6124 if (new_table != nullptr) {
6125 ArtMethod* new_conflict_method =
6126 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6127 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6128 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006129 } else {
6130 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006131 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006132 }
6133 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006134 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006135 }
6136 }
6137
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006138 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
6139 mirror::Class* interface = if_table->GetInterface(i);
6140 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6141 // Virtual methods can be larger than the if table methods if there are default methods.
6142 if (method_array_count == 0) {
6143 continue;
6144 }
6145 auto* method_array = if_table->GetMethodArray(i);
6146 for (size_t j = 0; j < method_array_count; ++j) {
6147 ArtMethod* implementation_method =
6148 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6149 if (ignore_copied_methods && implementation_method->IsCopied()) {
6150 continue;
6151 }
6152 DCHECK(implementation_method != nullptr);
6153 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Andreas Gampe75a7db62016-09-26 12:04:26 -07006154 const uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006155 if (!imt[imt_index]->IsRuntimeMethod() ||
6156 imt[imt_index] == unimplemented_method ||
6157 imt[imt_index] == imt_conflict_method) {
6158 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006159 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006160 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6161 const size_t num_entries = table->NumEntries(image_pointer_size_);
6162 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6163 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006164 }
6165 }
6166 }
6167}
6168
Alex Lighteb7c1442015-08-31 13:17:42 -07006169// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6170// set.
6171static bool NotSubinterfaceOfAny(const std::unordered_set<mirror::Class*>& classes,
6172 mirror::Class* val)
6173 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006174 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006175 DCHECK(val != nullptr);
6176 for (auto c : classes) {
6177 if (val->IsAssignableFrom(&*c)) {
6178 return false;
6179 }
6180 }
6181 return true;
6182}
6183
6184// Fills in and flattens the interface inheritance hierarchy.
6185//
6186// By the end of this function all interfaces in the transitive closure of to_process are added to
6187// the iftable and every interface precedes all of its sub-interfaces in this list.
6188//
6189// all I, J: Interface | I <: J implies J precedes I
6190//
6191// (note A <: B means that A is a subtype of B)
6192//
6193// This returns the total number of items in the iftable. The iftable might be resized down after
6194// this call.
6195//
6196// We order this backwards so that we do not need to reorder superclass interfaces when new
6197// interfaces are added in subclass's interface tables.
6198//
6199// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6200// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6201// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6202// iftable must be large enough to hold all interfaces without changing its size.
6203static size_t FillIfTable(mirror::IfTable* iftable,
6204 size_t super_ifcount,
6205 std::vector<mirror::Class*> to_process)
6206 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006207 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006208 // This is the set of all class's already in the iftable. Used to make checking if a class has
6209 // already been added quicker.
6210 std::unordered_set<mirror::Class*> classes_in_iftable;
6211 // The first super_ifcount elements are from the superclass. We note that they are already added.
6212 for (size_t i = 0; i < super_ifcount; i++) {
6213 mirror::Class* iface = iftable->GetInterface(i);
6214 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6215 classes_in_iftable.insert(iface);
6216 }
6217 size_t filled_ifcount = super_ifcount;
6218 for (mirror::Class* interface : to_process) {
6219 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6220 // At this point in the loop current-iface-list has the invariant that:
6221 // for every pair of interfaces I,J within it:
6222 // if index_of(I) < index_of(J) then I is not a subtype of J
6223
6224 // If we have already seen this element then all of its super-interfaces must already be in the
6225 // current-iface-list so we can skip adding it.
6226 if (!ContainsElement(classes_in_iftable, interface)) {
6227 // We haven't seen this interface so add all of its super-interfaces onto the
6228 // current-iface-list, skipping those already on it.
6229 int32_t ifcount = interface->GetIfTableCount();
6230 for (int32_t j = 0; j < ifcount; j++) {
6231 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
6232 if (!ContainsElement(classes_in_iftable, super_interface)) {
6233 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6234 classes_in_iftable.insert(super_interface);
6235 iftable->SetInterface(filled_ifcount, super_interface);
6236 filled_ifcount++;
6237 }
6238 }
6239 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6240 // Place this interface onto the current-iface-list after all of its super-interfaces.
6241 classes_in_iftable.insert(interface);
6242 iftable->SetInterface(filled_ifcount, interface);
6243 filled_ifcount++;
6244 } else if (kIsDebugBuild) {
6245 // Check all super-interfaces are already in the list.
6246 int32_t ifcount = interface->GetIfTableCount();
6247 for (int32_t j = 0; j < ifcount; j++) {
6248 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
6249 DCHECK(ContainsElement(classes_in_iftable, super_interface))
6250 << "Iftable does not contain " << PrettyClass(super_interface)
6251 << ", a superinterface of " << PrettyClass(interface);
6252 }
6253 }
6254 }
6255 if (kIsDebugBuild) {
6256 // Check that the iftable is ordered correctly.
6257 for (size_t i = 0; i < filled_ifcount; i++) {
6258 mirror::Class* if_a = iftable->GetInterface(i);
6259 for (size_t j = i + 1; j < filled_ifcount; j++) {
6260 mirror::Class* if_b = iftable->GetInterface(j);
6261 // !(if_a <: if_b)
6262 CHECK(!if_b->IsAssignableFrom(if_a))
6263 << "Bad interface order: " << PrettyClass(if_a) << " (index " << i << ") extends "
6264 << PrettyClass(if_b) << " (index " << j << ") and so should be after it in the "
6265 << "interface list.";
6266 }
6267 }
6268 }
6269 return filled_ifcount;
6270}
6271
6272bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6273 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6274 StackHandleScope<1> hs(self);
6275 const size_t super_ifcount =
6276 klass->HasSuperClass() ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006277 const bool have_interfaces = interfaces.Get() != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006278 const size_t num_interfaces =
6279 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006280 if (num_interfaces == 0) {
6281 if (super_ifcount == 0) {
6282 // Class implements no interfaces.
6283 DCHECK_EQ(klass->GetIfTableCount(), 0);
6284 DCHECK(klass->GetIfTable() == nullptr);
6285 return true;
6286 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006287 // Class implements same interfaces as parent, are any of these not marker interfaces?
6288 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08006289 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006290 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006291 if (super_iftable->GetMethodArrayCount(i) > 0) {
6292 has_non_marker_interface = true;
6293 break;
6294 }
6295 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006296 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006297 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006298 klass->SetIfTable(super_iftable);
6299 return true;
6300 }
6301 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006302 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006303 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006304 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006305 mirror::Class* interface = have_interfaces
6306 ? interfaces->GetWithoutChecks(i)
6307 : mirror::Class::GetDirectInterface(self, klass, i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006308 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006309 if (UNLIKELY(!interface->IsInterface())) {
6310 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006311 ThrowIncompatibleClassChangeError(klass.Get(),
6312 "Class %s implements non-interface class %s",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006313 PrettyDescriptor(klass.Get()).c_str(),
6314 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6315 return false;
6316 }
6317 ifcount += interface->GetIfTableCount();
6318 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006319 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006320 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006321 if (UNLIKELY(iftable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006322 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006323 return false;
6324 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006325 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006326 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08006327 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006328 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08006329 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006330 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006331 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006332 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006333
6334 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6335 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6336 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006337 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006338
6339 size_t new_ifcount;
6340 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006341 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Alex Lighteb7c1442015-08-31 13:17:42 -07006342 std::vector<mirror::Class*> to_add;
6343 for (size_t i = 0; i < num_interfaces; i++) {
6344 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
6345 mirror::Class::GetDirectInterface(self, klass, i);
6346 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006347 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006348
6349 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006350 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006351
Ian Rogers7b078e82014-09-10 14:44:24 -07006352 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006353
Ian Rogersb52b01a2012-01-12 17:01:38 -08006354 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07006355 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006356 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006357 iftable.Assign(down_cast<mirror::IfTable*>(
Alex Lighteb7c1442015-08-31 13:17:42 -07006358 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006359 if (UNLIKELY(iftable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006360 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006361 return false;
6362 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006363 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08006364 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006365 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006366 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006367 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07006368 return true;
6369}
6370
Alex Light1f3925d2016-09-07 12:04:20 -07006371// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
6372// of methods must be unique.
6373static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
6374 return nullptr;
6375}
6376
6377template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07006378static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07006379 const ScopedArenaVector<ArtMethod*>& list,
6380 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006381 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006382 for (ArtMethod* method : list) {
6383 if (cmp.HasSameNameAndSignature(method)) {
6384 return method;
6385 }
6386 }
Alex Light1f3925d2016-09-07 12:04:20 -07006387 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07006388}
6389
Alex Light1f3925d2016-09-07 12:04:20 -07006390// Check that all vtable entries are present in this class's virtuals or are the same as a
6391// superclasses vtable entry.
6392static void CheckClassOwnsVTableEntries(Thread* self,
6393 Handle<mirror::Class> klass,
6394 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006395 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07006396 StackHandleScope<2> hs(self);
6397 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6398 mirror::Class* super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
6399 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
6400 int32_t super_vtable_length = (superclass.Get() != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006401 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6402 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6403 CHECK(m != nullptr);
6404
Alex Light1f3925d2016-09-07 12:04:20 -07006405 CHECK_EQ(m->GetMethodIndexDuringLinking(), i)
6406 << PrettyMethod(m) << " has an unexpected method index for its spot in the vtable for class"
6407 << PrettyClass(klass.Get());
Alex Lighte64300b2015-12-15 15:02:47 -08006408 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6409 auto is_same_method = [m] (const ArtMethod& meth) {
6410 return &meth == m;
6411 };
6412 CHECK((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6413 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())
Alex Light1f3925d2016-09-07 12:04:20 -07006414 << PrettyMethod(m) << " does not seem to be owned by current class "
6415 << PrettyClass(klass.Get()) << " or any of its superclasses!";
Alex Lighte64300b2015-12-15 15:02:47 -08006416 }
6417}
6418
Alex Light1f3925d2016-09-07 12:04:20 -07006419// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
6420// method is overridden in a subclass.
6421static void CheckVTableHasNoDuplicates(Thread* self,
6422 Handle<mirror::Class> klass,
6423 PointerSize pointer_size)
6424 REQUIRES_SHARED(Locks::mutator_lock_) {
6425 StackHandleScope<1> hs(self);
6426 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6427 int32_t num_entries = vtable->GetLength();
6428 for (int32_t i = 0; i < num_entries; i++) {
6429 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6430 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe).
6431 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6432 vtable_entry->GetAccessFlags())) {
6433 continue;
6434 }
6435 MethodNameAndSignatureComparator name_comparator(
6436 vtable_entry->GetInterfaceMethodIfProxy(pointer_size));
6437 for (int32_t j = i+1; j < num_entries; j++) {
6438 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size);
6439 CHECK(vtable_entry != other_entry &&
6440 !name_comparator.HasSameNameAndSignature(
6441 other_entry->GetInterfaceMethodIfProxy(pointer_size)))
6442 << "vtable entries " << i << " and " << j << " are identical for "
6443 << PrettyClass(klass.Get()) << " in method " << PrettyMethod(vtable_entry) << " and "
6444 << PrettyMethod(other_entry);
6445 }
6446 }
6447}
6448
6449static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
6450 REQUIRES_SHARED(Locks::mutator_lock_) {
6451 CheckClassOwnsVTableEntries(self, klass, pointer_size);
6452 CheckVTableHasNoDuplicates(self, klass, pointer_size);
6453}
6454
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006455void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
6456 ArtMethod* unimplemented_method,
6457 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006458 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006459 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07006460 DCHECK(klass->HasSuperClass());
6461 mirror::Class* super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006462 if (super_class->ShouldHaveImt()) {
6463 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6464 for (size_t i = 0; i < ImTable::kSize; ++i) {
6465 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07006466 }
6467 } else {
6468 // No imt in the super class, need to reconstruct from the iftable.
6469 mirror::IfTable* if_table = super_class->GetIfTable();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006470 if (if_table != nullptr) {
6471 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006472 FillIMTFromIfTable(if_table,
6473 unimplemented_method,
6474 imt_conflict_method,
6475 klass.Get(),
6476 /*create_conflict_table*/false,
6477 /*ignore_copied_methods*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006478 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006479 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07006480 }
6481 }
6482}
6483
6484// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006485bool ClassLinker::LinkInterfaceMethods(
6486 Thread* self,
6487 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006488 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006489 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07006490 ArtMethod** out_imt) {
6491 StackHandleScope<3> hs(self);
6492 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07006493
6494 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07006495 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07006496 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07006497 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6498 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
6499 const size_t method_size = ArtMethod::Size(image_pointer_size_);
6500 const size_t ifcount = klass->GetIfTableCount();
6501
6502 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
6503
Mathieu Chartiere401d142015-04-22 13:56:20 -07006504 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
6505 // the virtual methods array.
6506 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
6507 // during cross compilation.
6508 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
6509 ArenaStack stack(runtime->GetLinearAlloc()->GetArenaPool());
6510 ScopedArenaAllocator allocator(&stack);
Alex Light9139e002015-10-09 15:59:48 -07006511
6512 ScopedArenaVector<ArtMethod*> default_conflict_methods(allocator.Adapter());
Alex Light1f3925d2016-09-07 12:04:20 -07006513 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods(allocator.Adapter());
Mathieu Chartiere401d142015-04-22 13:56:20 -07006514 ScopedArenaVector<ArtMethod*> miranda_methods(allocator.Adapter());
Alex Lighteb7c1442015-08-31 13:17:42 -07006515 ScopedArenaVector<ArtMethod*> default_methods(allocator.Adapter());
Alex Light1f3925d2016-09-07 12:04:20 -07006516 ScopedArenaVector<ArtMethod*> overriding_default_methods(allocator.Adapter());
Mathieu Chartiere401d142015-04-22 13:56:20 -07006517
6518 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6519 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07006520 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006521 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07006522 const bool extend_super_iftable = has_superclass;
6523 if (has_superclass && fill_tables) {
6524 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07006525 unimplemented_method,
6526 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006527 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006528 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006529 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006530 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
6531 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07006532 if (fill_tables) {
6533 for (size_t i = 0; i < ifcount; ++i) {
6534 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6535 if (num_methods > 0) {
6536 const bool is_super = i < super_ifcount;
6537 // This is an interface implemented by a super-class. Therefore we can just copy the method
6538 // array from the superclass.
6539 const bool super_interface = is_super && extend_super_iftable;
6540 mirror::PointerArray* method_array;
6541 if (super_interface) {
6542 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
6543 DCHECK(if_table != nullptr);
6544 DCHECK(if_table->GetMethodArray(i) != nullptr);
6545 // If we are working on a super interface, try extending the existing method array.
6546 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
6547 } else {
6548 method_array = AllocPointerArray(self, num_methods);
6549 }
6550 if (UNLIKELY(method_array == nullptr)) {
6551 self->AssertPendingOOMException();
6552 return false;
6553 }
6554 iftable->SetMethodArray(i, method_array);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006555 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006556 }
6557 }
6558
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006559 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006560 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07006561 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
6562 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
6563 // they will already be null. This has the additional benefit that the declarer of a miranda
6564 // method will actually declare an abstract method.
6565 for (size_t i = ifcount; i != 0; ) {
6566 --i;
6567
6568 DCHECK_GE(i, 0u);
6569 DCHECK_LT(i, ifcount);
6570
Alex Light705ad492015-09-21 11:36:30 -07006571 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07006572 if (num_methods > 0) {
6573 StackHandleScope<2> hs2(self);
6574 const bool is_super = i < super_ifcount;
6575 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07006576 // We don't actually create or fill these tables for interfaces, we just copy some methods for
6577 // conflict methods. Just set this as nullptr in those cases.
6578 Handle<mirror::PointerArray> method_array(fill_tables
6579 ? hs2.NewHandle(iftable->GetMethodArray(i))
6580 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006581
Alex Lighte64300b2015-12-15 15:02:47 -08006582 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08006583 ScopedNullHandle<mirror::PointerArray> null_handle;
6584 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006585 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006586
Alex Light9139e002015-10-09 15:59:48 -07006587 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
6588 // and confusing. Default methods should always look through all the superclasses
6589 // because they are the last choice of an implementation. We get around this by looking
6590 // at the super-classes iftable methods (copied into method_array previously) when we are
6591 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08006592 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07006593 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08006594 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07006595 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08006596 using_virtuals = true;
6597 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
6598 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07006599 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08006600 // For a new interface, however, we need the whole vtable in case a new
6601 // interface method is implemented in the whole superclass.
6602 using_virtuals = false;
Alex Light705ad492015-09-21 11:36:30 -07006603 DCHECK(vtable.Get() != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006604 input_vtable_array = vtable;
6605 input_array_length = input_vtable_array->GetLength();
6606 }
Alex Lighte64300b2015-12-15 15:02:47 -08006607
Alex Lighteb7c1442015-08-31 13:17:42 -07006608 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08006609 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006610 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006611 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006612 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Andreas Gampe75a7db62016-09-26 12:04:26 -07006613 uint32_t imt_index = ImTable::GetImtIndex(interface_method);
Alex Lighteb7c1442015-08-31 13:17:42 -07006614 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07006615 // For each method listed in the interface's method list, find the
6616 // matching method in our class's method list. We want to favor the
6617 // subclass over the superclass, which just requires walking
6618 // back from the end of the vtable. (This only matters if the
6619 // superclass defines a private method and this class redefines
6620 // it -- otherwise it would use the same vtable slot. In .dex files
6621 // those don't end up in the virtual method table, so it shouldn't
6622 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07006623 //
6624 // To find defaults we need to do the same but also go over interfaces.
6625 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07006626 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006627 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08006628 ArtMethod* vtable_method = using_virtuals ?
6629 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07006630 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
6631 ArtMethod* vtable_method_for_name_comparison =
6632 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006633 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006634 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006635 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07006636 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
6637 // allocations.
6638 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006639 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07006640 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartiere401d142015-04-22 13:56:20 -07006641 PrettyMethod(vtable_method).c_str(), PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07006642 return false;
Alex Light9139e002015-10-09 15:59:48 -07006643 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006644 // We might have a newer, better, default method for this, so we just skip it. If we
6645 // are still using this we will select it again when scanning for default methods. To
6646 // obviate the need to copy the method again we will make a note that we already found
6647 // a default here.
6648 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07006649 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07006650 break;
6651 } else {
6652 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07006653 if (LIKELY(fill_tables)) {
6654 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
6655 // Place method in imt if entry is empty, place conflict otherwise.
6656 SetIMTRef(unimplemented_method,
6657 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07006658 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006659 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07006660 /*out*/imt_ptr);
6661 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006662 break;
6663 }
6664 }
Alex Light9139e002015-10-09 15:59:48 -07006665 }
6666 // Continue on to the next method if we are done.
6667 if (LIKELY(found_impl)) {
6668 continue;
6669 } else if (LIKELY(super_interface)) {
6670 // Don't look for a default implementation when the super-method is implemented directly
6671 // by the class.
6672 //
6673 // See if we can use the superclasses method and skip searching everything else.
6674 // Note: !found_impl && super_interface
6675 CHECK(extend_super_iftable);
6676 // If this is a super_interface method it is possible we shouldn't override it because a
6677 // superclass could have implemented it directly. We get the method the superclass used
6678 // to implement this to know if we can override it with a default method. Doing this is
6679 // safe since we know that the super_iftable is filled in so we can simply pull it from
6680 // there. We don't bother if this is not a super-classes interface since in that case we
6681 // have scanned the entire vtable anyway and would have found it.
6682 // TODO This is rather dirty but it is faster than searching through the entire vtable
6683 // every time.
6684 ArtMethod* supers_method =
6685 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6686 DCHECK(supers_method != nullptr);
6687 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07006688 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07006689 // The method is not overridable by a default method (i.e. it is directly implemented
6690 // in some class). Therefore move onto the next interface method.
6691 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07006692 } else {
6693 // If the super-classes method is override-able by a default method we need to keep
6694 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
6695 // 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 -07006696 // to the vtable twice, causing corruption (vtable entries having inconsistent and
6697 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
6698 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07006699 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
6700 << "vtable_impl was " << PrettyMethod(vtable_impl) << " and not 'nullptr' or "
6701 << PrettyMethod(supers_method) << " as expected. IFTable appears to be corrupt!";
6702 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07006703 }
6704 }
6705 // If we haven't found it yet we should search through the interfaces for default methods.
6706 ArtMethod* current_method = nullptr;
6707 switch (FindDefaultMethodImplementation(self,
6708 interface_method,
6709 klass,
6710 /*out*/&current_method)) {
6711 case DefaultMethodSearchResult::kDefaultConflict: {
6712 // Default method conflict.
6713 DCHECK(current_method == nullptr);
6714 ArtMethod* default_conflict_method = nullptr;
6715 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
6716 // We can reuse the method from the superclass, don't bother adding it to virtuals.
6717 default_conflict_method = vtable_impl;
6718 } else {
6719 // See if we already have a conflict method for this method.
Alex Light1f3925d2016-09-07 12:04:20 -07006720 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
6721 interface_name_comparator,
6722 default_conflict_methods,
6723 overriding_default_conflict_methods);
Alex Light9139e002015-10-09 15:59:48 -07006724 if (LIKELY(preexisting_conflict != nullptr)) {
6725 // We already have another conflict we can reuse.
6726 default_conflict_method = preexisting_conflict;
6727 } else {
Alex Light705ad492015-09-21 11:36:30 -07006728 // Note that we do this even if we are an interface since we need to create this and
6729 // cannot reuse another classes.
Alex Light9139e002015-10-09 15:59:48 -07006730 // Create a new conflict method for this to use.
6731 default_conflict_method =
6732 reinterpret_cast<ArtMethod*>(allocator.Alloc(method_size));
6733 new(default_conflict_method) ArtMethod(interface_method, image_pointer_size_);
Alex Light1f3925d2016-09-07 12:04:20 -07006734 if (vtable_impl == nullptr) {
6735 // Save the conflict method. We need to add it to the vtable.
6736 default_conflict_methods.push_back(default_conflict_method);
6737 } else {
6738 // Save the conflict method but it is already in the vtable.
6739 overriding_default_conflict_methods.push_back(default_conflict_method);
6740 }
Alex Light9139e002015-10-09 15:59:48 -07006741 }
6742 }
6743 current_method = default_conflict_method;
6744 break;
Alex Light705ad492015-09-21 11:36:30 -07006745 } // case kDefaultConflict
Alex Light9139e002015-10-09 15:59:48 -07006746 case DefaultMethodSearchResult::kDefaultFound: {
6747 DCHECK(current_method != nullptr);
6748 // Found a default method.
6749 if (vtable_impl != nullptr &&
6750 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
6751 // We found a default method but it was the same one we already have from our
6752 // superclass. Don't bother adding it to our vtable again.
6753 current_method = vtable_impl;
Alex Light705ad492015-09-21 11:36:30 -07006754 } else if (LIKELY(fill_tables)) {
6755 // Interfaces don't need to copy default methods since they don't have vtables.
Alex Light9139e002015-10-09 15:59:48 -07006756 // Only record this default method if it is new to save space.
Alex Light705ad492015-09-21 11:36:30 -07006757 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
6758 // would make lookup for interface super much faster. (We would only need to scan
6759 // the iftable to find if there is a NSME or AME.)
Alex Light1f3925d2016-09-07 12:04:20 -07006760 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
6761 default_methods,
6762 overriding_default_methods);
Alex Light9139e002015-10-09 15:59:48 -07006763 if (old == nullptr) {
6764 // We found a default method implementation and there were no conflicts.
Alex Light1f3925d2016-09-07 12:04:20 -07006765 if (vtable_impl == nullptr) {
6766 // Save the default method. We need to add it to the vtable.
6767 default_methods.push_back(current_method);
6768 } else {
6769 // Save the default method but it is already in the vtable.
6770 overriding_default_methods.push_back(current_method);
6771 }
Alex Light9139e002015-10-09 15:59:48 -07006772 } else {
6773 CHECK(old == current_method) << "Multiple default implementations selected!";
6774 }
6775 }
6776 break;
Alex Light705ad492015-09-21 11:36:30 -07006777 } // case kDefaultFound
Alex Light9139e002015-10-09 15:59:48 -07006778 case DefaultMethodSearchResult::kAbstractFound: {
6779 DCHECK(current_method == nullptr);
6780 // Abstract method masks all defaults.
6781 if (vtable_impl != nullptr &&
6782 vtable_impl->IsAbstract() &&
6783 !vtable_impl->IsDefaultConflicting()) {
6784 // We need to make this an abstract method but the version in the vtable already is so
6785 // don't do anything.
6786 current_method = vtable_impl;
6787 }
6788 break;
Alex Light705ad492015-09-21 11:36:30 -07006789 } // case kAbstractFound
6790 }
6791 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08006792 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07006793 // We could not find an implementation for this method and since it is a brand new
6794 // interface we searched the entire vtable (and all default methods) for an
6795 // implementation but couldn't find one. We therefore need to make a miranda method.
6796 //
6797 // Find out if there is already a miranda method we can use.
6798 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
6799 miranda_methods);
6800 if (miranda_method == nullptr) {
6801 DCHECK(interface_method->IsAbstract()) << PrettyMethod(interface_method);
6802 miranda_method = reinterpret_cast<ArtMethod*>(allocator.Alloc(method_size));
6803 CHECK(miranda_method != nullptr);
6804 // Point the interface table at a phantom slot.
6805 new(miranda_method) ArtMethod(interface_method, image_pointer_size_);
6806 miranda_methods.push_back(miranda_method);
6807 }
Alex Light12771082016-01-26 16:07:41 -08006808 current_method = miranda_method;
6809 }
6810
6811 if (current_method != nullptr) {
6812 // We found a default method implementation. Record it in the iftable and IMT.
6813 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
6814 SetIMTRef(unimplemented_method,
6815 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08006816 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006817 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08006818 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07006819 }
6820 }
Alex Light705ad492015-09-21 11:36:30 -07006821 } // For each method in interface end.
6822 } // if (num_methods > 0)
6823 } // For each interface.
6824 const bool has_new_virtuals = !(miranda_methods.empty() &&
6825 default_methods.empty() &&
Alex Light1f3925d2016-09-07 12:04:20 -07006826 overriding_default_methods.empty() &&
6827 overriding_default_conflict_methods.empty() &&
Alex Light705ad492015-09-21 11:36:30 -07006828 default_conflict_methods.empty());
6829 // TODO don't extend virtuals of interface unless necessary (when is it?).
6830 if (has_new_virtuals) {
6831 DCHECK(!is_interface || (default_methods.empty() && miranda_methods.empty()))
6832 << "Interfaces should only have default-conflict methods appended to them.";
Alex Light9139e002015-10-09 15:59:48 -07006833 VLOG(class_linker) << PrettyClass(klass.Get()) << ": miranda_methods=" << miranda_methods.size()
6834 << " default_methods=" << default_methods.size()
Alex Light1f3925d2016-09-07 12:04:20 -07006835 << " overriding_default_methods=" << overriding_default_methods.size()
6836 << " default_conflict_methods=" << default_conflict_methods.size()
6837 << " overriding_default_conflict_methods="
6838 << overriding_default_conflict_methods.size();
Alex Lighte64300b2015-12-15 15:02:47 -08006839 const size_t old_method_count = klass->NumMethods();
Alex Light9139e002015-10-09 15:59:48 -07006840 const size_t new_method_count = old_method_count +
6841 miranda_methods.size() +
6842 default_methods.size() +
Alex Light1f3925d2016-09-07 12:04:20 -07006843 overriding_default_conflict_methods.size() +
6844 overriding_default_methods.size() +
Alex Light9139e002015-10-09 15:59:48 -07006845 default_conflict_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07006846 // Attempt to realloc to save RAM if possible.
Alex Lighte64300b2015-12-15 15:02:47 -08006847 LengthPrefixedArray<ArtMethod>* old_methods = klass->GetMethodsPtr();
6848 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
Mathieu Chartiere401d142015-04-22 13:56:20 -07006849 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
6850 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
6851 // CopyFrom has internal read barriers.
Alex Lighte64300b2015-12-15 15:02:47 -08006852 //
6853 // TODO We should maybe move some of this into mirror::Class or at least into another method.
6854 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
6855 method_size,
6856 method_alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006857 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
Vladimir Markocf36d492015-08-12 19:27:26 +01006858 method_size,
6859 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08006860 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
6861 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
6862 runtime->GetLinearAlloc()->Realloc(self, old_methods, old_methods_ptr_size, new_size));
6863 if (UNLIKELY(methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006864 self->AssertPendingOOMException();
Mathieu Chartier4e2cb092015-07-22 16:17:51 -07006865 self->EndAssertNoThreadSuspension(old_cause);
Ian Rogersa436fde2013-08-27 23:34:06 -07006866 return false;
6867 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006868 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table(allocator.Adapter());
Alex Lighte64300b2015-12-15 15:02:47 -08006869 if (methods != old_methods) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006870 // Maps from heap allocated miranda method to linear alloc miranda method.
Alex Lighte64300b2015-12-15 15:02:47 -08006871 StrideIterator<ArtMethod> out = methods->begin(method_size, method_alignment);
6872 // Copy over the old methods.
6873 for (auto& m : klass->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006874 move_table.emplace(&m, &*out);
6875 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
6876 // barriers when it copies.
6877 out->CopyFrom(&m, image_pointer_size_);
6878 ++out;
6879 }
6880 }
Alex Lighte64300b2015-12-15 15:02:47 -08006881 StrideIterator<ArtMethod> out(methods->begin(method_size, method_alignment) + old_method_count);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07006882 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
6883 // we want the roots of the miranda methods to get visited.
6884 for (ArtMethod* mir_method : miranda_methods) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006885 ArtMethod& new_method = *out;
6886 new_method.CopyFrom(mir_method, image_pointer_size_);
Alex Light36121492016-02-22 13:43:29 -08006887 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
Alex Lighteb7c1442015-08-31 13:17:42 -07006888 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
6889 << "Miranda method should be abstract!";
6890 move_table.emplace(mir_method, &new_method);
6891 ++out;
6892 }
Alex Lighte64300b2015-12-15 15:02:47 -08006893 // We need to copy the default methods into our own method table since the runtime requires that
6894 // every method on a class's vtable be in that respective class's virtual method table.
Alex Lighteb7c1442015-08-31 13:17:42 -07006895 // NOTE This means that two classes might have the same implementation of a method from the same
6896 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
6897 // default method found on a class with one found on the declaring interface directly and must
6898 // look at the declaring class to determine if they are the same.
Alex Light1f3925d2016-09-07 12:04:20 -07006899 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods,
6900 overriding_default_methods}) {
6901 for (ArtMethod* def_method : methods_vec) {
6902 ArtMethod& new_method = *out;
6903 new_method.CopyFrom(def_method, image_pointer_size_);
6904 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
6905 // verified yet it shouldn't have methods that are skipping access checks.
6906 // TODO This is rather arbitrary. We should maybe support classes where only some of its
6907 // methods are skip_access_checks.
6908 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
6909 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
6910 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
6911 move_table.emplace(def_method, &new_method);
6912 ++out;
6913 }
Mathieu Chartiercf3b1a32015-06-01 14:30:06 -07006914 }
Alex Light1f3925d2016-09-07 12:04:20 -07006915 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_conflict_methods,
6916 overriding_default_conflict_methods}) {
6917 for (ArtMethod* conf_method : methods_vec) {
6918 ArtMethod& new_method = *out;
6919 new_method.CopyFrom(conf_method, image_pointer_size_);
6920 // This is a type of default method (there are default method impls, just a conflict) so
6921 // mark this as a default, non-abstract method, since thats what it is. Also clear the
6922 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
6923 // methods that are skipping access checks.
6924 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
6925 constexpr uint32_t kMaskFlags = ~(kAccAbstract | kAccSkipAccessChecks);
6926 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
6927 DCHECK(new_method.IsDefaultConflicting());
6928 // The actual method might or might not be marked abstract since we just copied it from a
6929 // (possibly default) interface method. We need to set it entry point to be the bridge so
6930 // that the compiler will not invoke the implementation of whatever method we copied from.
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01006931 EnsureThrowsInvocationError(this, &new_method);
Alex Light1f3925d2016-09-07 12:04:20 -07006932 move_table.emplace(conf_method, &new_method);
6933 ++out;
6934 }
Alex Light9139e002015-10-09 15:59:48 -07006935 }
Alex Lighte64300b2015-12-15 15:02:47 -08006936 methods->SetSize(new_method_count);
6937 UpdateClassMethods(klass.Get(), methods);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07006938 // 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 -07006939 // suspension assert.
6940 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07006941
Alex Light705ad492015-09-21 11:36:30 -07006942 if (fill_tables) {
6943 // Update the vtable to the new method structures. We can skip this for interfaces since they
6944 // do not have vtables.
6945 const size_t old_vtable_count = vtable->GetLength();
6946 const size_t new_vtable_count = old_vtable_count +
6947 miranda_methods.size() +
6948 default_methods.size() +
6949 default_conflict_methods.size();
Alex Light1f3925d2016-09-07 12:04:20 -07006950
Alex Light705ad492015-09-21 11:36:30 -07006951 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, new_vtable_count)));
6952 if (UNLIKELY(vtable.Get() == nullptr)) {
6953 self->AssertPendingOOMException();
6954 return false;
6955 }
Alex Light705ad492015-09-21 11:36:30 -07006956 size_t vtable_pos = old_vtable_count;
6957 // Update all the newly copied method's indexes so they denote their placement in the vtable.
Alex Light1f3925d2016-09-07 12:04:20 -07006958 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods,
6959 default_conflict_methods,
6960 miranda_methods}) {
6961 // These are the functions that are not already in the vtable!
6962 for (ArtMethod* new_method : methods_vec) {
6963 auto translated_method_it = move_table.find(new_method);
6964 CHECK(translated_method_it != move_table.end())
6965 << "We must have a translation for methods added to the classes methods_ array! We "
6966 << "could not find the ArtMethod added for " << PrettyMethod(new_method);
6967 ArtMethod* new_vtable_method = translated_method_it->second;
6968 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
6969 // fields are references into the dex file the method was defined in. Since the ArtMethod
6970 // does not store that information it uses declaring_class_->dex_cache_.
6971 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
6972 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, image_pointer_size_);
6973 ++vtable_pos;
6974 }
Alex Light705ad492015-09-21 11:36:30 -07006975 }
6976 CHECK_EQ(vtable_pos, new_vtable_count);
6977 // Update old vtable methods. We use the default_translations map to figure out what each
6978 // vtable entry should be updated to, if they need to be at all.
6979 for (size_t i = 0; i < old_vtable_count; ++i) {
6980 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(
6981 i, image_pointer_size_);
6982 // Try and find what we need to change this method to.
6983 auto translation_it = default_translations.find(i);
6984 bool found_translation = false;
6985 if (translation_it != default_translations.end()) {
6986 if (translation_it->second.IsInConflict()) {
6987 // Find which conflict method we are to use for this method.
6988 MethodNameAndSignatureComparator old_method_comparator(
6989 translated_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Light1f3925d2016-09-07 12:04:20 -07006990 // We only need to look through overriding_default_conflict_methods since this is an
6991 // overridden method we are fixing up here.
6992 ArtMethod* new_conflict_method = FindSameNameAndSignature(
6993 old_method_comparator, overriding_default_conflict_methods);
Alex Light705ad492015-09-21 11:36:30 -07006994 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
6995 translated_method = new_conflict_method;
6996 } else if (translation_it->second.IsAbstract()) {
6997 // Find which miranda method we are to use for this method.
6998 MethodNameAndSignatureComparator old_method_comparator(
6999 translated_method->GetInterfaceMethodIfProxy(image_pointer_size_));
7000 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
Alex Light1f3925d2016-09-07 12:04:20 -07007001 miranda_methods);
Alex Light705ad492015-09-21 11:36:30 -07007002 DCHECK(miranda_method != nullptr);
7003 translated_method = miranda_method;
7004 } else {
7005 // Normal default method (changed from an older default or abstract interface method).
7006 DCHECK(translation_it->second.IsTranslation());
7007 translated_method = translation_it->second.GetTranslation();
7008 }
7009 found_translation = true;
Alex Light9139e002015-10-09 15:59:48 -07007010 }
Alex Light705ad492015-09-21 11:36:30 -07007011 DCHECK(translated_method != nullptr);
7012 auto it = move_table.find(translated_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007013 if (it != move_table.end()) {
Alex Light705ad492015-09-21 11:36:30 -07007014 auto* new_method = it->second;
7015 DCHECK(new_method != nullptr);
Alex Light1f3925d2016-09-07 12:04:20 -07007016 // Make sure the new_methods index is set.
7017 if (new_method->GetMethodIndexDuringLinking() != i) {
7018 DCHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size, method_alignment)),
7019 reinterpret_cast<uintptr_t>(new_method));
7020 DCHECK_LT(reinterpret_cast<uintptr_t>(new_method),
7021 reinterpret_cast<uintptr_t>(&*methods->end(method_size, method_alignment)));
7022 new_method->SetMethodIndex(0xFFFF & i);
7023 }
Alex Light705ad492015-09-21 11:36:30 -07007024 vtable->SetElementPtrSize(i, new_method, image_pointer_size_);
7025 } else {
7026 // If it was not going to be updated we wouldn't have put it into the default_translations
7027 // map.
7028 CHECK(!found_translation) << "We were asked to update this vtable entry. Must not fail.";
7029 }
7030 }
7031 klass->SetVTable(vtable.Get());
7032
7033 // Go fix up all the stale iftable pointers.
7034 for (size_t i = 0; i < ifcount; ++i) {
7035 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7036 auto* method_array = iftable->GetMethodArray(i);
7037 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7038 DCHECK(m != nullptr) << PrettyClass(klass.Get());
7039 auto it = move_table.find(m);
7040 if (it != move_table.end()) {
7041 auto* new_m = it->second;
7042 DCHECK(new_m != nullptr) << PrettyClass(klass.Get());
7043 method_array->SetElementPtrSize(j, new_m, image_pointer_size_);
7044 }
7045 }
7046 }
7047
7048 // Fix up IMT next
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007049 for (size_t i = 0; i < ImTable::kSize; ++i) {
Alex Light705ad492015-09-21 11:36:30 -07007050 auto it = move_table.find(out_imt[i]);
7051 if (it != move_table.end()) {
7052 out_imt[i] = it->second;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007053 }
7054 }
7055 }
Alex Light705ad492015-09-21 11:36:30 -07007056
Mathieu Chartiere401d142015-04-22 13:56:20 -07007057 // Check that there are no stale methods are in the dex cache array.
7058 if (kIsDebugBuild) {
7059 auto* resolved_methods = klass->GetDexCache()->GetResolvedMethods();
Vladimir Marko05792b92015-08-03 11:56:49 +01007060 for (size_t i = 0, count = klass->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
7061 auto* m = mirror::DexCache::GetElementPtrSize(resolved_methods, i, image_pointer_size_);
Alex Lighte64300b2015-12-15 15:02:47 -08007062 CHECK(move_table.find(m) == move_table.end() ||
7063 // The original versions of copied methods will still be present so allow those too.
7064 // Note that if the first check passes this might fail to GetDeclaringClass().
7065 std::find_if(m->GetDeclaringClass()->GetMethods(image_pointer_size_).begin(),
7066 m->GetDeclaringClass()->GetMethods(image_pointer_size_).end(),
7067 [m] (ArtMethod& meth) {
7068 return &meth == m;
7069 }) != m->GetDeclaringClass()->GetMethods(image_pointer_size_).end())
7070 << "Obsolete methods " << PrettyMethod(m) << " is in dex cache!";
Mathieu Chartiere401d142015-04-22 13:56:20 -07007071 }
7072 }
Alex Lighte64300b2015-12-15 15:02:47 -08007073 // Put some random garbage in old methods to help find stale pointers.
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -07007074 if (methods != old_methods && old_methods != nullptr && kIsDebugBuild) {
7075 // Need to make sure the GC is not running since it could be scanning the methods we are
7076 // about to overwrite.
7077 ScopedThreadStateChange tsc(self, kSuspended);
7078 gc::ScopedGCCriticalSection gcs(self,
7079 gc::kGcCauseClassLinker,
7080 gc::kCollectorTypeClassLinker);
Alex Lighte64300b2015-12-15 15:02:47 -08007081 memset(old_methods, 0xFEu, old_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007082 }
7083 } else {
7084 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007085 }
Alex Light705ad492015-09-21 11:36:30 -07007086 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007087 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007088 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007089 return true;
7090}
7091
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007092bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007093 CHECK(klass.Get() != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007094 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007095}
7096
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007097bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007098 CHECK(klass.Get() != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007099 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07007100}
7101
Brian Carlstromdbc05252011-09-09 01:59:59 -07007102struct LinkFieldsComparator {
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007103 explicit LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07007104 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007105 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007106 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007107 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07007108 // 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 -07007109 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7110 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08007111 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00007112 if (type1 == Primitive::kPrimNot) {
7113 // Reference always goes first.
7114 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08007115 }
Vladimir Markod5777482014-11-12 17:02:02 +00007116 if (type2 == Primitive::kPrimNot) {
7117 // Reference always goes first.
7118 return false;
7119 }
7120 size_t size1 = Primitive::ComponentSize(type1);
7121 size_t size2 = Primitive::ComponentSize(type2);
7122 if (size1 != size2) {
7123 // Larger primitive types go first.
7124 return size1 > size2;
7125 }
7126 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7127 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007128 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007129 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7130 // by name and for equal names by type id index.
7131 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7132 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07007133 }
7134};
7135
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007136bool ClassLinker::LinkFields(Thread* self,
7137 Handle<mirror::Class> klass,
7138 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007139 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07007140 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07007141 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007142 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7143 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007144
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007145 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07007146 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007147 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007148 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007149 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007150 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007151 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07007152 CHECK(super_class->IsResolved())
7153 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007154 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007155 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007156 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007157
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007158 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007159
Brian Carlstromdbc05252011-09-09 01:59:59 -07007160 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07007161 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08007162 //
7163 // The overall sort order order is:
7164 // 1) All object reference fields, sorted alphabetically.
7165 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7166 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7167 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7168 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7169 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7170 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7171 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7172 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7173 //
7174 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7175 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07007176 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07007177 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07007178 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07007179 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007180 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007181 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07007182 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7183 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07007184
Fred Shih381e4ca2014-08-25 17:24:27 -07007185 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07007186 size_t current_field = 0;
7187 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07007188 FieldGaps gaps;
7189
Brian Carlstromdbc05252011-09-09 01:59:59 -07007190 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007191 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07007192 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07007193 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07007194 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07007195 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007196 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007197 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7198 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07007199 MemberOffset old_offset = field_offset;
7200 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7201 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7202 }
Roland Levillain14d90572015-07-16 10:52:26 +01007203 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07007204 grouped_and_sorted_fields.pop_front();
7205 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007206 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00007207 field_offset = MemberOffset(field_offset.Uint32Value() +
7208 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007209 }
Fred Shih381e4ca2014-08-25 17:24:27 -07007210 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7211 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00007212 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7213 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7214 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7215 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07007216 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
7217 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07007218 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007219
Elliott Hughesadb460d2011-10-05 17:02:34 -07007220 // 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 -07007221 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07007222 // We know there are no non-reference fields in the Reference classes, and we know
7223 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07007224 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007225 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
7226 << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07007227 --num_reference_fields;
7228 }
7229
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007230 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007231 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007232 if (is_static) {
7233 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07007234 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07007235 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007236 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007237 mirror::Class* super_class = klass->GetSuperClass();
7238 if (num_reference_fields == 0 || super_class == nullptr) {
7239 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007240 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007241 if (super_class == nullptr ||
7242 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
7243 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07007244 }
7245 }
7246 if (kIsDebugBuild) {
7247 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
7248 size_t total_reference_instance_fields = 0;
7249 mirror::Class* cur_super = klass.Get();
7250 while (cur_super != nullptr) {
7251 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
7252 cur_super = cur_super->GetSuperClass();
7253 }
7254 if (super_class == nullptr) {
7255 CHECK_EQ(total_reference_instance_fields, 1u) << PrettyDescriptor(klass.Get());
7256 } else {
7257 // Check that there is at least num_reference_fields other than Object.class.
7258 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
7259 << PrettyClass(klass.Get());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07007260 }
7261 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07007262 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007263 std::string temp;
7264 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
7265 size_t previous_size = klass->GetObjectSize();
7266 if (previous_size != 0) {
7267 // Make sure that we didn't originally have an incorrect size.
7268 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07007269 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007270 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007271 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007272 }
Vladimir Marko76649e82014-11-10 18:32:59 +00007273
7274 if (kIsDebugBuild) {
7275 // Make sure that the fields array is ordered by name but all reference
7276 // offsets are at the beginning as far as alignment allows.
7277 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07007278 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00007279 : klass->GetFirstReferenceInstanceFieldOffset();
7280 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
7281 num_reference_fields *
7282 sizeof(mirror::HeapReference<mirror::Object>));
7283 MemberOffset current_ref_offset = start_ref_offset;
7284 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007285 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007286 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
7287 << " class=" << PrettyClass(klass.Get()) << " field=" << PrettyField(field) << " offset="
Nicolas Geoffray555b3d02015-06-23 12:11:24 +01007288 << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007289 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007290 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00007291 // NOTE: The field names can be the same. This is not possible in the Java language
7292 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07007293 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00007294 }
7295 Primitive::Type type = field->GetTypeAsPrimitiveType();
7296 bool is_primitive = type != Primitive::kPrimNot;
7297 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
7298 strcmp("referent", field->GetName()) == 0) {
7299 is_primitive = true; // We lied above, so we have to expect a lie here.
7300 }
7301 MemberOffset offset = field->GetOffsetDuringLinking();
7302 if (is_primitive) {
7303 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
7304 // Shuffled before references.
7305 size_t type_size = Primitive::ComponentSize(type);
7306 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
7307 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
7308 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
7309 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
7310 }
7311 } else {
7312 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
7313 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
7314 sizeof(mirror::HeapReference<mirror::Object>));
7315 }
7316 }
7317 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
7318 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007319 return true;
7320}
7321
Vladimir Marko76649e82014-11-10 18:32:59 +00007322// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007323void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007324 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007325 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007326 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007327 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007328 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007329 // Compute reference offsets unless our superclass overflowed.
7330 if (reference_offsets != mirror::Class::kClassWalkSuper) {
7331 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00007332 if (num_reference_fields != 0u) {
7333 // All of the fields that contain object references are guaranteed be grouped in memory
7334 // starting at an appropriately aligned address after super class object data.
7335 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
7336 sizeof(mirror::HeapReference<mirror::Object>));
7337 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007338 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00007339 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007340 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007341 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00007342 reference_offsets |= (0xffffffffu << start_bit) &
7343 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07007344 }
7345 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07007346 }
7347 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07007348 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007349}
7350
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007351mirror::String* ClassLinker::ResolveString(const DexFile& dex_file,
7352 uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007353 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007354 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007355 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007356 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007357 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007358 return resolved;
7359 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07007360 uint32_t utf16_length;
7361 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007362 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007363 dex_cache->SetResolvedString(string_idx, string);
7364 return string;
7365}
7366
Vladimir Markocac5a7e2016-02-22 10:39:50 +00007367mirror::String* ClassLinker::LookupString(const DexFile& dex_file,
7368 uint32_t string_idx,
7369 Handle<mirror::DexCache> dex_cache) {
7370 DCHECK(dex_cache.Get() != nullptr);
7371 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
7372 if (resolved != nullptr) {
7373 return resolved;
7374 }
7375 uint32_t utf16_length;
7376 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
7377 mirror::String* string = intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
7378 if (string != nullptr) {
7379 dex_cache->SetResolvedString(string_idx, string);
7380 }
7381 return string;
7382}
7383
Mathieu Chartierb8901302016-09-30 10:27:43 -07007384ObjPtr<mirror::Class> ClassLinker::LookupResolvedType(const DexFile& dex_file,
7385 uint16_t type_idx,
7386 ObjPtr<mirror::DexCache> dex_cache,
7387 ObjPtr<mirror::ClassLoader> class_loader) {
7388 ObjPtr<mirror::Class> type = dex_cache->GetResolvedType(type_idx);
7389 if (type == nullptr) {
7390 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
7391 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
7392 if (descriptor[1] == '\0') {
7393 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
7394 // for primitive classes that aren't backed by dex files.
7395 type = FindPrimitiveClass(descriptor[0]);
7396 } else {
7397 Thread* const self = Thread::Current();
7398 DCHECK(self != nullptr);
7399 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
7400 // Find the class in the loaded classes table.
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07007401 type = LookupClass(self, descriptor, hash, class_loader.Ptr());
Mathieu Chartierb8901302016-09-30 10:27:43 -07007402 }
7403 }
7404 if (type != nullptr || type->IsResolved()) {
7405 return type;
7406 }
7407 return nullptr;
7408}
7409
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007410mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
7411 uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08007412 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007413 StackHandleScope<2> hs(Thread::Current());
7414 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
7415 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07007416 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
7417}
7418
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007419mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
7420 uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007421 Handle<mirror::DexCache> dex_cache,
7422 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007423 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007424 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007425 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007426 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08007427 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07007428 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08007429 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007430 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05007431 // TODO: we used to throw here if resolved's class loader was not the
7432 // boot class loader. This was to permit different classes with the
7433 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007434 dex_cache->SetResolvedType(type_idx, resolved);
7435 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08007436 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08007437 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08007438 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007439 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00007440 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08007441 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007442 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08007443 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08007444 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00007445 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08007446 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07007447 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007448 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007449 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Mathieu Chartiere401d142015-04-22 13:56:20 -07007450 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007451 return resolved;
7452}
7453
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007454template <ClassLinker::ResolveMode kResolveMode>
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007455ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file,
7456 uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07007457 Handle<mirror::DexCache> dex_cache,
7458 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007459 ArtMethod* referrer,
7460 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007461 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07007462 // Check for hit in the dex cache.
Mathieu Chartiere401d142015-04-22 13:56:20 -07007463 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007464 Thread::PoisonObjectPointersIfDebug();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07007465 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007466 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007467 if (kResolveMode == ClassLinker::kForceICCECheck) {
7468 if (resolved->CheckIncompatibleClassChange(type)) {
7469 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
7470 return nullptr;
7471 }
7472 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007473 return resolved;
7474 }
Ian Rogers08f753d2012-08-24 14:35:25 -07007475 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007476 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007477 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007478 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07007479 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007480 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007481 }
Ian Rogers08f753d2012-08-24 14:35:25 -07007482 // Scan using method_idx, this saves string compares but will only hit for matching dex
7483 // caches/files.
7484 switch (type) {
7485 case kDirect: // Fall-through.
7486 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007487 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7488 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07007489 break;
7490 case kInterface:
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08007491 // We have to check whether the method id really belongs to an interface (dex static bytecode
7492 // constraint A15). Otherwise you must not invoke-interface on it.
7493 //
7494 // This is not symmetric to A12-A14 (direct, static, virtual), as using FindInterfaceMethod
7495 // assumes that the given type is an interface, and will check the interface table if the
7496 // method isn't declared in the class. So it may find an interface method (usually by name
7497 // in the handling below, but we do the constraint check early). In that case,
7498 // CheckIncompatibleClassChange will succeed (as it is called on an interface method)
7499 // unexpectedly.
7500 // Example:
7501 // interface I {
7502 // foo()
7503 // }
7504 // class A implements I {
7505 // ...
7506 // }
7507 // class B extends A {
7508 // ...
7509 // }
7510 // invoke-interface B.foo
7511 // -> FindInterfaceMethod finds I.foo (interface method), not A.foo (miranda method)
7512 if (UNLIKELY(!klass->IsInterface())) {
7513 ThrowIncompatibleClassChangeError(klass,
7514 "Found class %s, but interface was expected",
7515 PrettyDescriptor(klass).c_str());
7516 return nullptr;
7517 } else {
7518 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7519 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
7520 }
Ian Rogers08f753d2012-08-24 14:35:25 -07007521 break;
Alex Light705ad492015-09-21 11:36:30 -07007522 case kSuper:
7523 if (klass->IsInterface()) {
7524 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7525 } else {
7526 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7527 }
7528 break;
Ian Rogers08f753d2012-08-24 14:35:25 -07007529 case kVirtual:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007530 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07007531 break;
7532 default:
7533 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07007534 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07007535 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007536 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07007537 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08007538 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07007539 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07007540 switch (type) {
7541 case kDirect: // Fall-through.
7542 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007543 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_);
7544 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07007545 break;
7546 case kInterface:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007547 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007548 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07007549 break;
Alex Light705ad492015-09-21 11:36:30 -07007550 case kSuper:
7551 if (klass->IsInterface()) {
7552 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
7553 } else {
7554 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
7555 }
7556 break;
Ian Rogers08f753d2012-08-24 14:35:25 -07007557 case kVirtual:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007558 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07007559 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08007560 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007561 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007562 // If we found a method, check for incompatible class changes.
7563 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07007564 // Be a good citizen and update the dex cache to speed subsequent calls.
Mathieu Chartiere401d142015-04-22 13:56:20 -07007565 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07007566 return resolved;
7567 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007568 // If we had a method, it's an incompatible-class-change error.
7569 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007570 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007571 } else {
7572 // We failed to find the method which means either an access error, an incompatible class
7573 // change, or no such method. First try to find the method among direct and virtual methods.
7574 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
7575 const Signature signature = dex_file.GetMethodSignature(method_id);
7576 switch (type) {
7577 case kDirect:
7578 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007579 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007580 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
7581 // have had a resolved method before, which triggers the "true" branch above.
7582 break;
7583 case kInterface:
7584 case kVirtual:
7585 case kSuper:
Mathieu Chartiere401d142015-04-22 13:56:20 -07007586 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007587 break;
7588 }
7589
7590 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08007591 bool exception_generated = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007592 if (resolved != nullptr && referrer != nullptr) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007593 mirror::Class* methods_class = resolved->GetDeclaringClass();
7594 mirror::Class* referring_class = referrer->GetDeclaringClass();
7595 if (!referring_class->CanAccess(methods_class)) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007596 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class,
7597 methods_class,
7598 resolved,
Mathieu Chartiere401d142015-04-22 13:56:20 -07007599 type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08007600 exception_generated = true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007601 } else if (!referring_class->CanAccessMember(methods_class, resolved->GetAccessFlags())) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007602 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08007603 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007604 }
7605 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08007606 if (!exception_generated) {
7607 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
7608 // interface methods and throw if we find the method there. If we find nothing, throw a
7609 // NoSuchMethodError.
7610 switch (type) {
7611 case kDirect:
7612 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007613 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007614 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007615 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007616 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08007617 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007618 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08007619 } else {
7620 ThrowNoSuchMethodError(type, klass, name, signature);
7621 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007622 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08007623 break;
7624 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007625 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007626 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08007627 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007628 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08007629 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007630 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08007631 } else {
7632 ThrowNoSuchMethodError(type, klass, name, signature);
7633 }
7634 }
7635 break;
7636 case kSuper:
7637 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007638 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007639 } else {
7640 ThrowNoSuchMethodError(type, klass, name, signature);
7641 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08007642 break;
7643 case kVirtual:
7644 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007645 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08007646 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007647 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08007648 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007649 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08007650 } else {
7651 ThrowNoSuchMethodError(type, klass, name, signature);
7652 }
7653 }
7654 break;
7655 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007656 }
Ian Rogers08f753d2012-08-24 14:35:25 -07007657 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08007658 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07007659 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07007660 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007661}
7662
Jeff Hao13e748b2015-08-25 20:44:19 +00007663ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(const DexFile& dex_file,
7664 uint32_t method_idx,
7665 Handle<mirror::DexCache> dex_cache,
7666 Handle<mirror::ClassLoader> class_loader) {
7667 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007668 Thread::PoisonObjectPointersIfDebug();
Jeff Hao13e748b2015-08-25 20:44:19 +00007669 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
7670 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
7671 return resolved;
7672 }
7673 // Fail, get the declaring class.
7674 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
7675 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
7676 if (klass == nullptr) {
7677 Thread::Current()->AssertPendingException();
7678 return nullptr;
7679 }
7680 if (klass->IsInterface()) {
7681 LOG(FATAL) << "ResolveAmbiguousMethod: unexpected method in interface: " << PrettyClass(klass);
7682 return nullptr;
7683 }
7684
7685 // Search both direct and virtual methods
7686 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7687 if (resolved == nullptr) {
7688 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7689 }
7690
7691 return resolved;
7692}
7693
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007694ArtField* ClassLinker::ResolveField(const DexFile& dex_file,
7695 uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07007696 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007697 Handle<mirror::ClassLoader> class_loader,
7698 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007699 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007700 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007701 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07007702 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007703 return resolved;
7704 }
7705 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07007706 Thread* const self = Thread::Current();
7707 StackHandleScope<1> hs(self);
7708 Handle<mirror::Class> klass(
7709 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07007710 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08007711 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07007712 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007713 }
7714
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07007715 if (is_static) {
Vladimir Markobb268b12016-06-30 15:52:56 +01007716 resolved = mirror::Class::FindStaticField(self, klass.Get(), dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07007717 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007718 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07007719 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08007720
Andreas Gampe58a5af82014-07-31 16:23:49 -07007721 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08007722 const char* name = dex_file.GetFieldName(field_id);
7723 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
7724 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07007725 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08007726 } else {
7727 resolved = klass->FindInstanceField(name, type);
7728 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07007729 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07007730 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007731 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08007732 }
Ian Rogersb067ac22011-12-13 18:05:09 -08007733 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07007734 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08007735 return resolved;
7736}
7737
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007738ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
7739 uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07007740 Handle<mirror::DexCache> dex_cache,
7741 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007742 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07007743 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07007744 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07007745 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08007746 return resolved;
7747 }
7748 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07007749 Thread* self = Thread::Current();
7750 StackHandleScope<1> hs(self);
7751 Handle<mirror::Class> klass(
7752 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007753 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08007754 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007755 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08007756 }
7757
Ian Rogersdfb325e2013-10-30 01:00:44 -07007758 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
7759 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07007760 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07007761 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007762 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07007763 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08007764 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07007765 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07007766 }
7767 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07007768}
7769
Narayan Kamath25352fc2016-08-03 12:46:58 +01007770mirror::MethodType* ClassLinker::ResolveMethodType(const DexFile& dex_file,
7771 uint32_t proto_idx,
7772 Handle<mirror::DexCache> dex_cache,
7773 Handle<mirror::ClassLoader> class_loader) {
7774 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
7775 DCHECK(dex_cache.Get() != nullptr);
7776
7777 mirror::MethodType* resolved = dex_cache->GetResolvedMethodType(proto_idx);
7778 if (resolved != nullptr) {
7779 return resolved;
7780 }
7781
7782 Thread* const self = Thread::Current();
7783 StackHandleScope<4> hs(self);
7784
7785 // First resolve the return type.
7786 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
7787 Handle<mirror::Class> return_type(hs.NewHandle(
7788 ResolveType(dex_file, proto_id.return_type_idx_, dex_cache, class_loader)));
7789 if (return_type.Get() == nullptr) {
7790 DCHECK(self->IsExceptionPending());
7791 return nullptr;
7792 }
7793
7794 // Then resolve the argument types.
7795 //
7796 // TODO: Is there a better way to figure out the number of method arguments
7797 // other than by looking at the shorty ?
7798 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
7799
7800 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
7801 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
7802 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
7803 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
7804 if (method_params.Get() == nullptr) {
7805 DCHECK(self->IsExceptionPending());
7806 return nullptr;
7807 }
7808
7809 DexFileParameterIterator it(dex_file, proto_id);
7810 int32_t i = 0;
7811 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
7812 for (; it.HasNext(); it.Next()) {
7813 const uint16_t type_idx = it.GetTypeIdx();
7814 param_class.Assign(ResolveType(dex_file, type_idx, dex_cache, class_loader));
7815 if (param_class.Get() == nullptr) {
7816 DCHECK(self->IsExceptionPending());
7817 return nullptr;
7818 }
7819
7820 method_params->Set(i++, param_class.Get());
7821 }
7822
7823 DCHECK(!it.HasNext());
7824
7825 Handle<mirror::MethodType> type = hs.NewHandle(
7826 mirror::MethodType::Create(self, return_type, method_params));
7827 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
7828
7829 return type.Get();
7830}
7831
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007832const char* ClassLinker::MethodShorty(uint32_t method_idx,
7833 ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007834 uint32_t* length) {
7835 mirror::Class* declaring_class = referrer->GetDeclaringClass();
7836 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07007837 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07007838 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08007839 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07007840}
7841
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07007842class DumpClassVisitor : public ClassVisitor {
7843 public:
7844 explicit DumpClassVisitor(int flags) : flags_(flags) {}
7845
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007846 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07007847 klass->DumpClass(LOG_STREAM(ERROR), flags_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07007848 return true;
7849 }
7850
7851 private:
7852 const int flags_;
7853};
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07007854
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07007855void ClassLinker::DumpAllClasses(int flags) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07007856 DumpClassVisitor visitor(flags);
7857 VisitClasses(&visitor);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07007858}
7859
Elliott Hughes956af0f2014-12-11 14:34:28 -08007860static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07007861 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08007862 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
7863 base -= sizeof(void*); // Move backward so that code_offset != 0.
7864 const uint32_t code_offset = sizeof(void*);
7865 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07007866}
7867
Ian Rogers6f3dbba2014-10-14 17:41:57 -07007868bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
7869 return (entry_point == GetQuickResolutionStub()) ||
7870 (quick_resolution_trampoline_ == entry_point);
7871}
7872
Ian Rogers6f3dbba2014-10-14 17:41:57 -07007873bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
7874 return (entry_point == GetQuickToInterpreterBridge()) ||
7875 (quick_to_interpreter_bridge_trampoline_ == entry_point);
7876}
7877
7878bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
7879 return (entry_point == GetQuickGenericJniStub()) ||
7880 (quick_generic_jni_trampoline_ == entry_point);
7881}
7882
7883const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
7884 return GetQuickGenericJniStub();
7885}
7886
Mathieu Chartiere401d142015-04-22 13:56:20 -07007887void ClassLinker::SetEntryPointsToCompiledCode(ArtMethod* method,
Elliott Hughes956af0f2014-12-11 14:34:28 -08007888 const void* method_code) const {
7889 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07007890 oat_method.LinkMethod(method);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07007891}
7892
Mathieu Chartiere401d142015-04-22 13:56:20 -07007893void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07007894 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07007895 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
7896 } else {
7897 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08007898 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07007899 oat_method.LinkMethod(method);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07007900 }
7901}
7902
Ian Rogers7dfb28c2013-08-22 08:18:36 -07007903void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07007904 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07007905 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07007906 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
7907 << NumNonZygoteClasses() << "\n";
7908}
7909
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07007910class CountClassesVisitor : public ClassLoaderVisitor {
7911 public:
7912 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
7913
7914 void Visit(mirror::ClassLoader* class_loader)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007915 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07007916 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07007917 if (class_table != nullptr) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07007918 num_zygote_classes += class_table->NumZygoteClasses();
7919 num_non_zygote_classes += class_table->NumNonZygoteClasses();
Mathieu Chartier6b069532015-08-05 15:08:12 -07007920 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07007921 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07007922
7923 size_t num_zygote_classes;
7924 size_t num_non_zygote_classes;
7925};
7926
7927size_t ClassLinker::NumZygoteClasses() const {
7928 CountClassesVisitor visitor;
7929 VisitClassLoaders(&visitor);
7930 return visitor.num_zygote_classes + boot_class_table_.NumZygoteClasses();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07007931}
7932
7933size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07007934 CountClassesVisitor visitor;
7935 VisitClassLoaders(&visitor);
7936 return visitor.num_non_zygote_classes + boot_class_table_.NumNonZygoteClasses();
Elliott Hughescac6cc72011-11-03 20:31:21 -07007937}
7938
Ian Rogers7dfb28c2013-08-22 08:18:36 -07007939size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07007940 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08007941 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07007942 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07007943}
7944
Brian Carlstrom47d237a2011-10-18 15:08:33 -07007945pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07007946 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07007947}
7948
7949pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07007950 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07007951}
7952
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08007953void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08007954 DCHECK(!init_done_);
7955
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007956 DCHECK(klass != nullptr);
7957 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08007958
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07007959 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07007960 DCHECK(class_roots != nullptr);
7961 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07007962 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08007963}
7964
Ian Rogers6f3dbba2014-10-14 17:41:57 -07007965const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
7966 static const char* class_roots_descriptors[] = {
7967 "Ljava/lang/Class;",
7968 "Ljava/lang/Object;",
7969 "[Ljava/lang/Class;",
7970 "[Ljava/lang/Object;",
7971 "Ljava/lang/String;",
7972 "Ljava/lang/DexCache;",
7973 "Ljava/lang/ref/Reference;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07007974 "Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07007975 "Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07007976 "Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07007977 "Ljava/lang/reflect/Proxy;",
7978 "[Ljava/lang/String;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07007979 "[Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07007980 "[Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07007981 "[Ljava/lang/reflect/Method;",
Narayan Kamathafa48272016-08-03 12:46:58 +01007982 "Ljava/lang/invoke/MethodHandleImpl;",
7983 "Ljava/lang/invoke/MethodType;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07007984 "Ljava/lang/ClassLoader;",
7985 "Ljava/lang/Throwable;",
7986 "Ljava/lang/ClassNotFoundException;",
7987 "Ljava/lang/StackTraceElement;",
7988 "Z",
7989 "B",
7990 "C",
7991 "D",
7992 "F",
7993 "I",
7994 "J",
7995 "S",
7996 "V",
7997 "[Z",
7998 "[B",
7999 "[C",
8000 "[D",
8001 "[F",
8002 "[I",
8003 "[J",
8004 "[S",
8005 "[Ljava/lang/StackTraceElement;",
8006 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08008007 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
8008 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07008009
8010 const char* descriptor = class_roots_descriptors[class_root];
8011 CHECK(descriptor != nullptr);
8012 return descriptor;
8013}
8014
Jeff Hao5872d7c2016-04-27 11:07:41 -07008015jobject ClassLinker::CreatePathClassLoader(Thread* self,
8016 const std::vector<const DexFile*>& dex_files) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008017 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
8018 // We could move the jobject to the callers, but all call-sites do this...
8019 ScopedObjectAccessUnchecked soa(self);
8020
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008021 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Mathieu Chartier3398c782016-09-30 10:27:43 -07008022 StackHandleScope<11> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008023
Mathieu Chartierc7853442015-03-27 14:35:38 -07008024 ArtField* dex_elements_field =
8025 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008026
Mathieu Chartier3398c782016-09-30 10:27:43 -07008027 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->GetType<true>()));
8028 DCHECK(dex_elements_class.Get() != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008029 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07008030 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07008031 mirror::ObjectArray<mirror::Object>::Alloc(self,
8032 dex_elements_class.Get(),
8033 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008034 Handle<mirror::Class> h_dex_element_class =
8035 hs.NewHandle(dex_elements_class->GetComponentType());
8036
Mathieu Chartierc7853442015-03-27 14:35:38 -07008037 ArtField* element_file_field =
8038 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
8039 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008040
Mathieu Chartierc7853442015-03-27 14:35:38 -07008041 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
8042 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008043
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008044 ArtField* file_name_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_fileName);
8045 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->GetType<false>());
8046
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008047 // Fill the elements array.
8048 int32_t index = 0;
8049 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008050 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008051
Mathieu Chartier966878d2016-01-14 14:33:29 -08008052 // CreatePathClassLoader is only used by gtests. Index 0 of h_long_array is supposed to be the
8053 // oat file but we can leave it null.
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008054 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
8055 self,
8056 kDexFileIndexStart + 1));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008057 DCHECK(h_long_array.Get() != nullptr);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07008058 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008059
8060 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008061 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008062 DCHECK(h_dex_file.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008063 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008064
Mathieu Chartierfbc31082016-01-24 11:59:56 -08008065 Handle<mirror::String> h_file_name = hs2.NewHandle(
8066 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
8067 DCHECK(h_file_name.Get() != nullptr);
8068 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
8069
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008070 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
8071 DCHECK(h_element.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008072 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008073
8074 h_dex_elements->Set(index, h_element.Get());
8075 index++;
8076 }
8077 DCHECK_EQ(index, h_dex_elements->GetLength());
8078
8079 // Create DexPathList.
8080 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07008081 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008082 DCHECK(h_dex_path_list.Get() != nullptr);
8083 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008084 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008085
8086 // Create PathClassLoader.
8087 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -07008088 soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008089 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
8090 h_path_class_class->AllocObject(self));
8091 DCHECK(h_path_class_loader.Get() != nullptr);
8092 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008093 ArtField* path_list_field =
8094 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList);
8095 DCHECK(path_list_field != nullptr);
8096 path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008097
8098 // Make a pretend boot-classpath.
8099 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07008100 ArtField* const parent_field =
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008101 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07008102 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01008103 DCHECK(parent_field != nullptr);
Mathieu Chartier966878d2016-01-14 14:33:29 -08008104 mirror::Object* boot_cl =
Mathieu Chartier0795f232016-09-27 18:43:30 -07008105 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
Mathieu Chartier966878d2016-01-14 14:33:29 -08008106 parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008107
8108 // Make it a global ref and return.
8109 ScopedLocalRef<jobject> local_ref(
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07008110 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07008111 return soa.Env()->NewGlobalRef(local_ref.get());
8112}
8113
Nicolas Geoffray796d6302016-03-13 22:22:31 +00008114ArtMethod* ClassLinker::CreateRuntimeMethod(LinearAlloc* linear_alloc) {
Vladimir Marko14632852015-08-17 12:07:23 +01008115 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
8116 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008117 LengthPrefixedArray<ArtMethod>* method_array = AllocArtMethodArray(
8118 Thread::Current(),
Nicolas Geoffray796d6302016-03-13 22:22:31 +00008119 linear_alloc,
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008120 1);
Vladimir Markocf36d492015-08-12 19:27:26 +01008121 ArtMethod* method = &method_array->At(0, method_size, method_alignment);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008122 CHECK(method != nullptr);
8123 method->SetDexMethodIndex(DexFile::kDexNoIndex);
8124 CHECK(method->IsRuntimeMethod());
8125 return method;
8126}
8127
Andreas Gampe8ac75952015-06-02 21:01:45 -07008128void ClassLinker::DropFindArrayClassCache() {
8129 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
8130 find_array_class_cache_next_victim_ = 0;
8131}
8132
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07008133void ClassLinker::ClearClassTableStrongRoots() const {
8134 Thread* const self = Thread::Current();
8135 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8136 for (const ClassLoaderData& data : class_loaders_) {
8137 if (data.class_table != nullptr) {
8138 data.class_table->ClearStrongRoots();
8139 }
8140 }
8141}
8142
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008143void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008144 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008145 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07008146 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008147 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
8148 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008149 if (class_loader != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008150 visitor->Visit(class_loader.Ptr());
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008151 }
8152 }
8153}
8154
Mathieu Chartier00310e02015-10-17 12:46:42 -07008155void ClassLinker::InsertDexFileInToClassLoader(mirror::Object* dex_file,
8156 mirror::ClassLoader* class_loader) {
8157 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07008158 Thread* const self = Thread::Current();
8159 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierf2bf9d62016-04-12 16:54:48 -07008160 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07008161 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07008162 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07008163 // It was not already inserted, perform the write barrier to let the GC know the class loader's
8164 // class table was modified.
8165 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
8166 }
8167}
8168
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07008169void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008170 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07008171 std::vector<ClassLoaderData> to_delete;
8172 // Do the delete outside the lock to avoid lock violation in jit code cache.
8173 {
8174 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8175 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
8176 const ClassLoaderData& data = *it;
8177 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008178 ObjPtr<mirror::ClassLoader> class_loader =
8179 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07008180 if (class_loader != nullptr) {
8181 ++it;
8182 } else {
8183 VLOG(class_linker) << "Freeing class loader";
8184 to_delete.push_back(data);
8185 it = class_loaders_.erase(it);
8186 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008187 }
8188 }
Mathieu Chartier65975772016-08-05 10:46:36 -07008189 for (ClassLoaderData& data : to_delete) {
8190 DeleteClassLoader(self, data);
8191 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07008192}
8193
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008194std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08008195 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008196 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07008197 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008198 std::set<DexCacheResolvedClasses> ret;
8199 VLOG(class_linker) << "Collecting resolved classes";
8200 const uint64_t start_time = NanoTime();
8201 ReaderMutexLock mu(soa.Self(), *DexLock());
8202 // Loop through all the dex caches and inspect resolved classes.
8203 for (const ClassLinker::DexCacheData& data : GetDexCachesData()) {
8204 if (soa.Self()->IsJWeakCleared(data.weak_root)) {
8205 continue;
8206 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008207 ObjPtr<mirror::DexCache> dex_cache = soa.Decode<mirror::DexCache>(data.weak_root);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008208 if (dex_cache == nullptr) {
8209 continue;
8210 }
8211 const DexFile* dex_file = dex_cache->GetDexFile();
8212 const std::string& location = dex_file->GetLocation();
8213 const size_t num_class_defs = dex_file->NumClassDefs();
8214 // Use the resolved types, this will miss array classes.
8215 const size_t num_types = dex_file->NumTypeIds();
8216 VLOG(class_linker) << "Collecting class profile for dex file " << location
8217 << " types=" << num_types << " class_defs=" << num_class_defs;
8218 DexCacheResolvedClasses resolved_classes(dex_file->GetLocation(),
Mathieu Chartier9275af62016-04-29 12:03:56 -07008219 dex_file->GetBaseLocation(),
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008220 dex_file->GetLocationChecksum());
8221 size_t num_resolved = 0;
8222 std::unordered_set<uint16_t> class_set;
8223 CHECK_EQ(num_types, dex_cache->NumResolvedTypes());
8224 for (size_t i = 0; i < num_types; ++i) {
8225 mirror::Class* klass = dex_cache->GetResolvedType(i);
8226 // Filter out null class loader since that is the boot class loader.
8227 if (klass == nullptr || (ignore_boot_classes && klass->GetClassLoader() == nullptr)) {
8228 continue;
8229 }
8230 ++num_resolved;
8231 DCHECK(!klass->IsProxyClass());
Andreas Gampe4309f612016-03-09 15:52:21 -08008232 if (!klass->IsResolved()) {
8233 DCHECK(klass->IsErroneous());
8234 continue;
8235 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008236 mirror::DexCache* klass_dex_cache = klass->GetDexCache();
8237 if (klass_dex_cache == dex_cache) {
8238 const size_t class_def_idx = klass->GetDexClassDefIndex();
8239 DCHECK(klass->IsResolved());
8240 CHECK_LT(class_def_idx, num_class_defs);
8241 class_set.insert(class_def_idx);
8242 }
8243 }
8244
8245 if (!class_set.empty()) {
8246 auto it = ret.find(resolved_classes);
8247 if (it != ret.end()) {
8248 // Already have the key, union the class def idxs.
8249 it->AddClasses(class_set.begin(), class_set.end());
8250 } else {
8251 resolved_classes.AddClasses(class_set.begin(), class_set.end());
8252 ret.insert(resolved_classes);
8253 }
8254 }
8255
8256 VLOG(class_linker) << "Dex location " << location << " has " << num_resolved << " / "
8257 << num_class_defs << " resolved classes";
8258 }
8259 VLOG(class_linker) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
8260 return ret;
8261}
8262
8263std::unordered_set<std::string> ClassLinker::GetClassDescriptorsForProfileKeys(
8264 const std::set<DexCacheResolvedClasses>& classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08008265 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008266 std::unordered_set<std::string> ret;
8267 Thread* const self = Thread::Current();
8268 std::unordered_map<std::string, const DexFile*> location_to_dex_file;
8269 ScopedObjectAccess soa(self);
Mathieu Chartier268764d2016-09-13 12:09:38 -07008270 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008271 ReaderMutexLock mu(self, *DexLock());
8272 for (const ClassLinker::DexCacheData& data : GetDexCachesData()) {
8273 if (!self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07008274 ObjPtr<mirror::DexCache> dex_cache = soa.Decode<mirror::DexCache>(data.weak_root);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08008275 if (dex_cache != nullptr) {
8276 const DexFile* dex_file = dex_cache->GetDexFile();
8277 // There could be duplicates if two dex files with the same location are mapped.
8278 location_to_dex_file.emplace(
8279 ProfileCompilationInfo::GetProfileDexFileKey(dex_file->GetLocation()), dex_file);
8280 }
8281 }
8282 }
8283 for (const DexCacheResolvedClasses& info : classes) {
8284 const std::string& profile_key = info.GetDexLocation();
8285 auto found = location_to_dex_file.find(profile_key);
8286 if (found != location_to_dex_file.end()) {
8287 const DexFile* dex_file = found->second;
8288 VLOG(profiler) << "Found opened dex file for " << dex_file->GetLocation() << " with "
8289 << info.GetClasses().size() << " classes";
8290 DCHECK_EQ(dex_file->GetLocationChecksum(), info.GetLocationChecksum());
8291 for (uint16_t class_def_idx : info.GetClasses()) {
8292 if (class_def_idx >= dex_file->NumClassDefs()) {
8293 LOG(WARNING) << "Class def index " << class_def_idx << " >= " << dex_file->NumClassDefs();
8294 continue;
8295 }
8296 const DexFile::TypeId& type_id = dex_file->GetTypeId(
8297 dex_file->GetClassDef(class_def_idx).class_idx_);
8298 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
8299 ret.insert(descriptor);
8300 }
8301 } else {
8302 VLOG(class_linker) << "Failed to find opened dex file for profile key " << profile_key;
8303 }
8304 }
8305 return ret;
8306}
8307
Mathieu Chartier65975772016-08-05 10:46:36 -07008308class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
8309 public:
8310 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
8311 : method_(method),
8312 pointer_size_(pointer_size) {}
8313
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07008314 bool operator()(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) OVERRIDE {
Mathieu Chartier65975772016-08-05 10:46:36 -07008315 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
8316 holder_ = klass;
8317 }
8318 // Return false to stop searching if holder_ is not null.
8319 return holder_ == nullptr;
8320 }
8321
8322 mirror::Class* holder_ = nullptr;
8323 const ArtMethod* const method_;
8324 const PointerSize pointer_size_;
8325};
8326
8327mirror::Class* ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
8328 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
8329 CHECK(method->IsCopied());
8330 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
8331 VisitClasses(&visitor);
8332 return visitor.holder_;
8333}
8334
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008335// Instantiate ResolveMethod.
8336template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::kForceICCECheck>(
8337 const DexFile& dex_file,
8338 uint32_t method_idx,
8339 Handle<mirror::DexCache> dex_cache,
8340 Handle<mirror::ClassLoader> class_loader,
8341 ArtMethod* referrer,
8342 InvokeType type);
8343template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::kNoICCECheckForCache>(
8344 const DexFile& dex_file,
8345 uint32_t method_idx,
8346 Handle<mirror::DexCache> dex_cache,
8347 Handle<mirror::ClassLoader> class_loader,
8348 ArtMethod* referrer,
8349 InvokeType type);
8350
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008351} // namespace art