blob: cdb7712211138a0720d997c639a533e68cead84a [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"
Vladimir Marko80afd022015-05-19 18:08:00 +010039#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080040#include "base/unix_file/fd_file.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070041#include "base/value_object.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "class_linker-inl.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070043#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000044#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080045#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070046#include "dex_file-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070047#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070048#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070049#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070050#include "gc/accounting/card_table-inl.h"
51#include "gc/accounting/heap_bitmap.h"
52#include "gc/heap.h"
53#include "gc/space/image_space.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070054#include "handle_scope-inl.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070055#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070056#include "interpreter/interpreter.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080057#include "jit/jit.h"
58#include "jit/jit_code_cache.h"
Ian Rogers0571d352011-11-03 19:51:38 -070059#include "leb128.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070060#include "linear_alloc.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/class.h"
62#include "mirror/class-inl.h"
63#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070064#include "mirror/dex_cache-inl.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070065#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080066#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070067#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080068#include "mirror/object-inl.h"
69#include "mirror/object_array-inl.h"
70#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070071#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080072#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070073#include "mirror/string-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070074#include "native/dalvik_system_DexFile.h"
75#include "oat.h"
76#include "oat_file.h"
77#include "oat_file-inl.h"
78#include "oat_file_assistant.h"
79#include "oat_file_manager.h"
80#include "object_lock.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080081#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070082#include "runtime.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070083#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070084#include "scoped_thread_state_change.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070085#include "thread-inl.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -070086#include "trace.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070087#include "utils.h"
Vladimir Marko05792b92015-08-03 11:56:49 +010088#include "utils/dex_cache_arrays_layout-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080089#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070090#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070091
92namespace art {
93
Mathieu Chartierc7853442015-03-27 14:35:38 -070094static constexpr bool kSanityCheckObjects = kIsDebugBuild;
95
Ian Rogers00f7d0e2012-07-19 15:28:27 -070096static void ThrowNoClassDefFoundError(const char* fmt, ...)
97 __attribute__((__format__(__printf__, 1, 2)))
Mathieu Chartier90443472015-07-16 20:32:27 -070098 SHARED_REQUIRES(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070099static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700100 va_list args;
101 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800102 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000103 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800104 va_end(args);
105}
106
Andreas Gampe99babb62015-11-02 16:20:00 -0800107static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
108 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700109 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700110 StackHandleScope<1> hs(self);
111 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700112 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Andreas Gampe99babb62015-11-02 16:20:00 -0800113 mirror::Class* exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700114
115 if (exception_class == nullptr) {
116 // No exc class ~ no <init>-with-string.
117 CHECK(self->IsExceptionPending());
118 self->ClearException();
119 return false;
120 }
121
Mathieu Chartiere401d142015-04-22 13:56:20 -0700122 ArtMethod* exception_init_method = exception_class->FindDeclaredDirectMethod(
Andreas Gampe99babb62015-11-02 16:20:00 -0800123 "<init>", "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700124 return exception_init_method != nullptr;
125}
126
Andreas Gampe99babb62015-11-02 16:20:00 -0800127// Helper for ThrowEarlierClassFailure. Throws the stored error.
128static void HandleEarlierVerifyError(Thread* self, ClassLinker* class_linker, mirror::Class* c)
129 SHARED_REQUIRES(Locks::mutator_lock_) {
130 mirror::Object* obj = c->GetVerifyError();
131 DCHECK(obj != nullptr);
132 self->AssertNoPendingException();
133 if (obj->IsClass()) {
134 // Previous error has been stored as class. Create a new exception of that type.
135
136 // It's possible the exception doesn't have a <init>(String).
137 std::string temp;
138 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
139
140 if (HasInitWithString(self, class_linker, descriptor)) {
141 self->ThrowNewException(descriptor, PrettyDescriptor(c).c_str());
142 } else {
143 self->ThrowNewException(descriptor, nullptr);
144 }
145 } else {
146 // Previous error has been stored as an instance. Just rethrow.
147 mirror::Class* throwable_class =
148 self->DecodeJObject(WellKnownClasses::java_lang_Throwable)->AsClass();
149 mirror::Class* error_class = obj->GetClass();
150 CHECK(throwable_class->IsAssignableFrom(error_class));
151 self->SetException(obj->AsThrowable());
152 }
153 self->AssertPendingException();
154}
155
Andreas Gampecb086952015-11-02 16:20:00 -0800156void ClassLinker::ThrowEarlierClassFailure(mirror::Class* c, bool wrap_in_no_class_def) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700157 // The class failed to initialize on a previous attempt, so we want to throw
158 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
159 // failed in verification, in which case v2 5.4.1 says we need to re-throw
160 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800161 Runtime* const runtime = Runtime::Current();
162 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700163 std::string extra;
Andreas Gampe99babb62015-11-02 16:20:00 -0800164 if (c->GetVerifyError() != nullptr) {
165 mirror::Class* descr_from = c->GetVerifyError()->IsClass()
166 ? c->GetVerifyError()->AsClass()
167 : c->GetVerifyError()->GetClass();
168 extra = PrettyDescriptor(descr_from);
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700169 }
170 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c) << ": " << extra;
Ian Rogers87e552d2012-08-31 15:54:48 -0700171 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700172
Elliott Hughes5c599942012-06-13 16:45:05 -0700173 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800174 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800175 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700176 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
177 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000178 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700179 } else {
Andreas Gampe99babb62015-11-02 16:20:00 -0800180 if (c->GetVerifyError() != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800181 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800182 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800183 }
184 if (c->GetVerifyError() == nullptr || wrap_in_no_class_def) {
185 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
186 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
187 // exception will be a cause.
188 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
189 PrettyDescriptor(c).c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700190 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700191 }
192}
193
Brian Carlstromb23eab12014-10-08 17:55:21 -0700194static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Mathieu Chartier90443472015-07-16 20:32:27 -0700195 SHARED_REQUIRES(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700196 if (VLOG_IS_ON(class_linker)) {
197 std::string temp;
198 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000199 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700200 }
201}
202
203static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Mathieu Chartier90443472015-07-16 20:32:27 -0700204 SHARED_REQUIRES(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700205 Thread* self = Thread::Current();
206 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700207
208 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700209 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700210
211 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700212 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
213 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700214
Elliott Hughesa4f94742012-05-29 16:28:38 -0700215 // We only wrap non-Error exceptions; an Error can just be used as-is.
216 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000217 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700218 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700219 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700220}
221
Fred Shih381e4ca2014-08-25 17:24:27 -0700222// Gap between two fields in object layout.
223struct FieldGap {
224 uint32_t start_offset; // The offset from the start of the object.
225 uint32_t size; // The gap size of 1, 2, or 4 bytes.
226};
227struct FieldGapsComparator {
228 explicit FieldGapsComparator() {
229 }
230 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
231 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800232 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700233 // Note that the priority queue returns the largest element, so operator()
234 // should return true if lhs is less than rhs.
235 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700236 }
237};
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700238typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
Fred Shih381e4ca2014-08-25 17:24:27 -0700239
240// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800241static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700242 DCHECK(gaps != nullptr);
243
244 uint32_t current_offset = gap_start;
245 while (current_offset != gap_end) {
246 size_t remaining = gap_end - current_offset;
247 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
248 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
249 current_offset += sizeof(uint32_t);
250 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
251 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
252 current_offset += sizeof(uint16_t);
253 } else {
254 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
255 current_offset += sizeof(uint8_t);
256 }
257 DCHECK_LE(current_offset, gap_end) << "Overran gap";
258 }
259}
260// Shuffle fields forward, making use of gaps whenever possible.
261template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000262static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700263 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700264 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700265 FieldGaps* gaps)
Mathieu Chartier90443472015-07-16 20:32:27 -0700266 SHARED_REQUIRES(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700267 DCHECK(current_field_idx != nullptr);
268 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700269 DCHECK(gaps != nullptr);
270 DCHECK(field_offset != nullptr);
271
272 DCHECK(IsPowerOfTwo(n));
273 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700274 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700275 Primitive::Type type = field->GetTypeAsPrimitiveType();
276 if (Primitive::ComponentSize(type) < n) {
277 break;
278 }
279 if (!IsAligned<n>(field_offset->Uint32Value())) {
280 MemberOffset old_offset = *field_offset;
281 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
282 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
283 }
284 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
285 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700286 if (!gaps->empty() && gaps->top().size >= n) {
287 FieldGap gap = gaps->top();
288 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100289 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700290 field->SetOffset(MemberOffset(gap.start_offset));
291 if (gap.size > n) {
292 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
293 }
294 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100295 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700296 field->SetOffset(*field_offset);
297 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
298 }
299 ++(*current_field_idx);
300 }
301}
302
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800303ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700304 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700305 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700306 dex_cache_image_class_lookup_required_(false),
307 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800308 class_roots_(nullptr),
309 array_iftable_(nullptr),
310 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700311 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800312 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700313 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800314 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800315 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100316 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800317 quick_to_interpreter_bridge_trampoline_(nullptr),
318 image_pointer_size_(sizeof(void*)) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700319 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700320 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
321 "Array cache size wrong.");
322 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700323}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700324
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800325void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800326 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700327
Mathieu Chartiere401d142015-04-22 13:56:20 -0700328 Thread* const self = Thread::Current();
329 Runtime* const runtime = Runtime::Current();
330 gc::Heap* const heap = runtime->GetHeap();
331
332 CHECK(!heap->HasImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700333 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700334
Mathieu Chartiere401d142015-04-22 13:56:20 -0700335 // Use the pointer size from the runtime since we are probably creating the image.
336 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
337
Elliott Hughes30646832011-10-13 16:59:46 -0700338 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700339 // 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 -0800340 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700341 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700342 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700343 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700344 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700345 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700346 mirror::Class::SetClassClass(java_lang_Class.Get());
347 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700348 if (kUseBakerOrBrooksReadBarrier) {
349 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800350 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700351 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700352 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800353 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800354 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700355
Elliott Hughes418d20f2011-09-22 14:00:39 -0700356 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700357 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700358 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700359 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700360 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700361
Ian Rogers23435d02012-09-24 11:23:12 -0700362 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700363 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700364 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700365 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700366 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700367 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700368 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700369
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700370 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
371 runtime->SetSentinel(heap->AllocObject<true>(self,
372 java_lang_Object.Get(),
373 java_lang_Object->GetObjectSize(),
374 VoidFunctor()));
375
Ian Rogers23435d02012-09-24 11:23:12 -0700376 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700377 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700378 AllocClass(self, java_lang_Class.Get(),
379 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700380 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700381
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700382 // Setup the char (primitive) class to be used for char[].
383 Handle<mirror::Class> char_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700384 AllocClass(self, java_lang_Class.Get(),
385 mirror::Class::PrimitiveClassSize(image_pointer_size_))));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700386 // The primitive char class won't be initialized by
387 // InitializePrimitiveClass until line 459, but strings (and
388 // internal char arrays) will be allocated before that and the
389 // component size, which is computed from the primitive type, needs
390 // to be set here.
391 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700392
Ian Rogers23435d02012-09-24 11:23:12 -0700393 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700394 Handle<mirror::Class> char_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700395 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700396 char_array_class->SetComponentType(char_class.Get());
397 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700398
Ian Rogers23435d02012-09-24 11:23:12 -0700399 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700400 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700401 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700402 java_lang_String->SetStringClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700403 mirror::String::SetClass(java_lang_String.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700404 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400405
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700406 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700407 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700408 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700409 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
410 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700411 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700412
Ian Rogers23435d02012-09-24 11:23:12 -0700413 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700414 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700415 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
416 kClassRootsMax));
417 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700418 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
419 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
420 SetClassRoot(kClassArrayClass, class_array_class.Get());
421 SetClassRoot(kObjectArrayClass, object_array_class.Get());
422 SetClassRoot(kCharArrayClass, char_array_class.Get());
423 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700424 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700425
426 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700427 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
428 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
429 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
430 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
431 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
432 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
433 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
434 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700435
Ian Rogers23435d02012-09-24 11:23:12 -0700436 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700437 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700438
Ian Rogers23435d02012-09-24 11:23:12 -0700439 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700440 Handle<mirror::Class> int_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700441 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700442 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700443 mirror::IntArray::SetArrayClass(int_array_class.Get());
444 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700445
Mathieu Chartierc7853442015-03-27 14:35:38 -0700446 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
447 Handle<mirror::Class> long_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700448 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700449 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
450 mirror::LongArray::SetArrayClass(long_array_class.Get());
451 SetClassRoot(kLongArrayClass, long_array_class.Get());
452
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700453 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700454
Ian Rogers52813c92012-10-11 11:50:38 -0700455 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700456 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700457 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700458 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100459 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700460 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700461 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700462
Mathieu Chartier66f19252012-09-18 08:57:04 -0700463 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700464 Handle<mirror::Class> object_array_string(hs.NewHandle(
465 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700466 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700467 object_array_string->SetComponentType(java_lang_String.Get());
468 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700469
Mathieu Chartiere401d142015-04-22 13:56:20 -0700470 // Create runtime resolution and imt conflict methods.
471 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
472 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
473 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700474
Ian Rogers23435d02012-09-24 11:23:12 -0700475 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
476 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
477 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700478 CHECK_NE(0U, boot_class_path.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800479 for (auto& dex_file : boot_class_path) {
480 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700481 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800482 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700483 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700484
485 // now we can use FindSystemClass
486
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700487 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700488 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
489 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700490
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700491 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
492 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700493 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800494 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700495 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700496 quick_resolution_trampoline_ = GetQuickResolutionStub();
497 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
498 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700499 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700500
Mathieu Chartier66f19252012-09-18 08:57:04 -0700501 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700502 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700503 CHECK_EQ(java_lang_Object.Get(), FindSystemClass(self, "Ljava/lang/Object;"));
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700504 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700505 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800506 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700507 if (java_lang_String.Get() != String_class) {
508 std::ostringstream os1, os2;
509 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
510 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
511 LOG(FATAL) << os1.str() << "\n\n" << os2.str();
512 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700513 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700514 CHECK_EQ(java_lang_DexCache.Get(), FindSystemClass(self, "Ljava/lang/DexCache;"));
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700515 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700516
Ian Rogers23435d02012-09-24 11:23:12 -0700517 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800518 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800519 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700520
Ian Rogers98379392014-02-24 16:53:16 -0800521 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800522 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700523
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700524 CHECK_EQ(char_array_class.Get(), FindSystemClass(self, "[C"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700525
Ian Rogers98379392014-02-24 16:53:16 -0800526 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800527 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700528
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700529 CHECK_EQ(int_array_class.Get(), FindSystemClass(self, "[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700530
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700531 CHECK_EQ(long_array_class.Get(), FindSystemClass(self, "[J"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700532
Ian Rogers98379392014-02-24 16:53:16 -0800533 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800534 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700535
Ian Rogers98379392014-02-24 16:53:16 -0800536 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800537 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700538
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700539 CHECK_EQ(class_array_class.Get(), FindSystemClass(self, "[Ljava/lang/Class;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700540
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700541 CHECK_EQ(object_array_class.Get(), FindSystemClass(self, "[Ljava/lang/Object;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700542
Ian Rogers23435d02012-09-24 11:23:12 -0700543 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700544 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
545 CHECK(java_lang_Cloneable.Get() != nullptr);
546 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
547 CHECK(java_io_Serializable.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700548 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
549 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700550 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
551 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700552
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700553 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
554 // suspension.
555 CHECK_EQ(java_lang_Cloneable.Get(),
556 mirror::Class::GetDirectInterface(self, class_array_class, 0));
557 CHECK_EQ(java_io_Serializable.Get(),
558 mirror::Class::GetDirectInterface(self, class_array_class, 1));
559 CHECK_EQ(java_lang_Cloneable.Get(),
560 mirror::Class::GetDirectInterface(self, object_array_class, 0));
561 CHECK_EQ(java_io_Serializable.Get(),
562 mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700563 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700564 // dex_cache_ fields and register them in class_table_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700565 CHECK_EQ(java_lang_Class.Get(), FindSystemClass(self, "Ljava/lang/Class;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700566
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700567 CHECK_EQ(object_array_string.Get(),
568 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700569
Ian Rogers23435d02012-09-24 11:23:12 -0700570 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700571
Ian Rogers23435d02012-09-24 11:23:12 -0700572 // Create java.lang.reflect.Proxy root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700573 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700574
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700575 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700576 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
577 CHECK(class_root != nullptr);
578 SetClassRoot(kJavaLangReflectField, class_root);
579 mirror::Field::SetClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700580
581 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700582 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
583 CHECK(class_root != nullptr);
584 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
585 mirror::Field::SetArrayClass(class_root);
586
587 // Create java.lang.reflect.Constructor.class root and array root.
588 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
589 CHECK(class_root != nullptr);
590 SetClassRoot(kJavaLangReflectConstructor, class_root);
591 mirror::Constructor::SetClass(class_root);
592 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
593 CHECK(class_root != nullptr);
594 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
595 mirror::Constructor::SetArrayClass(class_root);
596
597 // Create java.lang.reflect.Method.class root and array root.
598 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
599 CHECK(class_root != nullptr);
600 SetClassRoot(kJavaLangReflectMethod, class_root);
601 mirror::Method::SetClass(class_root);
602 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
603 CHECK(class_root != nullptr);
604 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
605 mirror::Method::SetArrayClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700606
Brian Carlstrom1f870082011-08-23 16:02:11 -0700607 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700608 // finish initializing Reference class
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700609 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700610 CHECK_EQ(java_lang_ref_Reference.Get(), FindSystemClass(self, "Ljava/lang/ref/Reference;"));
Fred Shih4ee7a662014-07-11 09:59:27 -0700611 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700612 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
613 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700614 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700615 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700616 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700617 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700618 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700619 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700620 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700621 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700622 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700623 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700624 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700625 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700626
Ian Rogers23435d02012-09-24 11:23:12 -0700627 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700628 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700629 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700630 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
631 SetClassRoot(kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700632
jeffhao8cd6dda2012-02-22 10:15:34 -0800633 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700634 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800635 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800636 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700637 SetClassRoot(kJavaLangClassNotFoundException,
638 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800639 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700640 SetClassRoot(kJavaLangStackTraceElementArrayClass,
641 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800642 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700643
Andreas Gampe76bd8802014-12-10 16:43:58 -0800644 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
645 // initialized.
646 {
647 const DexFile& dex_file = java_lang_Object->GetDexFile();
Mathieu Chartier9507fa22015-10-29 15:08:57 -0700648 const DexFile::TypeId* void_type_id = dex_file.FindTypeId("V");
Andreas Gampe76bd8802014-12-10 16:43:58 -0800649 CHECK(void_type_id != nullptr);
650 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
651 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
652 // as referrer so the used dex cache is core's one.
653 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
654 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
655 self->AssertNoPendingException();
656 }
657
Ian Rogers98379392014-02-24 16:53:16 -0800658 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700659
Brian Carlstroma004aa92012-02-08 18:05:09 -0800660 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700661}
662
Ian Rogers98379392014-02-24 16:53:16 -0800663void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800664 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700665
666 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700667 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700668 // as the types of the field can't be resolved prior to the runtime being
669 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800670 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700671 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800672 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800673
Mathieu Chartierc7853442015-03-27 14:35:38 -0700674 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700675 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
676 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700677
Mathieu Chartierc7853442015-03-27 14:35:38 -0700678 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700679 CHECK_STREQ(queue->GetName(), "queue");
680 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700681
Mathieu Chartierc7853442015-03-27 14:35:38 -0700682 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700683 CHECK_STREQ(queueNext->GetName(), "queueNext");
684 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700685
Mathieu Chartierc7853442015-03-27 14:35:38 -0700686 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700687 CHECK_STREQ(referent->GetName(), "referent");
688 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700689
Mathieu Chartierc7853442015-03-27 14:35:38 -0700690 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700691 CHECK_STREQ(zombie->GetName(), "zombie");
692 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700693
Brian Carlstroma663ea52011-08-19 23:33:41 -0700694 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700695 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700696 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800697 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700698 CHECK(klass != nullptr);
699 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700700 // note SetClassRoot does additional validation.
701 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700702 }
703
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700704 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700705
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700706 // disable the slow paths in FindClass and CreatePrimitiveClass now
707 // that Object, Class, and Object[] are setup
708 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700709
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800710 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700711}
712
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700713void ClassLinker::RunRootClinits() {
714 Thread* self = Thread::Current();
715 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800716 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700717 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700718 StackHandleScope<1> hs(self);
719 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700720 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700721 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700722 }
723 }
724}
725
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -0700726static void SanityCheckArtMethod(ArtMethod* m,
727 mirror::Class* expected_class,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700728 gc::space::ImageSpace* space)
Mathieu Chartier90443472015-07-16 20:32:27 -0700729 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700730 if (m->IsRuntimeMethod()) {
731 CHECK(m->GetDeclaringClass() == nullptr) << PrettyMethod(m);
732 } else if (m->IsMiranda()) {
733 CHECK(m->GetDeclaringClass() != nullptr) << PrettyMethod(m);
734 } else if (expected_class != nullptr) {
735 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << PrettyMethod(m);
736 }
737 if (space != nullptr) {
738 auto& header = space->GetImageHeader();
739 auto& methods = header.GetMethodsSection();
740 auto offset = reinterpret_cast<uint8_t*>(m) - space->Begin();
741 CHECK(methods.Contains(offset)) << m << " not in " << methods;
742 }
743}
744
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -0700745static void SanityCheckArtMethodPointerArray(mirror::PointerArray* arr,
746 mirror::Class* expected_class,
747 size_t pointer_size,
748 gc::space::ImageSpace* space)
749 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700750 CHECK(arr != nullptr);
751 for (int32_t j = 0; j < arr->GetLength(); ++j) {
752 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size);
753 // expected_class == null means we are a dex cache.
754 if (expected_class != nullptr) {
755 CHECK(method != nullptr);
756 }
757 if (method != nullptr) {
758 SanityCheckArtMethod(method, expected_class, space);
Ian Rogers848871b2013-08-05 10:56:33 -0700759 }
760 }
761}
762
Vladimir Marko05792b92015-08-03 11:56:49 +0100763static void SanityCheckArtMethodPointerArray(
764 ArtMethod** arr,
765 size_t size,
766 size_t pointer_size,
767 gc::space::ImageSpace* space) SHARED_REQUIRES(Locks::mutator_lock_) {
768 CHECK_EQ(arr != nullptr, size != 0u);
769 if (arr != nullptr) {
770 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
771 CHECK(space->GetImageHeader().GetImageSection(
772 ImageHeader::kSectionDexCacheArrays).Contains(offset));
773 }
774 for (size_t j = 0; j < size; ++j) {
775 ArtMethod* method = mirror::DexCache::GetElementPtrSize(arr, j, pointer_size);
776 // expected_class == null means we are a dex cache.
777 if (method != nullptr) {
778 SanityCheckArtMethod(method, nullptr, space);
779 }
780 }
781}
782
Mathieu Chartiere401d142015-04-22 13:56:20 -0700783static void SanityCheckObjectsCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700784 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700785 DCHECK(obj != nullptr);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700786 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700787 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
788 if (obj->IsClass()) {
789 auto klass = obj->AsClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700790 for (ArtField& field : klass->GetIFields()) {
791 CHECK_EQ(field.GetDeclaringClass(), klass);
792 }
793 for (ArtField& field : klass->GetSFields()) {
794 CHECK_EQ(field.GetDeclaringClass(), klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700795 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700796 auto* runtime = Runtime::Current();
797 auto* image_space = runtime->GetHeap()->GetImageSpace();
798 auto pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
799 for (auto& m : klass->GetDirectMethods(pointer_size)) {
800 SanityCheckArtMethod(&m, klass, image_space);
801 }
802 for (auto& m : klass->GetVirtualMethods(pointer_size)) {
803 SanityCheckArtMethod(&m, klass, image_space);
804 }
805 auto* vtable = klass->GetVTable();
806 if (vtable != nullptr) {
807 SanityCheckArtMethodPointerArray(vtable, nullptr, pointer_size, image_space);
808 }
809 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
810 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
811 SanityCheckArtMethod(klass->GetEmbeddedImTableEntry(i, pointer_size), nullptr, image_space);
812 }
813 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
814 SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr, image_space);
815 }
816 }
817 auto* iftable = klass->GetIfTable();
818 if (iftable != nullptr) {
819 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
820 if (iftable->GetMethodArrayCount(i) > 0) {
821 SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr, pointer_size,
822 image_space);
823 }
824 }
825 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700826 }
827}
828
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200829// Set image methods' entry point to interpreter.
830class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
831 public:
832 explicit SetInterpreterEntrypointArtMethodVisitor(size_t image_pointer_size)
833 : image_pointer_size_(image_pointer_size) {}
834
835 void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
836 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
837 CHECK(method->GetDeclaringClass() != nullptr);
838 }
839 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
840 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
841 image_pointer_size_);
842 }
843 }
844
845 private:
846 const size_t image_pointer_size_;
847
848 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
849};
850
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700851void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800852 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700853 CHECK(!init_done_);
854
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700855 Runtime* const runtime = Runtime::Current();
856 Thread* const self = Thread::Current();
857 gc::Heap* const heap = runtime->GetHeap();
858 gc::space::ImageSpace* const space = heap->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700859 CHECK(space != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700860 image_pointer_size_ = space->GetImageHeader().GetPointerSize();
861 dex_cache_image_class_lookup_required_ = true;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700862 const OatFile* oat_file = runtime->GetOatFileManager().RegisterImageOatFile(space);
863 DCHECK(oat_file != nullptr);
864 CHECK_EQ(oat_file->GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
865 CHECK_EQ(oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
866 const char* image_file_location = oat_file->GetOatHeader().
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700867 GetStoreValueByKey(OatHeader::kImageLocationKey);
868 CHECK(image_file_location == nullptr || *image_file_location == 0);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700869 quick_resolution_trampoline_ = oat_file->GetOatHeader().GetQuickResolutionTrampoline();
870 quick_imt_conflict_trampoline_ = oat_file->GetOatHeader().GetQuickImtConflictTrampoline();
871 quick_generic_jni_trampoline_ = oat_file->GetOatHeader().GetQuickGenericJniTrampoline();
872 quick_to_interpreter_bridge_trampoline_ = oat_file->GetOatHeader().GetQuickToInterpreterBridge();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700873 StackHandleScope<2> hs(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800874 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700875 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
876 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700877
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700878 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
879 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
880 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700881 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700882
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700883 // Special case of setting up the String class early so that we can test arbitrary objects
884 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700885 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800886
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700887 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
888 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
889 Runtime::Current()->SetSentinel(Runtime::Current()->GetHeap()->AllocObject<true>(self,
890 java_lang_Object,
891 java_lang_Object->GetObjectSize(),
892 VoidFunctor()));
893
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700894 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700895 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700896 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800897 StackHandleScope<1> hs2(self);
898 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700899 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700900 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location.c_str(),
901 nullptr);
902 CHECK(oat_dex_file != nullptr) << oat_file->GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700903 std::string error_msg;
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700904 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700905 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700906 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700907 << " from within oat file " << oat_file->GetLocation()
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700908 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -0800909 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700910 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700911
Mathieu Chartiere401d142015-04-22 13:56:20 -0700912 if (kSanityCheckObjects) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100913 SanityCheckArtMethodPointerArray(dex_cache->GetResolvedMethods(),
914 dex_cache->NumResolvedMethods(),
915 image_pointer_size_,
916 space);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700917 }
918
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700919 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
920
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800921 AppendToBootClassPath(*dex_file.get(), dex_cache);
922 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700923 }
924
Mathieu Chartiere401d142015-04-22 13:56:20 -0700925 CHECK(ValidPointerSize(image_pointer_size_)) << image_pointer_size_;
926
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700927 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
928 // bitmap walk.
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700929 if (!runtime->IsAotCompiler()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700930 // Only the Aot compiler supports having an image with a different pointer size than the
931 // runtime. This happens on the host for compile 32 bit tests since we use a 64 bit libart
932 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
933 CHECK_EQ(image_pointer_size_, sizeof(void*));
Mathieu Chartier2d721012014-11-10 11:08:06 -0800934 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700935
Mathieu Chartierc7853442015-03-27 14:35:38 -0700936 if (kSanityCheckObjects) {
937 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
938 auto* dex_cache = dex_caches->Get(i);
939 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
940 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
941 if (field != nullptr) {
942 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
943 }
944 }
945 }
946 heap->VisitObjects(SanityCheckObjectsCallback, nullptr);
947 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700948
Mathieu Chartiere401d142015-04-22 13:56:20 -0700949 // Set entry point to interpreter if in InterpretOnly mode.
950 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200951 const ImageHeader& header = space->GetImageHeader();
952 const ImageSection& methods = header.GetMethodsSection();
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200953 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +0100954 methods.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700955 }
956
Brian Carlstroma663ea52011-08-19 23:33:41 -0700957 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800958 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700959 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700960
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800961 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700962 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800963 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800964 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700965 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
966 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700967 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
968 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
969 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
970 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
Fred Shih4ee7a662014-07-11 09:59:27 -0700971 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800972 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
973 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
974 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
975 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
976 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
977 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
978 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
979 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
980 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
981 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700982
Ian Rogers98379392014-02-24 16:53:16 -0800983 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700984
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800985 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700986}
987
Mathieu Chartiere401d142015-04-22 13:56:20 -0700988bool ClassLinker::ClassInClassTable(mirror::Class* klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -0700989 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
990 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700991}
992
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700993void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -0700994 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
995 // enabling tracing requires the mutator lock, there are no race conditions here.
996 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -0700997 Thread* const self = Thread::Current();
998 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700999 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
1000 visitor, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001001 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001002 // Argument for how root visiting deals with ArtField and ArtMethod roots.
1003 // There is 3 GC cases to handle:
1004 // Non moving concurrent:
1005 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001006 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001007 //
1008 // Moving non-concurrent:
1009 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
1010 // To prevent missing roots, this case needs to ensure that there is no
1011 // suspend points between the point which we allocate ArtMethod arrays and place them in a
1012 // class which is in the class table.
1013 //
1014 // Moving concurrent:
1015 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
1016 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001017 boot_class_table_.VisitRoots(buffered_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07001018
1019 // If tracing is enabled, then mark all the class loaders to prevent unloading.
1020 if (tracing_enabled) {
1021 for (const ClassLoaderData& data : class_loaders_) {
1022 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
1023 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
1024 }
1025 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001026 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001027 for (auto& root : new_class_roots_) {
1028 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001029 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001030 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001031 // Concurrent moving GC marked new roots through the to-space invariant.
1032 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001033 }
1034 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001035 buffered_visitor.Flush(); // Flush before clearing new_class_roots_.
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001036 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1037 new_class_roots_.clear();
1038 }
1039 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1040 log_new_class_table_roots_ = true;
1041 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1042 log_new_class_table_roots_ = false;
1043 }
1044 // We deliberately ignore the class roots in the image since we
1045 // handle image roots by using the MS/CMS rescanning of dirty cards.
1046}
1047
Brian Carlstroma663ea52011-08-19 23:33:41 -07001048// Keep in sync with InitCallback. Anything we visit, we need to
1049// reinit references to when reinitializing a ClassLinker from a
1050// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001051void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07001052 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001053 VisitClassRoots(visitor, flags);
Mathieu Chartier31000802015-06-14 14:14:37 -07001054 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07001055 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
1056 // unloading if we are marking roots.
1057 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001058}
1059
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001060class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
1061 public:
1062 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
1063 : visitor_(visitor),
1064 done_(false) {}
1065
1066 void Visit(mirror::ClassLoader* class_loader)
1067 SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
1068 ClassTable* const class_table = class_loader->GetClassTable();
1069 if (!done_ && class_table != nullptr && !class_table->Visit(visitor_)) {
1070 // If the visitor ClassTable returns false it means that we don't need to continue.
1071 done_ = true;
1072 }
1073 }
1074
1075 private:
1076 ClassVisitor* const visitor_;
1077 // If done is true then we don't need to do any more visiting.
1078 bool done_;
1079};
1080
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001081void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07001082 if (boot_class_table_.Visit(visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001083 VisitClassLoaderClassesVisitor loader_visitor(visitor);
1084 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001085 }
1086}
1087
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001088void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001089 if (dex_cache_image_class_lookup_required_) {
1090 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001091 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001092 Thread* const self = Thread::Current();
1093 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1094 // Not safe to have thread suspension when we are holding a lock.
1095 if (self != nullptr) {
1096 ScopedAssertNoThreadSuspension nts(self, __FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001097 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001098 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001099 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08001100 }
1101}
1102
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001103class GetClassesInToVector : public ClassVisitor {
1104 public:
1105 bool Visit(mirror::Class* klass) OVERRIDE {
1106 classes_.push_back(klass);
1107 return true;
1108 }
1109 std::vector<mirror::Class*> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07001110};
1111
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001112class GetClassInToObjectArray : public ClassVisitor {
1113 public:
1114 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
1115 : arr_(arr), index_(0) {}
1116
1117 bool Visit(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
1118 ++index_;
1119 if (index_ <= arr_->GetLength()) {
1120 arr_->Set(index_ - 1, klass);
1121 return true;
1122 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001123 return false;
1124 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001125
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001126 bool Succeeded() const SHARED_REQUIRES(Locks::mutator_lock_) {
1127 return index_ <= arr_->GetLength();
1128 }
1129
1130 private:
1131 mirror::ObjectArray<mirror::Class>* const arr_;
1132 int32_t index_;
1133};
1134
1135void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001136 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1137 // is avoiding duplicates.
1138 if (!kMovingClasses) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001139 GetClassesInToVector accumulator;
1140 VisitClasses(&accumulator);
1141 for (mirror::Class* klass : accumulator.classes_) {
1142 if (!visitor->Visit(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001143 return;
1144 }
1145 }
1146 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001147 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001148 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001149 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07001150 // We size the array assuming classes won't be added to the class table during the visit.
1151 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001152 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001153 size_t class_table_size;
1154 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001155 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001156 // Add 100 in case new classes get loaded when we are filling in the object array.
1157 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07001158 }
1159 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1160 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1161 classes.Assign(
1162 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1163 CHECK(classes.Get() != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001164 GetClassInToObjectArray accumulator(classes.Get());
1165 VisitClasses(&accumulator);
1166 if (accumulator.Succeeded()) {
1167 break;
1168 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001169 }
1170 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1171 // If the class table shrank during creation of the clases array we expect null elements. If
1172 // the class table grew then the loop repeats. If classes are created after the loop has
1173 // finished then we don't visit.
1174 mirror::Class* klass = classes->Get(i);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001175 if (klass != nullptr && !visitor->Visit(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001176 return;
1177 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001178 }
1179 }
1180}
1181
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001182ClassLinker::~ClassLinker() {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001183 mirror::Class::ResetClass();
1184 mirror::Constructor::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001185 mirror::Field::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001186 mirror::Method::ResetClass();
1187 mirror::Reference::ResetClass();
1188 mirror::StackTraceElement::ResetClass();
1189 mirror::String::ResetClass();
1190 mirror::Throwable::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001191 mirror::BooleanArray::ResetArrayClass();
1192 mirror::ByteArray::ResetArrayClass();
1193 mirror::CharArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001194 mirror::Constructor::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001195 mirror::DoubleArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001196 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001197 mirror::FloatArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001198 mirror::Method::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001199 mirror::IntArray::ResetArrayClass();
1200 mirror::LongArray::ResetArrayClass();
1201 mirror::ShortArray::ResetArrayClass();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001202 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07001203 for (const ClassLoaderData& data : class_loaders_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001204 DeleteClassLoader(self, data);
Mathieu Chartier6b069532015-08-05 15:08:12 -07001205 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001206 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001207}
1208
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001209void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data) {
1210 Runtime* const runtime = Runtime::Current();
1211 JavaVMExt* const vm = runtime->GetJavaVM();
1212 vm->DeleteWeakGlobalRef(self, data.weak_root);
1213 if (runtime->GetJit() != nullptr) {
1214 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
1215 if (code_cache != nullptr) {
1216 code_cache->RemoveMethodsIn(self, *data.allocator);
1217 }
1218 }
1219 delete data.allocator;
1220 delete data.class_table;
1221}
1222
Mathieu Chartiere401d142015-04-22 13:56:20 -07001223mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) {
1224 return down_cast<mirror::PointerArray*>(image_pointer_size_ == 8u ?
1225 static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length)) :
1226 static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length)));
1227}
1228
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001229mirror::DexCache* ClassLinker::AllocDexCache(Thread* self,
1230 const DexFile& dex_file,
1231 LinearAlloc* linear_alloc) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001232 StackHandleScope<6> hs(self);
1233 auto dex_cache(hs.NewHandle(down_cast<mirror::DexCache*>(
1234 GetClassRoot(kJavaLangDexCache)->AllocObject(self))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001235 if (dex_cache.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001236 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001237 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001238 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001239 auto location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001240 if (location.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001241 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001242 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001243 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001244 DexCacheArraysLayout layout(image_pointer_size_, &dex_file);
1245 uint8_t* raw_arrays = nullptr;
Vladimir Marko09d09432015-09-08 13:47:48 +01001246 if (dex_file.GetOatDexFile() != nullptr &&
1247 dex_file.GetOatDexFile()->GetDexCacheArrays() != nullptr) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +01001248 raw_arrays = dex_file.GetOatDexFile()->GetDexCacheArrays();
Vladimir Marko09d09432015-09-08 13:47:48 +01001249 } else if (dex_file.NumStringIds() != 0u || dex_file.NumTypeIds() != 0u ||
Vladimir Marko05792b92015-08-03 11:56:49 +01001250 dex_file.NumMethodIds() != 0u || dex_file.NumFieldIds() != 0u) {
1251 // NOTE: We "leak" the raw_arrays because we never destroy the dex cache.
1252 DCHECK(image_pointer_size_ == 4u || image_pointer_size_ == 8u);
Mathieu Chartier32cc9ee2015-10-15 09:19:15 -07001253 // Zero-initialized.
1254 raw_arrays = reinterpret_cast<uint8_t*>(linear_alloc->Alloc(self, layout.Size()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001255 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001256 GcRoot<mirror::String>* strings = (dex_file.NumStringIds() == 0u) ? nullptr :
1257 reinterpret_cast<GcRoot<mirror::String>*>(raw_arrays + layout.StringsOffset());
1258 GcRoot<mirror::Class>* types = (dex_file.NumTypeIds() == 0u) ? nullptr :
1259 reinterpret_cast<GcRoot<mirror::Class>*>(raw_arrays + layout.TypesOffset());
1260 ArtMethod** methods = (dex_file.NumMethodIds() == 0u) ? nullptr :
1261 reinterpret_cast<ArtMethod**>(raw_arrays + layout.MethodsOffset());
1262 ArtField** fields = (dex_file.NumFieldIds() == 0u) ? nullptr :
1263 reinterpret_cast<ArtField**>(raw_arrays + layout.FieldsOffset());
1264 dex_cache->Init(&dex_file,
1265 location.Get(),
1266 strings,
1267 dex_file.NumStringIds(),
1268 types,
1269 dex_file.NumTypeIds(),
1270 methods,
1271 dex_file.NumMethodIds(),
1272 fields,
1273 dex_file.NumFieldIds(),
1274 image_pointer_size_);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001275 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001276}
1277
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001278mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001279 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001280 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001281 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001282 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001283 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001284 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1285 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001286 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001287 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08001288 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001289 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001290 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001291}
1292
Ian Rogers6fac4472014-02-25 17:01:10 -08001293mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001294 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001295}
1296
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001297mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001298 Thread* self,
1299 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001300 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1301 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001302}
1303
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001304mirror::Class* ClassLinker::EnsureResolved(Thread* self,
1305 const char* descriptor,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001306 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001307 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001308
1309 // For temporary classes we must wait for them to be retired.
1310 if (init_done_ && klass->IsTemp()) {
1311 CHECK(!klass->IsResolved());
1312 if (klass->IsErroneous()) {
1313 ThrowEarlierClassFailure(klass);
1314 return nullptr;
1315 }
1316 StackHandleScope<1> hs(self);
1317 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1318 ObjectLock<mirror::Class> lock(self, h_class);
1319 // Loop and wait for the resolving thread to retire this class.
1320 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1321 lock.WaitIgnoringInterrupts();
1322 }
1323 if (h_class->IsErroneous()) {
1324 ThrowEarlierClassFailure(h_class.Get());
1325 return nullptr;
1326 }
1327 CHECK(h_class->IsRetired());
1328 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001329 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
1330 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001331 }
1332
Brian Carlstromaded5f72011-10-07 17:15:04 -07001333 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001334 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001335 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001336 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1337 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001338 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001339 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1340 ThrowClassCircularityError(h_class.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001341 mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001342 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001343 }
1344 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001345 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001346 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001347 }
1348 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001349
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001350 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001351 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001352 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001353 }
1354 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001355 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001356 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001357 return klass;
1358}
1359
Ian Rogers68b56852014-08-29 20:19:11 -07001360typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
1361
1362// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001363ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001364 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001365 for (const DexFile* dex_file : class_path) {
1366 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001367 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07001368 return ClassPathEntry(dex_file, dex_class_def);
1369 }
1370 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001371 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07001372}
1373
Andreas Gampef865ea92015-04-13 22:14:19 -07001374static bool IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1375 mirror::ClassLoader* class_loader)
Mathieu Chartier90443472015-07-16 20:32:27 -07001376 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampef865ea92015-04-13 22:14:19 -07001377 return class_loader == nullptr ||
1378 class_loader->GetClass() ==
1379 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader);
1380}
1381
1382bool ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001383 Thread* self,
1384 const char* descriptor,
Andreas Gampef865ea92015-04-13 22:14:19 -07001385 size_t hash,
1386 Handle<mirror::ClassLoader> class_loader,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001387 mirror::Class** result) {
Andreas Gampef865ea92015-04-13 22:14:19 -07001388 // Termination case: boot class-loader.
1389 if (IsBootClassLoader(soa, class_loader.Get())) {
1390 // The boot class loader, search the boot class path.
1391 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
1392 if (pair.second != nullptr) {
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001393 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Andreas Gampef865ea92015-04-13 22:14:19 -07001394 if (klass != nullptr) {
1395 *result = EnsureResolved(self, descriptor, klass);
1396 } else {
1397 *result = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(),
1398 *pair.first, *pair.second);
1399 }
1400 if (*result == nullptr) {
1401 CHECK(self->IsExceptionPending()) << descriptor;
1402 self->ClearException();
1403 }
Ian Rogers32427292014-11-19 14:05:21 -08001404 } else {
Andreas Gampef865ea92015-04-13 22:14:19 -07001405 *result = nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001406 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001407 return true;
1408 }
1409
1410 // Unsupported class-loader?
1411 if (class_loader->GetClass() !=
1412 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)) {
1413 *result = nullptr;
1414 return false;
1415 }
1416
1417 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
1418 StackHandleScope<4> hs(self);
1419 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
1420 bool recursive_result = FindClassInPathClassLoader(soa, self, descriptor, hash, h_parent, result);
1421
1422 if (!recursive_result) {
1423 // Something wrong up the chain.
1424 return false;
1425 }
1426
1427 if (*result != nullptr) {
1428 // Found the class up the chain.
1429 return true;
1430 }
1431
1432 // Handle this step.
1433 // Handle as if this is the child PathClassLoader.
1434 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
1435 // We need to get the DexPathList and loop through it.
1436 ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
1437 ArtField* const dex_file_field =
1438 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
1439 mirror::Object* dex_path_list =
1440 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
1441 GetObject(class_loader.Get());
1442 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
1443 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1444 mirror::Object* dex_elements_obj =
1445 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1446 GetObject(dex_path_list);
1447 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1448 // at the mCookie which is a DexFile vector.
1449 if (dex_elements_obj != nullptr) {
1450 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
1451 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
1452 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
1453 mirror::Object* element = dex_elements->GetWithoutChecks(i);
1454 if (element == nullptr) {
1455 // Should never happen, fall back to java code to throw a NPE.
1456 break;
1457 }
1458 mirror::Object* dex_file = dex_file_field->GetObject(element);
1459 if (dex_file != nullptr) {
1460 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
1461 if (long_array == nullptr) {
1462 // This should never happen so log a warning.
1463 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001464 break;
1465 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001466 int32_t long_array_size = long_array->GetLength();
Mathieu Chartiere58991b2015-10-13 07:59:34 -07001467 // First element is the oat file.
1468 for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) {
Andreas Gampef865ea92015-04-13 22:14:19 -07001469 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
1470 long_array->GetWithoutChecks(j)));
1471 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
1472 if (dex_class_def != nullptr) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -07001473 mirror::Class* klass = DefineClass(self,
1474 descriptor,
1475 hash,
1476 class_loader,
1477 *cp_dex_file,
1478 *dex_class_def);
Andreas Gampef865ea92015-04-13 22:14:19 -07001479 if (klass == nullptr) {
1480 CHECK(self->IsExceptionPending()) << descriptor;
1481 self->ClearException();
1482 // TODO: Is it really right to break here, and not check the other dex files?
1483 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001484 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001485 *result = klass;
1486 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001487 }
1488 }
1489 }
1490 }
1491 }
Ian Rogers32427292014-11-19 14:05:21 -08001492 self->AssertNoPendingException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001493 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001494
1495 // Result is still null from the parent call, no need to set it again...
1496 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001497}
1498
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001499mirror::Class* ClassLinker::FindClass(Thread* self,
1500 const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001501 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001502 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001503 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001504 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001505 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001506 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1507 // for primitive classes that aren't backed by dex files.
1508 return FindPrimitiveClass(descriptor[0]);
1509 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001510 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001511 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001512 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07001513 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001514 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001515 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001516 // Class is not yet loaded.
1517 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001518 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001519 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001520 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001521 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07001522 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001523 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07001524 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07001525 } else {
1526 // The boot class loader is searched ahead of the application class loader, failures are
1527 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
1528 // trigger the chaining with a proper stack trace.
1529 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001530 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07001531 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05001532 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001533 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001534 ScopedObjectAccessUnchecked soa(self);
Andreas Gampef865ea92015-04-13 22:14:19 -07001535 mirror::Class* cp_klass;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001536 if (FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader, &cp_klass)) {
Andreas Gampef865ea92015-04-13 22:14:19 -07001537 // The chain was understood. So the value in cp_klass is either the class we were looking
1538 // for, or not found.
1539 if (cp_klass != nullptr) {
1540 return cp_klass;
1541 }
1542 // TODO: We handle the boot classpath loader in FindClassInPathClassLoader. Try to unify this
1543 // and the branch above. TODO: throw the right exception here.
1544
1545 // We'll let the Java-side rediscover all this and throw the exception with the right stack
1546 // trace.
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07001547 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001548
1549 if (Runtime::Current()->IsAotCompiler()) {
1550 // Oops, compile-time, can't run actual class-loader code.
1551 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
1552 self->SetException(pre_allocated);
1553 return nullptr;
1554 }
1555
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001556 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001557 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001558 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07001559 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07001560 {
1561 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001562 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1563 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07001564 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001565 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07001566 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07001567 }
Ian Rogers68b56852014-08-29 20:19:11 -07001568 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001569 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1570 WellKnownClasses::java_lang_ClassLoader_loadClass,
1571 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001572 }
Ian Rogers98379392014-02-24 16:53:16 -08001573 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001574 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07001575 return nullptr;
1576 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08001577 // broken loader - throw NPE to be compatible with Dalvik
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001578 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
1579 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07001580 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08001581 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001582 // success, return mirror::Class*
1583 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001584 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001585 }
Ian Rogers07140832014-09-30 15:43:59 -07001586 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001587}
1588
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001589mirror::Class* ClassLinker::DefineClass(Thread* self,
1590 const char* descriptor,
1591 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001592 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001593 const DexFile& dex_file,
1594 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001595 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001596 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001597
Brian Carlstromaded5f72011-10-07 17:15:04 -07001598 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001599 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001600 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001601 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001602 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001603 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001604 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001605 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001606 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001607 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1608 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001609 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001610 klass.Assign(GetClassRoot(kJavaLangDexCache));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001611 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001612 }
1613
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001614 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001615 // Allocate a class with the status of not ready.
1616 // Interface object should get the right size here. Regular class will
1617 // figure out the right size later and be replaced with one of the right
1618 // size when the class becomes resolved.
1619 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001620 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001621 if (UNLIKELY(klass.Get() == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001622 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07001623 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001624 }
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001625 mirror::DexCache* dex_cache = RegisterDexFile(
1626 dex_file,
1627 GetOrCreateAllocatorForClassLoader(class_loader.Get()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001628 if (dex_cache == nullptr) {
1629 self->AssertPendingOOMException();
1630 return nullptr;
1631 }
1632 klass->SetDexCache(dex_cache);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001633 SetupClass(dex_file, dex_class_def, klass, class_loader.Get());
1634
Jeff Hao848f70a2014-01-15 13:49:50 -08001635 // Mark the string class by setting its access flag.
1636 if (UNLIKELY(!init_done_)) {
1637 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
1638 klass->SetStringClass();
1639 }
1640 }
1641
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001642 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001643 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001644
Mathieu Chartier590fee92013-09-13 13:46:47 -07001645 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001646 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001647 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001648 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1649 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001650 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001651 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001652
Mathieu Chartierc7853442015-03-27 14:35:38 -07001653 // Load the fields and other things after we are inserted in the table. This is so that we don't
1654 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
1655 // other reason is that the field roots are only visited from the class table. So we need to be
1656 // inserted before we allocate / fill in these fields.
1657 LoadClass(self, dex_file, dex_class_def, klass);
1658 if (self->IsExceptionPending()) {
1659 // An exception occured during load, set status to erroneous while holding klass' lock in case
1660 // notification is necessary.
1661 if (!klass->IsErroneous()) {
1662 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
1663 }
1664 return nullptr;
1665 }
1666
Brian Carlstromaded5f72011-10-07 17:15:04 -07001667 // Finish loading (if necessary) by finding parents
1668 CHECK(!klass->IsLoaded());
1669 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1670 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001671 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001672 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001673 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001674 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001675 }
1676 CHECK(klass->IsLoaded());
1677 // Link the class (if necessary)
1678 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001679 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001680 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001681
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07001682 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001683 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001684 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001685 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001686 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001687 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001688 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001689 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07001690 self->AssertNoPendingException();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07001691 CHECK(h_new_class.Get() != nullptr) << descriptor;
1692 CHECK(h_new_class->IsResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001693
Sebastien Hertza8a697f2015-01-15 12:28:47 +01001694 // Instrumentation may have updated entrypoints for all methods of all
1695 // classes. However it could not update methods of this class while we
1696 // were loading it. Now the class is resolved, we can update entrypoints
1697 // as required by instrumentation.
1698 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
1699 // We must be in the kRunnable state to prevent instrumentation from
1700 // suspending all threads to update entrypoints while we are doing it
1701 // for this class.
1702 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07001703 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01001704 }
1705
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001706 /*
1707 * We send CLASS_PREPARE events to the debugger from here. The
1708 * definition of "preparation" is creating the static fields for a
1709 * class and initializing them to the standard default values, but not
1710 * executing any code (that comes later, during "initialization").
1711 *
1712 * We did the static preparation in LinkClass.
1713 *
1714 * The class has been prepared and resolved but possibly not yet verified
1715 * at this point.
1716 */
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07001717 Dbg::PostClassPrepare(h_new_class.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001718
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07001719 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001720}
1721
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001722uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
1723 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07001724 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001725 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07001726 size_t num_8 = 0;
1727 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001728 size_t num_32 = 0;
1729 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001730 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001731 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1732 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001733 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001734 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07001735 switch (c) {
1736 case 'L':
1737 case '[':
1738 num_ref++;
1739 break;
1740 case 'J':
1741 case 'D':
1742 num_64++;
1743 break;
1744 case 'I':
1745 case 'F':
1746 num_32++;
1747 break;
1748 case 'S':
1749 case 'C':
1750 num_16++;
1751 break;
1752 case 'B':
1753 case 'Z':
1754 num_8++;
1755 break;
1756 default:
1757 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08001758 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001759 }
1760 }
1761 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001762 return mirror::Class::ComputeClassSize(false,
1763 0,
1764 num_8,
1765 num_16,
1766 num_32,
1767 num_64,
1768 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001769 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001770}
1771
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001772OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file,
1773 uint16_t class_def_idx,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001774 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001775 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Richard Uhler07b3c232015-03-31 15:57:54 -07001776 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001777 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001778 *found = false;
1779 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001780 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001781 *found = true;
1782 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08001783}
1784
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001785static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file,
1786 uint16_t class_def_idx,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001787 uint32_t method_idx) {
1788 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07001789 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001790 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001791 ClassDataItemIterator it(dex_file, class_data);
1792 // Skip fields
1793 while (it.HasNextStaticField()) {
1794 it.Next();
1795 }
1796 while (it.HasNextInstanceField()) {
1797 it.Next();
1798 }
1799 // Process methods
1800 size_t class_def_method_index = 0;
1801 while (it.HasNextDirectMethod()) {
1802 if (it.GetMemberIndex() == method_idx) {
1803 return class_def_method_index;
1804 }
1805 class_def_method_index++;
1806 it.Next();
1807 }
1808 while (it.HasNextVirtualMethod()) {
1809 if (it.GetMemberIndex() == method_idx) {
1810 return class_def_method_index;
1811 }
1812 class_def_method_index++;
1813 it.Next();
1814 }
1815 DCHECK(!it.HasNext());
1816 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08001817 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001818}
1819
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001820const OatFile::OatMethod ClassLinker::FindOatMethodFor(ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08001821 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001822 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001823 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08001824 size_t oat_method_index;
1825 if (method->IsStatic() || method->IsDirect()) {
1826 // Simple case where the oat method index was stashed at load time.
1827 oat_method_index = method->GetMethodIndex();
1828 } else {
1829 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1830 // by search for its position in the declared virtual methods.
1831 oat_method_index = declaring_class->NumDirectMethods();
1832 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001833 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001834 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07001835 // Check method index instead of identity in case of duplicate method definitions.
1836 if (method->GetDexMethodIndex() ==
Mathieu Chartiere401d142015-04-22 13:56:20 -07001837 declaring_class->GetVirtualMethod(i, image_pointer_size_)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001838 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001839 break;
1840 }
Ian Rogersf320b632012-03-13 18:47:47 -07001841 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001842 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001843 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
1844 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001845 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001846 DCHECK_EQ(oat_method_index,
1847 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001848 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001849 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07001850 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
1851 declaring_class->GetDexClassDefIndex(),
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001852 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001853 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001854 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001855 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001856 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07001857}
1858
1859// Special case to get oat code without overwriting a trampoline.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001860const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001861 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07001862 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001863 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07001864 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001865 bool found;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001866 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001867 if (found) {
1868 auto* code = oat_method.GetQuickCode();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001869 if (code != nullptr) {
1870 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08001871 }
1872 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001873 if (method->IsNative()) {
1874 // No code and native? Use generic trampoline.
1875 return GetQuickGenericJniStub();
1876 }
1877 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07001878}
1879
Mathieu Chartiere401d142015-04-22 13:56:20 -07001880const void* ClassLinker::GetOatMethodQuickCodeFor(ArtMethod* method) {
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001881 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
1882 return nullptr;
1883 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001884 bool found;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001885 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001886 if (found) {
1887 return oat_method.GetQuickCode();
1888 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001889 return nullptr;
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001890}
1891
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001892const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file,
1893 uint16_t class_def_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08001894 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001895 bool found;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001896 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
Ian Rogers97b52f82014-08-14 11:34:07 -07001897 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001898 return nullptr;
1899 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001900 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001901 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001902}
1903
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001904// Returns true if the method must run with interpreter, false otherwise.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001905static bool NeedsInterpreter(ArtMethod* method, const void* quick_code)
Mathieu Chartier90443472015-07-16 20:32:27 -07001906 SHARED_REQUIRES(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08001907 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001908 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08001909 // May return true for native code, in the case of generic JNI
1910 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001911 return true;
1912 }
1913 // If interpreter mode is enabled, every method (except native and proxy) must
1914 // be run with interpreter.
1915 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
1916 !method->IsNative() && !method->IsProxyMethod();
1917}
1918
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001919void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08001920 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07001921 if (klass->NumDirectMethods() == 0) {
1922 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08001923 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001924 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001925 if (!runtime->IsStarted()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001926 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001927 return; // OAT file unavailable.
1928 }
Ian Rogers19846512012-02-24 11:42:47 -08001929 }
Alex Light64ad14d2014-08-19 14:23:13 -07001930
Mathieu Chartierf8322842014-05-16 10:59:25 -07001931 const DexFile& dex_file = klass->GetDexFile();
1932 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07001933 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07001934 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07001935 // There should always be class data if there were direct methods.
1936 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08001937 ClassDataItemIterator it(dex_file, class_data);
1938 // Skip fields
1939 while (it.HasNextStaticField()) {
1940 it.Next();
1941 }
1942 while (it.HasNextInstanceField()) {
1943 it.Next();
1944 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001945 bool has_oat_class;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001946 OatFile::OatClass oat_class = FindOatClass(dex_file,
1947 klass->GetDexClassDefIndex(),
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001948 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07001949 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001950 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001951 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001952 if (!method->IsStatic()) {
1953 // Only update static methods.
1954 continue;
Ian Rogers19846512012-02-24 11:42:47 -08001955 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001956 const void* quick_code = nullptr;
1957 if (has_oat_class) {
1958 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001959 quick_code = oat_method.GetQuickCode();
1960 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001961 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001962 if (enter_interpreter) {
1963 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07001964 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001965 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001966 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08001967 } else {
1968 quick_code = GetQuickToInterpreterBridge();
1969 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001970 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001971 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08001972 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001973 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08001974}
1975
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001976void ClassLinker::LinkCode(ArtMethod* method, const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001977 uint32_t class_def_method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001978 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001979 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001980 // The following code only applies to a non-compiler runtime.
1981 return;
1982 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001983 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001984 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001985 if (oat_class != nullptr) {
1986 // Every kind of method should at least get an invoke stub from the oat_method.
1987 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001988 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001989 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001990 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001991
Jeff Hao16743632013-05-08 10:59:04 -07001992 // Install entry point from interpreter.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001993 bool enter_interpreter = NeedsInterpreter(method, method->GetEntryPointFromQuickCompiledCode());
Jeff Hao16743632013-05-08 10:59:04 -07001994
Brian Carlstrom92827a52011-10-10 15:50:01 -07001995 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001996 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001997 return;
1998 }
Ian Rogers19846512012-02-24 11:42:47 -08001999
2000 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002001 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002002 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2003 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002004 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002005 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002006 if (!method->IsNative()) {
2007 // Set entry point from compiled code if there's no code or in interpreter only mode.
2008 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002009 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002010 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002011 }
Ian Rogers0d6de042012-02-29 08:50:26 -08002012 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002013
Ian Rogers62d6c772013-02-27 08:32:07 -08002014 if (method->IsNative()) {
2015 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002016 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002017
2018 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002019 // We have a native method here without code. Then it should have either the generic JNI
2020 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2021 // TODO: this doesn't handle all the cases where trampolines may be installed.
2022 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2023 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002024 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002025 }
2026}
2027
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002028void ClassLinker::SetupClass(const DexFile& dex_file,
2029 const DexFile::ClassDef& dex_class_def,
2030 Handle<mirror::Class> klass,
2031 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002032 CHECK(klass.Get() != nullptr);
2033 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002034 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002035 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002036 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002037
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002038 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07002039 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002040 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002041 klass->SetAccessFlags(access_flags);
2042 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002043 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002044 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002045
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002046 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002047 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002048 CHECK(klass->GetDexCacheStrings() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002049}
Brian Carlstrom934486c2011-07-12 23:42:50 -07002050
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002051void ClassLinker::LoadClass(Thread* self,
2052 const DexFile& dex_file,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002053 const DexFile::ClassDef& dex_class_def,
2054 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07002055 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002056 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002057 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002058 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002059 bool has_oat_class = false;
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002060 if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002061 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002062 &has_oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002063 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002064 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002065 }
2066 }
2067 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002068 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002069 }
2070}
2071
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002072LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
2073 LinearAlloc* allocator,
2074 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002075 if (length == 0) {
2076 return nullptr;
2077 }
Vladimir Markocf36d492015-08-12 19:27:26 +01002078 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
2079 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
2080 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002081 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01002082 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002083 CHECK(ret != nullptr);
2084 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
2085 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002086}
2087
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002088LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
2089 LinearAlloc* allocator,
2090 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002091 if (length == 0) {
2092 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002093 }
Vladimir Marko14632852015-08-17 12:07:23 +01002094 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
2095 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01002096 const size_t storage_size =
2097 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002098 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01002099 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002100 CHECK(ret != nullptr);
2101 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01002102 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002103 }
2104 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002105}
2106
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002107LinearAlloc* ClassLinker::GetAllocatorForClassLoader(mirror::ClassLoader* class_loader) {
2108 if (class_loader == nullptr) {
2109 return Runtime::Current()->GetLinearAlloc();
2110 }
2111 LinearAlloc* allocator = class_loader->GetAllocator();
2112 DCHECK(allocator != nullptr);
2113 return allocator;
2114}
2115
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002116LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(mirror::ClassLoader* class_loader) {
2117 if (class_loader == nullptr) {
2118 return Runtime::Current()->GetLinearAlloc();
2119 }
2120 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2121 LinearAlloc* allocator = class_loader->GetAllocator();
2122 if (allocator == nullptr) {
2123 allocator = Runtime::Current()->CreateLinearAlloc();
2124 class_loader->SetAllocator(allocator);
2125 }
2126 return allocator;
2127}
2128
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002129void ClassLinker::LoadClassMembers(Thread* self,
2130 const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002131 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002132 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002133 const OatFile::OatClass* oat_class) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002134 {
2135 // Note: We cannot have thread suspension until the field and method arrays are setup or else
2136 // Class::VisitFieldRoots may miss some fields or methods.
2137 ScopedAssertNoThreadSuspension nts(self, __FUNCTION__);
2138 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01002139 // We allow duplicate definitions of the same field in a class_data_item
2140 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002141 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002142 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002143 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
2144 allocator,
2145 it.NumStaticFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01002146 size_t num_sfields = 0;
2147 uint32_t last_field_idx = 0u;
2148 for (; it.HasNextStaticField(); it.Next()) {
2149 uint32_t field_idx = it.GetMemberIndex();
2150 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
2151 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
2152 DCHECK_LT(num_sfields, it.NumStaticFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002153 LoadField(it, klass, &sfields->At(num_sfields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01002154 ++num_sfields;
2155 last_field_idx = field_idx;
2156 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002157 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002158 klass->SetSFieldsPtr(sfields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002159 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
2160 // Load instance fields.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002161 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
2162 allocator,
2163 it.NumInstanceFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01002164 size_t num_ifields = 0u;
2165 last_field_idx = 0u;
2166 for (; it.HasNextInstanceField(); it.Next()) {
2167 uint32_t field_idx = it.GetMemberIndex();
2168 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
2169 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
2170 DCHECK_LT(num_ifields, it.NumInstanceFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002171 LoadField(it, klass, &ifields->At(num_ifields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01002172 ++num_ifields;
2173 last_field_idx = field_idx;
2174 }
2175 }
2176 if (UNLIKELY(num_sfields != it.NumStaticFields()) ||
2177 UNLIKELY(num_ifields != it.NumInstanceFields())) {
2178 LOG(WARNING) << "Duplicate fields in class " << PrettyDescriptor(klass.Get())
2179 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields()
2180 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
2181 // NOTE: Not shrinking the over-allocated sfields/ifields.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002182 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002183 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002184 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
2185 // Load methods.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002186 klass->SetDirectMethodsPtr(AllocArtMethodArray(self, allocator, it.NumDirectMethods()));
2187 klass->SetVirtualMethodsPtr(AllocArtMethodArray(self, allocator, it.NumVirtualMethods()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002188 size_t class_def_method_index = 0;
2189 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2190 size_t last_class_def_method_index = 0;
2191 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
2192 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
2193 LoadMethod(self, dex_file, it, klass, method);
2194 LinkCode(method, oat_class, class_def_method_index);
2195 uint32_t it_method_index = it.GetMemberIndex();
2196 if (last_dex_method_index == it_method_index) {
2197 // duplicate case
2198 method->SetMethodIndex(last_class_def_method_index);
2199 } else {
2200 method->SetMethodIndex(class_def_method_index);
2201 last_dex_method_index = it_method_index;
2202 last_class_def_method_index = class_def_method_index;
2203 }
2204 class_def_method_index++;
2205 }
2206 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
2207 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
2208 LoadMethod(self, dex_file, it, klass, method);
2209 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
2210 LinkCode(method, oat_class, class_def_method_index);
2211 class_def_method_index++;
2212 }
2213 DCHECK(!it.HasNext());
Ian Rogers0571d352011-11-03 19:51:38 -07002214 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07002215 // Ensure that the card is marked so that remembered sets pick up native roots.
2216 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07002217 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07002218}
2219
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002220void ClassLinker::LoadField(const ClassDataItemIterator& it,
2221 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002222 ArtField* dst) {
2223 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002224 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002225 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002226 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002227}
2228
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002229void ClassLinker::LoadMethod(Thread* self,
2230 const DexFile& dex_file,
2231 const ClassDataItemIterator& it,
2232 Handle<mirror::Class> klass,
2233 ArtMethod* dst) {
Ian Rogers19846512012-02-24 11:42:47 -08002234 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002235 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002236 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002237
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002238 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002239 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002240 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002241 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002242
Vladimir Marko05792b92015-08-03 11:56:49 +01002243 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods(), image_pointer_size_);
2244 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes(), image_pointer_size_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002245
Andreas Gampe51829322014-08-25 15:05:04 -07002246 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002247
Ian Rogersdfb325e2013-10-30 01:00:44 -07002248 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002249 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002250 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2251 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002252 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002253 klass->SetFinalizable();
2254 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002255 std::string temp;
2256 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002257 // The Enum class declares a "final" finalize() method to prevent subclasses from
2258 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2259 // subclasses, so we exclude it here.
2260 // We also want to avoid setting the flag on Object, where we know that finalize() is
2261 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002262 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2263 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002264 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002265 }
2266 }
2267 }
2268 } else if (method_name[0] == '<') {
2269 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002270 bool is_init = (strcmp("<init>", method_name) == 0);
2271 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002272 if (UNLIKELY(!is_init && !is_clinit)) {
2273 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2274 } else {
2275 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2276 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002277 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002278 access_flags |= kAccConstructor;
2279 }
2280 }
2281 }
2282 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002283}
2284
Ian Rogers7b078e82014-09-10 14:44:24 -07002285void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002286 StackHandleScope<1> hs(self);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002287 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(
2288 self,
2289 dex_file,
2290 Runtime::Current()->GetLinearAlloc())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002291 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2292 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002293 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002294}
2295
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002296void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002297 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002298 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002299 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002300 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002301}
2302
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002303void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002304 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002305 Thread* const self = Thread::Current();
2306 dex_lock_.AssertExclusiveHeld(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002307 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002308 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2309 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002310 // Clean up pass to remove null dex caches.
2311 // Null dex caches can occur due to class unloading and we are lazily removing null entries.
2312 JavaVMExt* const vm = self->GetJniEnv()->vm;
2313 for (auto it = dex_caches_.begin(); it != dex_caches_.end();) {
2314 mirror::Object* dex_cache_root = self->DecodeJObject(*it);
2315 if (dex_cache_root == nullptr) {
2316 vm->DeleteWeakGlobalRef(self, *it);
2317 it = dex_caches_.erase(it);
2318 } else {
2319 ++it;
2320 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07002321 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002322 dex_caches_.push_back(vm->AddWeakGlobalRef(self, dex_cache.Get()));
2323 dex_cache->SetDexFile(&dex_file);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002324}
2325
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002326mirror::DexCache* ClassLinker::RegisterDexFile(const DexFile& dex_file, LinearAlloc* linear_alloc) {
Ian Rogers1f539342012-10-03 21:09:42 -07002327 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002328 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002329 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002330 mirror::DexCache* dex_cache = FindDexCacheLocked(self, dex_file, true);
2331 if (dex_cache != nullptr) {
2332 return dex_cache;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002333 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002334 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002335 // Don't alloc while holding the lock, since allocation may need to
2336 // suspend all threads and another thread may need the dex_lock_ to
2337 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002338 StackHandleScope<1> hs(self);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002339 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file, linear_alloc)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002340 WriterMutexLock mu(self, dex_lock_);
2341 mirror::DexCache* dex_cache = FindDexCacheLocked(self, dex_file, true);
2342 if (dex_cache != nullptr) {
2343 return dex_cache;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002344 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002345 if (h_dex_cache.Get() == nullptr) {
2346 self->AssertPendingOOMException();
2347 return nullptr;
2348 }
2349 RegisterDexFileLocked(dex_file, h_dex_cache);
2350 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002351}
2352
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002353void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002354 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002355 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002356 RegisterDexFileLocked(dex_file, dex_cache);
2357}
2358
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002359mirror::DexCache* ClassLinker::FindDexCache(Thread* self,
2360 const DexFile& dex_file,
2361 bool allow_failure) {
2362 ReaderMutexLock mu(self, dex_lock_);
2363 return FindDexCacheLocked(self, dex_file, allow_failure);
2364}
2365
2366mirror::DexCache* ClassLinker::FindDexCacheLocked(Thread* self,
2367 const DexFile& dex_file,
2368 bool allow_failure) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002369 // Search assuming unique-ness of dex file.
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002370 for (jweak weak_root : dex_caches_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07002371 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
Mathieu Chartierca330892015-09-01 20:00:10 -07002372 if (dex_cache != nullptr && dex_cache->GetDexFile() == &dex_file) {
2373 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002374 }
2375 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002376 if (allow_failure) {
2377 return nullptr;
2378 }
Mathieu Chartierac8f4392015-08-27 13:54:20 -07002379 std::string location(dex_file.GetLocation());
Brian Carlstrom81a90872015-08-28 09:07:14 -07002380 // Failure, dump diagnostic and abort.
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002381 for (jobject weak_root : dex_caches_) {
2382 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
2383 if (dex_cache != nullptr) {
2384 LOG(ERROR) << "Registered dex file " << dex_cache->GetDexFile()->GetLocation();
2385 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07002386 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002387 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002388 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002389}
2390
Mathieu Chartiere401d142015-04-22 13:56:20 -07002391void ClassLinker::FixupDexCaches(ArtMethod* resolution_method) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002392 Thread* const self = Thread::Current();
2393 ReaderMutexLock mu(self, dex_lock_);
2394 for (jobject weak_root : dex_caches_) {
2395 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
2396 if (dex_cache != nullptr) {
2397 dex_cache->Fixup(resolution_method, image_pointer_size_);
2398 }
Ian Rogers19846512012-02-24 11:42:47 -08002399 }
2400}
2401
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002402mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002403 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002404 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002405 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002406 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002407 }
2408 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002409}
2410
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002411mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2412 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002413 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07002414 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002415 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002416 StackHandleScope<1> hs(self);
2417 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002418 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002419 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
2420 h_class->SetPrimitiveType(type);
2421 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002422 const char* descriptor = Primitive::Descriptor(type);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002423 mirror::Class* existing = InsertClass(descriptor, h_class.Get(),
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002424 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002425 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002426 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07002427}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002428
Brian Carlstrombe977852011-07-19 14:54:54 -07002429// Create an array class (i.e. the class object for the array, not the
2430// array itself). "descriptor" looks like "[C" or "[[[[B" or
2431// "[Ljava/lang/String;".
2432//
2433// If "descriptor" refers to an array of primitives, look up the
2434// primitive type's internally-generated class object.
2435//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002436// "class_loader" is the class loader of the class that's referring to
2437// us. It's used to ensure that we're looking for the element type in
2438// the right context. It does NOT become the class loader for the
2439// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002440//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002441// Returns null with an exception raised on failure.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002442mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002443 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002444 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002445 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002446 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002447 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
2448 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002449 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002450 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002451 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002452 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
2453 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002454 if (component_type.Get() == nullptr) {
2455 DCHECK(self->IsExceptionPending());
2456 return nullptr;
2457 } else {
2458 self->ClearException();
2459 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002460 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002461 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2462 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2463 return nullptr;
2464 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002465 // See if the component type is already loaded. Array classes are
2466 // always associated with the class loader of their underlying
2467 // element type -- an array of Strings goes with the loader for
2468 // java/lang/String -- so we need to look for it there. (The
2469 // caller should have checked for the existence of the class
2470 // before calling here, but they did so with *their* class loader,
2471 // not the component type's loader.)
2472 //
2473 // If we find it, the caller adds "loader" to the class' initiating
2474 // loader list, which should prevent us from going through this again.
2475 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002476 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002477 // are the same, because our caller (FindClass) just did the
2478 // lookup. (Even if we get this wrong we still have correct behavior,
2479 // because we effectively do this lookup again when we add the new
2480 // class to the hash table --- necessary because of possible races with
2481 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002482 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002483 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002484 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002485 return new_class;
2486 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002487 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002488
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002489 // Fill out the fields in the Class.
2490 //
2491 // It is possible to execute some methods against arrays, because
2492 // all arrays are subclasses of java_lang_Object_, so we need to set
2493 // up a vtable. We can just point at the one in java_lang_Object_.
2494 //
2495 // Array classes are simple enough that we don't need to do a full
2496 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002497 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002498 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002499 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002500 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002501 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002502 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002503 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002504 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002505 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002506 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002507 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002508 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002509 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002510 } else if (strcmp(descriptor, "[J") == 0) {
2511 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002512 }
2513 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002514 if (new_class.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002515 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002516 if (new_class.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002517 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002518 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002519 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002520 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002521 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002522 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002523 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002524 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002525 new_class->SetSuperClass(java_lang_Object);
2526 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002527 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002528 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07002529 if (component_type->IsPrimitive()) {
2530 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
2531 } else {
2532 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
2533 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002534 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002535 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002536 ArtMethod* imt[mirror::Class::kImtSize];
2537 std::fill_n(imt, arraysize(imt), Runtime::Current()->GetImtUnimplementedMethod());
2538 new_class->PopulateEmbeddedImtAndVTable(imt, image_pointer_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002539 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002540 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002541 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002542 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002543
2544
2545 // All arrays have java/lang/Cloneable and java/io/Serializable as
2546 // interfaces. We need to set that up here, so that stuff like
2547 // "instanceof" works right.
2548 //
2549 // Note: The GC could run during the call to FindSystemClass,
2550 // so we need to make sure the class object is GC-valid while we're in
2551 // there. Do this by clearing the interface list so the GC will just
2552 // think that the entries are null.
2553
2554
2555 // Use the single, global copies of "interfaces" and "iftable"
2556 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002557 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002558 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002559 CHECK(array_iftable != nullptr);
2560 new_class->SetIfTable(array_iftable);
2561 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002562
Elliott Hughes00626c22013-06-14 15:04:14 -07002563 // Inherit access flags from the component type.
2564 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2565 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2566 access_flags &= kAccJavaFlagsMask;
2567 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002568 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002569 access_flags |= kAccAbstract | kAccFinal;
2570 access_flags &= ~kAccInterface;
2571
2572 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002573
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002574 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002575 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002576 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002577 }
2578 // Another thread must have loaded the class after we
2579 // started but before we finished. Abandon what we've
2580 // done.
2581 //
2582 // (Yes, this happens.)
2583
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002584 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002585}
2586
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002587mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002588 switch (type) {
2589 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002590 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002591 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002592 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002593 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002594 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002595 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002596 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002597 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002598 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002599 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002600 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002601 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002602 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002603 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002604 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002605 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002606 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002607 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002608 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002609 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002610 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002611 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002612 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002613}
2614
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002615mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass, size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002616 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002617 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002618 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002619 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08002620 source += " from ";
2621 source += dex_cache->GetLocation()->ToModifiedUtf8();
2622 }
2623 LOG(INFO) << "Loaded class " << descriptor << source;
2624 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002625 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002626 mirror::ClassLoader* const class_loader = klass->GetClassLoader();
2627 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
2628 mirror::Class* existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002629 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002630 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002631 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002632 if (kIsDebugBuild && !klass->IsTemp() && class_loader == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002633 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002634 // Check a class loaded with the system class loader matches one in the image if the class
2635 // is in the image.
2636 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002637 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002638 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002639 }
2640 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002641 VerifyObject(klass);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002642 class_table->InsertWithHash(klass, hash);
Mathieu Chartiere4275c02015-08-06 15:34:15 -07002643 if (class_loader != nullptr) {
2644 // This is necessary because we need to have the card dirtied for remembered sets.
2645 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
2646 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08002647 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002648 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002649 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002650 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002651}
2652
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002653void ClassLinker::UpdateClassVirtualMethods(mirror::Class* klass,
2654 LengthPrefixedArray<ArtMethod>* new_methods) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002655 klass->SetVirtualMethodsPtr(new_methods);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002656 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07002657 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002658}
2659
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002660bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002661 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002662 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
2663 return class_table != nullptr && class_table->Remove(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08002664}
2665
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002666mirror::Class* ClassLinker::LookupClass(Thread* self,
2667 const char* descriptor,
2668 size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002669 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002670 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002671 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002672 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
2673 if (class_table != nullptr) {
2674 mirror::Class* result = class_table->Lookup(descriptor, hash);
2675 if (result != nullptr) {
2676 return result;
2677 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002678 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07002679 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002680 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
2681 return nullptr;
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002682 }
2683 // Lookup failed but need to search dex_caches_.
2684 mirror::Class* result = LookupClassFromImage(descriptor);
2685 if (result != nullptr) {
2686 result = InsertClass(descriptor, result, hash);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002687 } else {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002688 // Searching the image dex files/caches failed, we don't want to get into this situation
2689 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2690 // classes into the class table.
2691 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
2692 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2693 MoveImageClassesToClassTable();
Ian Rogers5d76c432011-10-31 21:42:49 -07002694 }
2695 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002696 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002697}
2698
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002699static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
Mathieu Chartier90443472015-07-16 20:32:27 -07002700 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002701 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002702 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002703 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2704 return root->AsObjectArray<mirror::DexCache>();
2705}
2706
2707void ClassLinker::MoveImageClassesToClassTable() {
2708 Thread* self = Thread::Current();
2709 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2710 if (!dex_cache_image_class_lookup_required_) {
2711 return; // All dex cache classes are already in the class table.
2712 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002713 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002714 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002715 std::string temp;
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002716 ClassTable* const class_table = InsertClassTableForClassLoader(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002717 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2718 mirror::DexCache* dex_cache = dex_caches->Get(i);
Vladimir Marko05792b92015-08-03 11:56:49 +01002719 GcRoot<mirror::Class>* types = dex_cache->GetResolvedTypes();
2720 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
2721 mirror::Class* klass = types[j].Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002722 if (klass != nullptr) {
2723 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002724 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002725 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002726 mirror::Class* existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002727 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002728 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002729 << PrettyClassAndClassLoader(klass);
2730 } else {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002731 class_table->Insert(klass);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002732 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002733 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002734 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002735 }
2736 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002737 }
2738 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002739 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002740}
2741
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002742class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
2743 public:
2744 explicit MoveClassTableToPreZygoteVisitor() {}
2745
2746 void Visit(mirror::ClassLoader* class_loader)
2747 REQUIRES(Locks::classlinker_classes_lock_)
2748 SHARED_REQUIRES(Locks::mutator_lock_) OVERRIDE {
2749 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07002750 if (class_table != nullptr) {
2751 class_table->FreezeSnapshot();
2752 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002753 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002754};
2755
2756void ClassLinker::MoveClassTableToPreZygote() {
2757 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2758 boot_class_table_.FreezeSnapshot();
2759 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002760 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002761}
2762
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002763mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002764 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002765 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2766 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
2767 mirror::DexCache* dex_cache = dex_caches->Get(i);
2768 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartier9507fa22015-10-29 15:08:57 -07002769 // Try binary searching the type index by descriptor.
2770 const DexFile::TypeId* type_id = dex_file->FindTypeId(descriptor);
2771 if (type_id != nullptr) {
2772 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
2773 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
2774 if (klass != nullptr) {
2775 return klass;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002776 }
2777 }
2778 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002779 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002780}
2781
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002782// Look up classes by hash and descriptor and put all matching ones in the result array.
2783class LookupClassesVisitor : public ClassLoaderVisitor {
2784 public:
2785 LookupClassesVisitor(const char* descriptor, size_t hash, std::vector<mirror::Class*>* result)
2786 : descriptor_(descriptor),
2787 hash_(hash),
2788 result_(result) {}
2789
2790 void Visit(mirror::ClassLoader* class_loader)
2791 SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
2792 ClassTable* const class_table = class_loader->GetClassTable();
2793 mirror::Class* klass = class_table->Lookup(descriptor_, hash_);
2794 if (klass != nullptr) {
2795 result_->push_back(klass);
2796 }
2797 }
2798
2799 private:
2800 const char* const descriptor_;
2801 const size_t hash_;
2802 std::vector<mirror::Class*>* const result_;
2803};
2804
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002805void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002806 result.clear();
2807 if (dex_cache_image_class_lookup_required_) {
2808 MoveImageClassesToClassTable();
2809 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002810 Thread* const self = Thread::Current();
2811 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002812 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
2813 mirror::Class* klass = boot_class_table_.Lookup(descriptor, hash);
2814 if (klass != nullptr) {
2815 result.push_back(klass);
2816 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002817 LookupClassesVisitor visitor(descriptor, hash, &result);
2818 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002819}
2820
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002821void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002822 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002823 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08002824
Ian Rogers9ffb0392012-09-10 11:56:50 -07002825 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002826 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07002827 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07002828 return;
2829 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002830 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002831 return;
2832 }
jeffhao98eacac2011-09-14 16:11:53 -07002833
Ian Rogers9ffb0392012-09-10 11:56:50 -07002834 // The class might already be erroneous, for example at compile time if we attempted to verify
2835 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002836 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002837 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002838 return;
2839 }
2840
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002841 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002842 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002843 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002844 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002845 << PrettyClass(klass.Get());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002846 CHECK(!Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002847 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002848 }
jeffhao98eacac2011-09-14 16:11:53 -07002849
Igor Murashkin7617abd2015-07-10 18:27:47 -07002850 // Skip verification if we are forcing a soft fail.
2851 // This has to be before the normal verification enabled check,
2852 // since technically verification is disabled in this mode.
2853 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
2854 // Force verification to be a 'soft failure'.
2855 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
2856 // As this is a fake verified status, make sure the methods are _not_ marked preverified
2857 // later.
2858 klass->SetPreverified();
2859 return;
2860 }
2861
Jeff Hao4a200f52014-04-01 14:58:49 -07002862 // Skip verification if disabled.
2863 if (!Runtime::Current()->IsVerificationEnabled()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002864 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07002865 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07002866 return;
2867 }
2868
Ian Rogers9ffb0392012-09-10 11:56:50 -07002869 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002870 StackHandleScope<2> hs(self);
2871 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002872 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07002873 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002874 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002875
2876 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002877 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002878 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002879 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07002880 std::string error_msg(
2881 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
2882 PrettyDescriptor(klass.Get()).c_str(),
2883 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08002884 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002885 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002886 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002887 self->ClearException();
2888 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002889 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
2890 if (cause.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002891 self->GetException()->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002892 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08002893 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002894 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00002895 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
2896 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002897 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002898 return;
2899 }
2900 }
2901
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002902 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07002903 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002904 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002905 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002906 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002907 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002908 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002909 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002910 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
2911 PrettyDescriptor(klass.Get()).c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002912 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07002913 return;
2914 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002915 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08002916 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07002917 if (!preverified) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002918 verifier_failure = verifier::MethodVerifier::VerifyClass(self,
2919 klass.Get(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002920 Runtime::Current()->IsAotCompiler(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002921 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002922 }
2923 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07002924 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002925 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07002926 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2927 << " because: " << error_msg;
2928 }
Ian Rogers1f539342012-10-03 21:09:42 -07002929 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002930 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002931 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002932 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002933 // Even though there were no verifier failures we need to respect whether the super-class
2934 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002935 if (super.Get() == nullptr || super->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002936 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002937 } else {
2938 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002939 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002940 // Pretend a soft failure occured so that we don't consider the class verified below.
2941 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002942 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002943 } else {
2944 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
2945 // Soft failures at compile time should be retried at runtime. Soft
2946 // failures at runtime will be handled by slow paths in the generated
2947 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002948 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002949 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002950 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002951 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002952 // As this is a fake verified status, make sure the methods are _not_ marked preverified
2953 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07002954 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002955 }
2956 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07002957 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002958 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08002959 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2960 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002961 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002962 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002963 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002964 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002965 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002966 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002967 // Let the interpreter know it by setting the kAccPreverified flag onto each
2968 // method.
2969 // Note: we're going here during compilation and at runtime. When we set the
2970 // kAccPreverified flag when compiling image classes, the flag is recorded
2971 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07002972 EnsurePreverifiedMethods(klass);
2973 }
2974}
2975
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002976void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002977 if (!klass->IsPreverified()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002978 klass->SetPreverifiedFlagOnAllMethods(image_pointer_size_);
Ian Rogers7b078e82014-09-10 14:44:24 -07002979 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002980 }
jeffhao98eacac2011-09-14 16:11:53 -07002981}
2982
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002983bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
2984 mirror::Class* klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002985 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002986 // If we're compiling, we can only verify the class using the oat file if
2987 // we are not compiling the image or if the class we're verifying is not part of
2988 // the app. In other words, we will only check for preverification of bootclasspath
2989 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002990 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002991 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002992 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002993 return false;
2994 }
2995 // We are compiling an app (not the image).
2996
2997 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002998 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002999 return false;
3000 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003001 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003002
Richard Uhler07b3c232015-03-31 15:57:54 -07003003 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003004 // In case we run without an image there won't be a backing oat file.
3005 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003006 return false;
3007 }
3008
Andreas Gampe76bd8802014-12-10 16:43:58 -08003009 // We may be running with a preopted oat file but without image. In this case,
3010 // we don't skip verification of preverified classes to ensure we initialize
3011 // dex caches with all types resolved during verification.
3012 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
3013 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
3014 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
3015 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003016 if (!Runtime::Current()->IsAotCompiler() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08003017 !Runtime::Current()->GetHeap()->HasImageSpace() &&
3018 klass->GetClassLoader() != nullptr) {
3019 return false;
3020 }
3021
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003022 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003023 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003024 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3025 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003026 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003027 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003028 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003029 // Compile time verification failed with a soft error. Compile time verification can fail
3030 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003031 // class ... {
3032 // Foo x;
3033 // .... () {
3034 // if (...) {
3035 // v1 gets assigned a type of resolved class Foo
3036 // } else {
3037 // v1 gets assigned a type of unresolved class Bar
3038 // }
3039 // iput x = v1
3040 // } }
3041 // when we merge v1 following the if-the-else it results in Conflict
3042 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3043 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3044 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3045 // at compile time).
3046 return false;
3047 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003048 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003049 // Compile time verification failed with a hard error. This is caused by invalid instructions
3050 // in the class. These errors are unrecoverable.
3051 return false;
3052 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003053 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003054 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3055 // not loading the class.
3056 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3057 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003058 return false;
3059 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003060 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003061 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003062 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003063 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003064 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003065}
3066
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003067void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003068 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003069 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003070 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i, image_pointer_size_));
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003071 }
3072 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003073 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i, image_pointer_size_));
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003074 }
3075}
3076
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003077void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003078 ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003079 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3080 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003081 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003082 return; // native or abstract method
3083 }
3084 if (code_item->tries_size_ == 0) {
3085 return; // nothing to process
3086 }
Ian Rogers13735952014-10-08 12:43:28 -07003087 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003088 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003089 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3090 CatchHandlerIterator iterator(handlers_ptr);
3091 for (; iterator.HasNext(); iterator.Next()) {
3092 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3093 // unresolved exception types will be ignored by exception delivery
3094 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Mathieu Chartier90443472015-07-16 20:32:27 -07003095 mirror::Class* exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003096 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003097 DCHECK(Thread::Current()->IsExceptionPending());
3098 Thread::Current()->ClearException();
3099 }
3100 }
3101 }
3102 handlers_ptr = iterator.EndDataPointer();
3103 }
3104}
3105
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003106mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
3107 jstring name,
3108 jobjectArray interfaces,
3109 jobject loader,
3110 jobjectArray methods,
3111 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003112 Thread* self = soa.Self();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003113 StackHandleScope<10> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003114 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003115 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003116 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003117 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003118 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003119 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003120 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003121 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003122 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3123 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003124 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003125 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003126 klass->SetName(soa.Decode<mirror::String*>(name));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003127 klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003128 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003129 std::string descriptor(GetDescriptorForProxy(klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003130 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003131
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003132 // Needs to be before we insert the class so that the allocator field is set.
3133 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(klass->GetClassLoader());
3134
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003135 // Insert the class before loading the fields as the field roots
3136 // (ArtField::declaring_class_) are only visited from the class
3137 // table. There can't be any suspend points between inserting the
3138 // class and setting the field arrays below.
3139 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), hash);
3140 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003141
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003142 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07003143 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003144 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003145 klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003146
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003147 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3148 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003149 ArtField& interfaces_sfield = sfields->At(0);
3150 interfaces_sfield.SetDexFieldIndex(0);
3151 interfaces_sfield.SetDeclaringClass(klass.Get());
3152 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003153
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003154 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003155 ArtField& throws_sfield = sfields->At(1);
3156 throws_sfield.SetDexFieldIndex(1);
3157 throws_sfield.SetDeclaringClass(klass.Get());
3158 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003159
Ian Rogers466bb252011-10-14 03:29:56 -07003160 // Proxies have 1 direct method, the constructor
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003161 LengthPrefixedArray<ArtMethod>* directs = AllocArtMethodArray(self, allocator, 1);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003162 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
3163 // want to throw OOM in the future.
3164 if (UNLIKELY(directs == nullptr)) {
3165 self->AssertPendingOOMException();
3166 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003167 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003168 klass->SetDirectMethodsPtr(directs);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003169 CreateProxyConstructor(klass, klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04003170
Mathieu Chartier590fee92013-09-13 13:46:47 -07003171 // Create virtual method using specified prototypes.
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003172 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>*>(methods));
3173 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003174 << PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003175 const size_t num_virtual_methods = h_methods->GetLength();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003176 auto* virtuals = AllocArtMethodArray(self, allocator, num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003177 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
3178 // want to throw OOM in the future.
3179 if (UNLIKELY(virtuals == nullptr)) {
3180 self->AssertPendingOOMException();
3181 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003182 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003183 klass->SetVirtualMethodsPtr(virtuals);
Jesse Wilson95caa792011-10-12 18:14:17 -04003184 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003185 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
3186 auto* prototype = h_methods->Get(i)->GetArtMethod();
3187 CreateProxyMethod(klass, prototype, virtual_method);
3188 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
3189 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04003190 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003191
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003192 // The super class is java.lang.reflect.Proxy
3193 klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy));
3194 // Now effectively in the loaded state.
3195 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08003196 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003197
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003198 MutableHandle<mirror::Class> new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07003199 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003200 // Must hold lock on object when resolved.
3201 ObjectLock<mirror::Class> resolution_lock(self, klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003202 // Link the fields and virtual methods, creating vtable and iftables.
3203 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003204 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003205 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003206 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003207 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003208 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003209 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003210 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003211 CHECK(klass->IsRetired());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003212 CHECK_NE(klass.Get(), new_class.Get());
3213 klass.Assign(new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003214
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003215 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
3216 interfaces_sfield.SetObject<false>(klass.Get(),
3217 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
3218 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
3219 throws_sfield.SetObject<false>(
3220 klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003221
3222 {
3223 // Lock on klass is released. Lock new class object.
3224 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003225 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003226 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003227
3228 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003229 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003230 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003231 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
3232
Ian Rogersc2b44472011-12-14 21:17:17 -08003233 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003234 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
3235 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003236 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003237 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003238
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003239 StackHandleScope<1> hs2(self);
3240 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String*>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003241 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003242 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003243 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3244
3245 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003246 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003247 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003248
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003249 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003250 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003251 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003252 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003253 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003254 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003255}
3256
Ian Rogersef7d42f2014-01-06 12:55:46 -08003257std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003258 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003259 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003260 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003261 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3262}
3263
Mathieu Chartier4e2cb092015-07-22 16:17:51 -07003264ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class, ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003265 DCHECK(proxy_class->IsProxyClass());
3266 DCHECK(proxy_method->IsProxyMethod());
Ian Rogers16f93672012-02-14 12:29:06 -08003267 {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003268 Thread* const self = Thread::Current();
3269 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003270 // Locate the dex cache of the original interface/Object
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003271 for (jobject weak_root : dex_caches_) {
3272 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
3273 if (dex_cache != nullptr &&
Vladimir Marko05792b92015-08-03 11:56:49 +01003274 proxy_method->HasSameDexCacheResolvedTypes(dex_cache->GetResolvedTypes(),
3275 image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003276 ArtMethod* resolved_method = dex_cache->GetResolvedMethod(
3277 proxy_method->GetDexMethodIndex(), image_pointer_size_);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003278 CHECK(resolved_method != nullptr);
3279 return resolved_method;
Ian Rogers16f93672012-02-14 12:29:06 -08003280 }
3281 }
3282 }
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003283 LOG(FATAL) << "Didn't find dex cache for " << PrettyClass(proxy_class) << " "
3284 << PrettyMethod(proxy_method);
3285 UNREACHABLE();
Ian Rogers16f93672012-02-14 12:29:06 -08003286}
3287
Mathieu Chartiere401d142015-04-22 13:56:20 -07003288void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
3289 // Create constructor for Proxy that must initialize the method.
3290 CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 16u);
3291 ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->GetDirectMethodUnchecked(
3292 2, image_pointer_size_);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003293 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3294 // constructor method.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003295 GetClassRoot(kJavaLangReflectProxy)->GetDexCache()->SetResolvedMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -07003296 proxy_constructor->GetDexMethodIndex(), proxy_constructor, image_pointer_size_);
Jeff Haodb8a6642014-08-14 17:18:52 -07003297 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3298 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07003299 DCHECK(out != nullptr);
3300 out->CopyFrom(proxy_constructor, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07003301 // Make this constructor public and fix the class to be our Proxy version
Mathieu Chartiere401d142015-04-22 13:56:20 -07003302 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) | kAccPublic);
3303 out->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003304}
3305
Mathieu Chartiere401d142015-04-22 13:56:20 -07003306void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07003307 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003308 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
3309 CHECK_STREQ(np->GetName(), "<init>");
3310 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003311 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003312}
3313
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003314void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003315 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003316 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3317 // prototype method
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003318 auto* dex_cache = prototype->GetDeclaringClass()->GetDexCache();
3319 // Avoid dirtying the dex cache unless we need to.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003320 if (dex_cache->GetResolvedMethod(prototype->GetDexMethodIndex(), image_pointer_size_) !=
3321 prototype) {
3322 dex_cache->SetResolvedMethod(
3323 prototype->GetDexMethodIndex(), prototype, image_pointer_size_);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003324 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003325 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003326 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07003327 DCHECK(out != nullptr);
3328 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07003329
3330 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3331 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiere401d142015-04-22 13:56:20 -07003332 out->SetDeclaringClass(klass.Get());
3333 out->SetAccessFlags((out->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003334
Ian Rogers466bb252011-10-14 03:29:56 -07003335 // At runtime the method looks like a reference and argument saving method, clone the code
3336 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003337 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08003338}
Jesse Wilson95caa792011-10-12 18:14:17 -04003339
Mathieu Chartiere401d142015-04-22 13:56:20 -07003340void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07003341 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003342 CHECK(!prototype->IsFinal());
3343 CHECK(method->IsFinal());
3344 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003345
3346 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3347 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Vladimir Marko05792b92015-08-03 11:56:49 +01003348 CHECK(prototype->HasSameDexCacheResolvedMethods(method, image_pointer_size_));
3349 CHECK(prototype->HasSameDexCacheResolvedTypes(method, image_pointer_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07003350 auto* np = method->GetInterfaceMethodIfProxy(image_pointer_size_);
3351 CHECK_EQ(prototype->GetDeclaringClass()->GetDexCache(), np->GetDexCache());
Ian Rogers19846512012-02-24 11:42:47 -08003352 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3353
Mathieu Chartiere401d142015-04-22 13:56:20 -07003354 CHECK_STREQ(np->GetName(), prototype->GetName());
3355 CHECK_STREQ(np->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003356 // More complex sanity - via dex cache
Vladimir Marko05792b92015-08-03 11:56:49 +01003357 CHECK_EQ(np->GetReturnType(true /* resolve */, image_pointer_size_),
3358 prototype->GetReturnType(true /* resolve */, image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04003359}
3360
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003361bool ClassLinker::CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003362 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003363 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003364 return true;
3365 }
3366 if (!can_init_statics) {
3367 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003368 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003369 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003370 return false;
3371 }
3372 // Check if there are encoded static values needing initialization.
3373 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003374 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003375 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003376 if (dex_class_def->static_values_off_ != 0) {
3377 return false;
3378 }
3379 }
Alex Lighteb7c1442015-08-31 13:17:42 -07003380 // If we are a class we need to initialize all interfaces with default methods when we are
3381 // initialized. Check all of them.
3382 if (!klass->IsInterface()) {
3383 size_t num_interfaces = klass->GetIfTableCount();
3384 for (size_t i = 0; i < num_interfaces; i++) {
3385 mirror::Class* iface = klass->GetIfTable()->GetInterface(i);
3386 if (iface->HasDefaultMethods() &&
3387 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
3388 return false;
3389 }
3390 }
3391 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003392 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003393 if (klass->IsInterface() || !klass->HasSuperClass()) {
3394 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003395 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003396 mirror::Class* super_class = klass->GetSuperClass();
3397 if (!can_init_parents && !super_class->IsInitialized()) {
3398 return false;
3399 }
3400 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003401}
3402
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003403bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
3404 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003405 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3406
3407 // Are we already initialized and therefore done?
3408 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3409 // an initialized class will never change its state.
3410 if (klass->IsInitialized()) {
3411 return true;
3412 }
3413
3414 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003415 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003416 return false;
3417 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003418
Ian Rogers7b078e82014-09-10 14:44:24 -07003419 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003420 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003421 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003422 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003423
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003424 // Re-check under the lock in case another thread initialized ahead of us.
3425 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003426 return true;
3427 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003428
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003429 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003430 if (klass->IsErroneous()) {
Andreas Gampecb086952015-11-02 16:20:00 -08003431 ThrowEarlierClassFailure(klass.Get(), true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07003432 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003433 return false;
3434 }
3435
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003436 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003437
3438 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003439 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003440 if (!klass->IsVerified()) {
3441 // We failed to verify, expect either the klass to be erroneous or verification failed at
3442 // compile time.
3443 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003444 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003445 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003446 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003447 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003448 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003449 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003450 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07003451 } else {
3452 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003453 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003454 }
3455
Brian Carlstromd1422f82011-09-28 11:37:09 -07003456 // If the class is kStatusInitializing, either this thread is
3457 // initializing higher up the stack or another thread has beat us
3458 // to initializing and we need to wait. Either way, this
3459 // invocation of InitializeClass will not be responsible for
3460 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003461 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07003462 // Could have got an exception during verification.
3463 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003464 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003465 return false;
3466 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003467 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003468 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003469 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003470 return true;
3471 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003472 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003473 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003474 }
3475
3476 if (!ValidateSuperClassDescriptors(klass)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003477 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003478 return false;
3479 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003480 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003481
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003482 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003483
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003484 // From here out other threads may observe that we're initializing and so changes of state
3485 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003486 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003487 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003488
3489 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003490 }
3491
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003492 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003493 if (!klass->IsInterface() && klass->HasSuperClass()) {
3494 mirror::Class* super_class = klass->GetSuperClass();
3495 if (!super_class->IsInitialized()) {
3496 CHECK(!super_class->IsInterface());
3497 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003498 StackHandleScope<1> hs(self);
3499 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07003500 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003501 if (!super_initialized) {
3502 // The super class was verified ahead of entering initializing, we should only be here if
3503 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003504 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003505 << "Super class initialization failed for "
3506 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003507 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003508 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003509 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003510 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003511 // Initialization failed because the super-class is erroneous.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003512 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003513 return false;
3514 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003515 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003516 }
3517
Alex Lighteb7c1442015-08-31 13:17:42 -07003518 if (!klass->IsInterface()) {
3519 // Initialize interfaces with default methods for the JLS.
3520 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07003521 // Only setup the (expensive) handle scope if we actually need to.
3522 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07003523 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07003524 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
3525 for (size_t i = 0; i < num_direct_interfaces; i++) {
3526 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass, i));
3527 CHECK(handle_scope_iface.Get() != nullptr);
3528 CHECK(handle_scope_iface->IsInterface());
3529 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
3530 // We have already done this for this interface. Skip it.
3531 continue;
3532 }
3533 // We cannot just call initialize class directly because we need to ensure that ALL
3534 // interfaces with default methods are initialized. Non-default interface initialization
3535 // will not affect other non-default super-interfaces.
3536 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
3537 handle_scope_iface,
3538 can_init_statics,
3539 can_init_parents);
3540 if (!iface_initialized) {
3541 ObjectLock<mirror::Class> lock(self, klass);
3542 // Initialization failed because one of our interfaces with default methods is erroneous.
3543 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
3544 return false;
3545 }
Alex Lighteb7c1442015-08-31 13:17:42 -07003546 }
3547 }
3548 }
3549
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003550 const size_t num_static_fields = klass->NumStaticFields();
3551 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003552 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003553 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003554 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07003555 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003556 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003557 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003558
3559 // Eagerly fill in static fields so that the we don't have to do as many expensive
3560 // Class::FindStaticField in ResolveField.
3561 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003562 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003563 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003564 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003565 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003566 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07003567 } else {
3568 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003569 }
3570 }
3571
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003572 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
3573 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07003574 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003575 ClassDataItemIterator field_it(dex_file, class_data);
3576 if (value_it.HasNext()) {
3577 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003578 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003579 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003580 ArtField* field = ResolveField(
3581 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003582 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003583 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003584 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003585 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003586 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003587 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003588 }
3589 }
3590 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003591
Mathieu Chartiere401d142015-04-22 13:56:20 -07003592 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003593 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003594 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003595 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003596 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003597 }
3598
Ian Rogers7b078e82014-09-10 14:44:24 -07003599 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003600 uint64_t t1 = NanoTime();
3601
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003602 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003603 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003604 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003605
3606 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003607 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003608 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003609 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003610 } else if (Runtime::Current()->IsTransactionAborted()) {
3611 // The exception thrown when the transaction aborted has been caught and cleared
3612 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01003613 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
3614 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02003615 Runtime::Current()->ThrowTransactionAbortError(self);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003616 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003617 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003618 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003619 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3620 RuntimeStats* thread_stats = self->GetStats();
3621 ++global_stats->class_init_count;
3622 ++thread_stats->class_init_count;
3623 global_stats->class_init_time_ns += (t1 - t0);
3624 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003625 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003626 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003627 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003628 std::string temp;
3629 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003630 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003631 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003632 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003633 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003634 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003635 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003636 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003637}
3638
Alex Lighteb7c1442015-08-31 13:17:42 -07003639// We recursively run down the tree of interfaces. We need to do this in the order they are declared
3640// and perform the initialization only on those interfaces that contain default methods.
3641bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
3642 Handle<mirror::Class> iface,
3643 bool can_init_statics,
3644 bool can_init_parents) {
3645 CHECK(iface->IsInterface());
3646 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07003647 // Only create the (expensive) handle scope if we need it.
3648 if (UNLIKELY(num_direct_ifaces > 0)) {
3649 StackHandleScope<1> hs(self);
3650 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
3651 // First we initialize all of iface's super-interfaces recursively.
3652 for (size_t i = 0; i < num_direct_ifaces; i++) {
3653 mirror::Class* super_iface = mirror::Class::GetDirectInterface(self, iface, i);
3654 if (!super_iface->HasBeenRecursivelyInitialized()) {
3655 // Recursive step
3656 handle_super_iface.Assign(super_iface);
3657 if (!InitializeDefaultInterfaceRecursive(self,
3658 handle_super_iface,
3659 can_init_statics,
3660 can_init_parents)) {
3661 return false;
3662 }
Alex Lighteb7c1442015-08-31 13:17:42 -07003663 }
3664 }
3665 }
3666
3667 bool result = true;
3668 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
3669 // initialize if we don't have default methods.
3670 if (iface->HasDefaultMethods()) {
3671 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
3672 }
3673
3674 // Mark that this interface has undergone recursive default interface initialization so we know we
3675 // can skip it on any later class initializations. We do this even if we are not a default
3676 // interface since we can still avoid the traversal. This is purely a performance optimization.
3677 if (result) {
3678 // TODO This should be done in a better way
3679 ObjectLock<mirror::Class> lock(self, iface);
3680 iface->SetRecursivelyInitialized();
3681 }
3682 return result;
3683}
3684
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003685bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
3686 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003687 ObjectLock<mirror::Class>& lock)
Mathieu Chartier90443472015-07-16 20:32:27 -07003688 SHARED_REQUIRES(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003689 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003690 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003691 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003692 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003693
3694 // When we wake up, repeat the test for init-in-progress. If
3695 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07003696 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003697 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003698 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003699 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003700 return false;
3701 }
3702 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003703 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003704 continue;
3705 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003706 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
3707 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003708 // Compile time initialization failed.
3709 return false;
3710 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003711 if (klass->IsErroneous()) {
3712 // The caller wants an exception, but it was thrown in a
3713 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003714 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003715 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003716 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003717 return false;
3718 }
3719 if (klass->IsInitialized()) {
3720 return true;
3721 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003722 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003723 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003724 }
Ian Rogers07140832014-09-30 15:43:59 -07003725 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003726}
3727
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003728static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
3729 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003730 ArtMethod* method,
3731 ArtMethod* m)
Mathieu Chartier90443472015-07-16 20:32:27 -07003732 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003733 DCHECK(Thread::Current()->IsExceptionPending());
3734 DCHECK(!m->IsProxyMethod());
3735 const DexFile* dex_file = m->GetDexFile();
3736 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
3737 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
3738 uint16_t return_type_idx = proto_id.return_type_idx_;
3739 std::string return_type = PrettyType(return_type_idx, *dex_file);
3740 std::string class_loader = PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
3741 ThrowWrappedLinkageError(klass.Get(),
3742 "While checking class %s method %s signature against %s %s: "
3743 "Failed to resolve return type %s with %s",
3744 PrettyDescriptor(klass.Get()).c_str(),
Mathieu Chartiere401d142015-04-22 13:56:20 -07003745 PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003746 super_klass->IsInterface() ? "interface" : "superclass",
3747 PrettyDescriptor(super_klass.Get()).c_str(),
3748 return_type.c_str(), class_loader.c_str());
3749}
3750
3751static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
3752 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003753 ArtMethod* method,
3754 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003755 uint32_t index,
3756 uint32_t arg_type_idx)
Mathieu Chartier90443472015-07-16 20:32:27 -07003757 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003758 DCHECK(Thread::Current()->IsExceptionPending());
3759 DCHECK(!m->IsProxyMethod());
3760 const DexFile* dex_file = m->GetDexFile();
3761 std::string arg_type = PrettyType(arg_type_idx, *dex_file);
3762 std::string class_loader = PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
3763 ThrowWrappedLinkageError(klass.Get(),
3764 "While checking class %s method %s signature against %s %s: "
3765 "Failed to resolve arg %u type %s with %s",
3766 PrettyDescriptor(klass.Get()).c_str(),
Mathieu Chartiere401d142015-04-22 13:56:20 -07003767 PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003768 super_klass->IsInterface() ? "interface" : "superclass",
3769 PrettyDescriptor(super_klass.Get()).c_str(),
3770 index, arg_type.c_str(), class_loader.c_str());
3771}
3772
3773static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
3774 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003775 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003776 const std::string& error_msg)
Mathieu Chartier90443472015-07-16 20:32:27 -07003777 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003778 ThrowLinkageError(klass.Get(),
3779 "Class %s method %s resolves differently in %s %s: %s",
3780 PrettyDescriptor(klass.Get()).c_str(),
Mathieu Chartiere401d142015-04-22 13:56:20 -07003781 PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003782 super_klass->IsInterface() ? "interface" : "superclass",
3783 PrettyDescriptor(super_klass.Get()).c_str(),
3784 error_msg.c_str());
3785}
3786
Ian Rogersb5fb2072014-12-02 17:22:02 -08003787static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Marko05792b92015-08-03 11:56:49 +01003788 size_t pointer_size,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003789 Handle<mirror::Class> klass,
3790 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003791 ArtMethod* method1,
3792 ArtMethod* method2)
Mathieu Chartier90443472015-07-16 20:32:27 -07003793 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003794 {
3795 StackHandleScope<1> hs(self);
Vladimir Marko05792b92015-08-03 11:56:49 +01003796 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType(true /* resolve */,
3797 pointer_size)));
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003798 if (UNLIKELY(return_type.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003799 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003800 return false;
3801 }
Vladimir Marko05792b92015-08-03 11:56:49 +01003802 mirror::Class* other_return_type = method2->GetReturnType(true /* resolve */,
3803 pointer_size);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003804 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003805 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003806 return false;
3807 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00003808 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003809 ThrowSignatureMismatch(klass, super_klass, method1,
3810 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
3811 PrettyClassAndClassLoader(return_type.Get()).c_str(),
3812 return_type.Get(),
3813 PrettyClassAndClassLoader(other_return_type).c_str(),
3814 other_return_type));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003815 return false;
3816 }
3817 }
3818 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
3819 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
3820 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003821 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003822 ThrowSignatureMismatch(klass, super_klass, method1,
3823 StringPrintf("Type list mismatch with %s",
Mathieu Chartiere401d142015-04-22 13:56:20 -07003824 PrettyMethod(method2, true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003825 return false;
3826 }
3827 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003828 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003829 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003830 ThrowSignatureMismatch(klass, super_klass, method1,
3831 StringPrintf("Type list mismatch with %s",
Mathieu Chartiere401d142015-04-22 13:56:20 -07003832 PrettyMethod(method2, true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003833 return false;
3834 }
3835 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003836 }
3837 uint32_t num_types = types1->Size();
3838 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003839 ThrowSignatureMismatch(klass, super_klass, method1,
3840 StringPrintf("Type list mismatch with %s",
Mathieu Chartiere401d142015-04-22 13:56:20 -07003841 PrettyMethod(method2, true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003842 return false;
3843 }
3844 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00003845 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003846 uint32_t param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00003847 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Marko05792b92015-08-03 11:56:49 +01003848 method1->GetClassFromTypeIndex(param_type_idx, true /* resolve */, pointer_size)));
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003849 if (UNLIKELY(param_type.Get() == nullptr)) {
3850 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003851 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003852 return false;
3853 }
3854 uint32_t other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003855 mirror::Class* other_param_type =
Vladimir Marko05792b92015-08-03 11:56:49 +01003856 method2->GetClassFromTypeIndex(other_param_type_idx, true /* resolve */, pointer_size);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003857 if (UNLIKELY(other_param_type == nullptr)) {
3858 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003859 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003860 return false;
3861 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00003862 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003863 ThrowSignatureMismatch(klass, super_klass, method1,
3864 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
3865 i,
3866 PrettyClassAndClassLoader(param_type.Get()).c_str(),
3867 param_type.Get(),
3868 PrettyClassAndClassLoader(other_param_type).c_str(),
3869 other_param_type));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003870 return false;
3871 }
3872 }
3873 return true;
3874}
3875
3876
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003877bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003878 if (klass->IsInterface()) {
3879 return true;
3880 }
Ian Rogers151f2212014-05-06 11:27:27 -07003881 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07003882 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003883 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003884 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003885 if (klass->HasSuperClass() &&
3886 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003887 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003888 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003889 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
3890 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
3891 if (m != super_m) {
Vladimir Marko05792b92015-08-03 11:56:49 +01003892 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, image_pointer_size_,
3893 klass, super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003894 m, super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003895 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003896 return false;
3897 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003898 }
3899 }
3900 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003901 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003902 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
3903 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
3904 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07003905 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003906 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
3907 j, image_pointer_size_);
3908 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
3909 if (m != super_m) {
Vladimir Marko05792b92015-08-03 11:56:49 +01003910 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, image_pointer_size_,
3911 klass, super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003912 m, super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003913 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003914 return false;
3915 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003916 }
3917 }
3918 }
3919 }
3920 return true;
3921}
3922
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003923bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003924 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003925 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003926 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003927 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003928 return true;
3929 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003930 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003931 if (!success) {
3932 if (can_init_fields && can_init_parents) {
3933 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
3934 }
3935 } else {
3936 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08003937 }
3938 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003939}
3940
Mathieu Chartiere401d142015-04-22 13:56:20 -07003941void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class,
3942 mirror::Class* new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003943 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003944 for (ArtField& field : new_class->GetIFields()) {
3945 if (field.GetDeclaringClass() == temp_class) {
3946 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003947 }
3948 }
3949
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003950 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003951 for (ArtField& field : new_class->GetSFields()) {
3952 if (field.GetDeclaringClass() == temp_class) {
3953 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003954 }
3955 }
3956
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003957 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003958 for (auto& method : new_class->GetDirectMethods(image_pointer_size_)) {
3959 if (method.GetDeclaringClass() == temp_class) {
3960 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003961 }
3962 }
3963
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003964 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003965 for (auto& method : new_class->GetVirtualMethods(image_pointer_size_)) {
3966 if (method.GetDeclaringClass() == temp_class) {
3967 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003968 }
3969 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003970
3971 // Make sure the remembered set and mod-union tables know that we updated some of the native
3972 // roots.
3973 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003974}
3975
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003976ClassTable* ClassLinker::InsertClassTableForClassLoader(mirror::ClassLoader* class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07003977 if (class_loader == nullptr) {
3978 return &boot_class_table_;
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003979 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07003980 ClassTable* class_table = class_loader->GetClassTable();
3981 if (class_table == nullptr) {
3982 class_table = new ClassTable;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003983 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003984 ClassLoaderData data;
3985 data.weak_root = self->GetJniEnv()->vm->AddWeakGlobalRef(self, class_loader);
3986 data.class_table = class_table;
Mathieu Chartier6b069532015-08-05 15:08:12 -07003987 // Don't already have a class table, add it to the class loader.
Mathieu Chartierc3fcd412015-09-25 16:54:59 -07003988 CHECK(class_loader->GetClassTable() == nullptr);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003989 class_loader->SetClassTable(data.class_table);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003990 // Should have been set when we registered the dex file.
3991 data.allocator = class_loader->GetAllocator();
3992 CHECK(data.allocator != nullptr);
3993 class_loaders_.push_back(data);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003994 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003995 return class_table;
3996}
3997
3998ClassTable* ClassLinker::ClassTableForClassLoader(mirror::ClassLoader* class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07003999 return class_loader == nullptr ? &boot_class_table_ : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004000}
4001
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004002bool ClassLinker::LinkClass(Thread* self,
4003 const char* descriptor,
4004 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004005 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004006 MutableHandle<mirror::Class>* h_new_class_out) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004007 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004008
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004009 if (!LinkSuperClass(klass)) {
4010 return false;
4011 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004012 ArtMethod* imt[mirror::Class::kImtSize];
4013 std::fill_n(imt, arraysize(imt), Runtime::Current()->GetImtUnimplementedMethod());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004014 if (!LinkMethods(self, klass, interfaces, imt)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004015 return false;
4016 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004017 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004018 return false;
4019 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004020 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004021 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004022 return false;
4023 }
4024 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004025 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004026
4027 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4028 // We don't need to retire this class as it has no embedded tables or it was created the
4029 // correct size during class linker initialization.
4030 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4031
4032 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004033 klass->PopulateEmbeddedImtAndVTable(imt, image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004034 }
4035
4036 // This will notify waiters on klass that saw the not yet resolved
4037 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004038 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004039 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004040 } else {
4041 CHECK(!klass->IsResolved());
4042 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004043 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004044 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07004045 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
4046 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
4047 // may not see any references to the target space and clean the card for a class if another
4048 // class had the same array pointer.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004049 klass->SetDirectMethodsPtrUnchecked(nullptr);
4050 klass->SetVirtualMethodsPtr(nullptr);
4051 klass->SetSFieldsPtrUnchecked(nullptr);
4052 klass->SetIFieldsPtrUnchecked(nullptr);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004053 if (UNLIKELY(h_new_class.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004054 self->AssertPendingOOMException();
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004055 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004056 return false;
4057 }
4058
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004059 CHECK_EQ(h_new_class->GetClassSize(), class_size);
4060 ObjectLock<mirror::Class> lock(self, h_new_class);
4061 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004062
4063 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07004064 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004065 mirror::ClassLoader* const class_loader = h_new_class.Get()->GetClassLoader();
4066 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
4067 mirror::Class* existing = table->UpdateClass(descriptor, h_new_class.Get(),
4068 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07004069 if (class_loader != nullptr) {
4070 // We updated the class in the class table, perform the write barrier so that the GC knows
4071 // about the change.
4072 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
4073 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004074 CHECK_EQ(existing, klass.Get());
4075 if (kIsDebugBuild && class_loader == nullptr && dex_cache_image_class_lookup_required_) {
4076 // Check a class loaded with the system class loader matches one in the image if the class
4077 // is in the image.
4078 mirror::Class* const image_class = LookupClassFromImage(descriptor);
4079 if (image_class != nullptr) {
4080 CHECK_EQ(klass.Get(), existing) << descriptor;
4081 }
4082 }
4083 if (log_new_class_table_roots_) {
4084 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
4085 }
4086 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004087
4088 // This will notify waiters on temp class that saw the not yet resolved class in the
4089 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004090 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004091
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004092 CHECK_EQ(h_new_class->GetStatus(), mirror::Class::kStatusResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004093 // This will notify waiters on new_class that saw the not yet resolved
4094 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004095 mirror::Class::SetStatus(h_new_class, mirror::Class::kStatusResolved, self);
4096 // Return the new class.
4097 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004098 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004099 return true;
4100}
4101
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004102static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
4103 size_t* virtual_methods,
4104 size_t* direct_methods,
4105 size_t* static_fields,
4106 size_t* instance_fields) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08004107 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
4108
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004109 while (dex_data.HasNextStaticField()) {
4110 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08004111 (*static_fields)++;
4112 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004113 while (dex_data.HasNextInstanceField()) {
4114 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08004115 (*instance_fields)++;
4116 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004117 while (dex_data.HasNextDirectMethod()) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08004118 (*direct_methods)++;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004119 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08004120 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004121 while (dex_data.HasNextVirtualMethod()) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08004122 (*virtual_methods)++;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004123 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08004124 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004125 DCHECK(!dex_data.HasNext());
Andreas Gampefd9eb392014-11-06 16:52:58 -08004126}
4127
4128static void DumpClass(std::ostream& os,
4129 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
4130 const char* suffix) {
4131 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
4132 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
4133 os << " Static fields:\n";
4134 while (dex_data.HasNextStaticField()) {
4135 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4136 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4137 dex_data.Next();
4138 }
4139 os << " Instance fields:\n";
4140 while (dex_data.HasNextInstanceField()) {
4141 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4142 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4143 dex_data.Next();
4144 }
4145 os << " Direct methods:\n";
4146 while (dex_data.HasNextDirectMethod()) {
4147 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4148 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4149 dex_data.Next();
4150 }
4151 os << " Virtual methods:\n";
4152 while (dex_data.HasNextVirtualMethod()) {
4153 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4154 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4155 dex_data.Next();
4156 }
4157}
4158
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004159static std::string DumpClasses(const DexFile& dex_file1,
4160 const DexFile::ClassDef& dex_class_def1,
4161 const DexFile& dex_file2,
4162 const DexFile::ClassDef& dex_class_def2) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08004163 std::ostringstream os;
4164 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
4165 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
4166 return os.str();
4167}
4168
4169
4170// Very simple structural check on whether the classes match. Only compares the number of
4171// methods and fields.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004172static bool SimpleStructuralCheck(const DexFile& dex_file1,
4173 const DexFile::ClassDef& dex_class_def1,
4174 const DexFile& dex_file2,
4175 const DexFile::ClassDef& dex_class_def2,
Andreas Gampefd9eb392014-11-06 16:52:58 -08004176 std::string* error_msg) {
4177 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
4178 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
4179
4180 // Counters for current dex file.
4181 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004182 CountMethodsAndFields(dex_data1,
4183 &dex_virtual_methods1,
4184 &dex_direct_methods1,
4185 &dex_static_fields1,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004186 &dex_instance_fields1);
Andreas Gampefd9eb392014-11-06 16:52:58 -08004187 // Counters for compile-time dex file.
4188 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004189 CountMethodsAndFields(dex_data2,
4190 &dex_virtual_methods2,
4191 &dex_direct_methods2,
4192 &dex_static_fields2,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004193 &dex_instance_fields2);
Andreas Gampefd9eb392014-11-06 16:52:58 -08004194
4195 if (dex_virtual_methods1 != dex_virtual_methods2) {
4196 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004197 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s",
4198 dex_virtual_methods1,
4199 dex_virtual_methods2,
4200 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08004201 return false;
4202 }
4203 if (dex_direct_methods1 != dex_direct_methods2) {
4204 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004205 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s",
4206 dex_direct_methods1,
4207 dex_direct_methods2,
4208 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08004209 return false;
4210 }
4211 if (dex_static_fields1 != dex_static_fields2) {
4212 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004213 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s",
4214 dex_static_fields1,
4215 dex_static_fields2,
4216 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08004217 return false;
4218 }
4219 if (dex_instance_fields1 != dex_instance_fields2) {
4220 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004221 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s",
4222 dex_instance_fields1,
4223 dex_instance_fields2,
4224 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08004225 return false;
4226 }
4227
4228 return true;
4229}
4230
4231// Checks whether a the super-class changed from what we had at compile-time. This would
4232// invalidate quickening.
4233static bool CheckSuperClassChange(Handle<mirror::Class> klass,
4234 const DexFile& dex_file,
4235 const DexFile::ClassDef& class_def,
4236 mirror::Class* super_class)
Mathieu Chartier90443472015-07-16 20:32:27 -07004237 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08004238 // Check for unexpected changes in the superclass.
4239 // Quick check 1) is the super_class class-loader the boot class loader? This always has
4240 // precedence.
4241 if (super_class->GetClassLoader() != nullptr &&
4242 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
4243 // which is implied by different dex cache.
4244 klass->GetDexCache() != super_class->GetDexCache()) {
4245 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
4246 // definition for the super-class, and (b) the files are in separate oat files. The oat files
4247 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
Richard Uhler07b3c232015-03-31 15:57:54 -07004248 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
4249 const OatFile* class_oat_file = nullptr;
4250 if (class_oat_dex_file != nullptr) {
4251 class_oat_file = class_oat_dex_file->GetOatFile();
4252 }
4253
Andreas Gampefd9eb392014-11-06 16:52:58 -08004254 if (class_oat_file != nullptr) {
Richard Uhler07b3c232015-03-31 15:57:54 -07004255 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
4256 const OatFile* loaded_super_oat_file = nullptr;
4257 if (loaded_super_oat_dex_file != nullptr) {
4258 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
4259 }
4260
Andreas Gampefd9eb392014-11-06 16:52:58 -08004261 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
4262 // Now check (a).
4263 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
4264 if (super_class_def != nullptr) {
4265 // Uh-oh, we found something. Do our check.
4266 std::string error_msg;
4267 if (!SimpleStructuralCheck(dex_file, *super_class_def,
4268 super_class->GetDexFile(), *super_class->GetClassDef(),
4269 &error_msg)) {
4270 // Print a warning to the log. This exception might be caught, e.g., as common in test
4271 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
4272 // only save the type of the exception.
4273 LOG(WARNING) << "Incompatible structural change detected: " <<
4274 StringPrintf(
4275 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4276 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4277 class_oat_file->GetLocation().c_str(),
4278 loaded_super_oat_file->GetLocation().c_str(),
4279 error_msg.c_str());
4280 ThrowIncompatibleClassChangeError(klass.Get(),
4281 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4282 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4283 class_oat_file->GetLocation().c_str(),
4284 loaded_super_oat_file->GetLocation().c_str(),
4285 error_msg.c_str());
4286 return false;
4287 }
4288 }
4289 }
4290 }
4291 }
4292 return true;
4293}
4294
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004295bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004296 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004297 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4298 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004299 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004300 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004301 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004302 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004303 return false;
4304 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004305 // Verify
4306 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004307 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004308 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004309 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004310 return false;
4311 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004312 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004313 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08004314
4315 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
4316 DCHECK(Thread::Current()->IsExceptionPending());
4317 return false;
4318 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004319 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004320 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004321 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004322 for (size_t i = 0; i < interfaces->Size(); i++) {
4323 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004324 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004325 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004326 DCHECK(Thread::Current()->IsExceptionPending());
4327 return false;
4328 }
4329 // Verify
4330 if (!klass->CanAccess(interface)) {
4331 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004332 ThrowIllegalAccessError(klass.Get(),
4333 "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004334 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004335 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004336 return false;
4337 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004338 }
4339 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004340 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004341 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004342 return true;
4343}
4344
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004345bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004346 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004347 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004348 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004349 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004350 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004351 return false;
4352 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004353 return true;
4354 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004355 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004356 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4357 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004358 return false;
4359 }
4360 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004361 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004362 ThrowIncompatibleClassChangeError(klass.Get(),
4363 "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004364 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004365 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004366 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004367 return false;
4368 }
4369 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004370 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004371 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004372 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004373 return false;
4374 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004375
Brian Carlstromf3632832014-05-20 15:36:53 -07004376 // Inherit kAccClassIsFinalizable from the superclass in case this
4377 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004378 if (super->IsFinalizable()) {
4379 klass->SetFinalizable();
4380 }
4381
Mathieu Chartiere4275c02015-08-06 15:34:15 -07004382 // Inherit class loader flag form super class.
4383 if (super->IsClassLoaderClass()) {
4384 klass->SetClassLoaderClass();
4385 }
4386
Elliott Hughes2da50362011-10-10 16:57:08 -07004387 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07004388 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07004389 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07004390 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004391 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07004392 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004393 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004394 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004395 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004396 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004397 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004398 return false;
4399 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004400
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004401 if (kIsDebugBuild) {
4402 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004403 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004404 CHECK(super->IsResolved());
4405 super = super->GetSuperClass();
4406 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004407 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004408 return true;
4409}
4410
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004411// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004412bool ClassLinker::LinkMethods(Thread* self,
4413 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004414 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004415 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004416 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07004417 // A map from vtable indexes to the method they need to be updated to point to. Used because we
4418 // need to have default methods be in the virtuals array of each class but we don't set that up
4419 // until LinkInterfaceMethods.
4420 std::unordered_map<size_t, ArtMethod*> default_translations;
4421 // Link virtual methods then interface methods.
4422 // We set up the interface lookup table first because we need it to determine if we need to update
4423 // any vtable entries with new default method implementations.
4424 return SetupInterfaceLookupTable(self, klass, interfaces)
4425 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
4426 && LinkInterfaceMethods(self, klass, default_translations, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004427}
4428
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004429// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4430// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4431// caches in the implementation below.
4432class MethodNameAndSignatureComparator FINAL : public ValueObject {
4433 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07004434 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07004435 SHARED_REQUIRES(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004436 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4437 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004438 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4439 }
4440
4441 const char* GetName() {
4442 if (name_ == nullptr) {
4443 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4444 }
4445 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004446 }
4447
Mathieu Chartiere401d142015-04-22 13:56:20 -07004448 bool HasSameNameAndSignature(ArtMethod* other)
Mathieu Chartier90443472015-07-16 20:32:27 -07004449 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004450 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4451 const DexFile* other_dex_file = other->GetDexFile();
4452 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4453 if (dex_file_ == other_dex_file) {
4454 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4455 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004456 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004457 uint32_t other_name_len;
4458 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4459 &other_name_len);
4460 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4461 return false;
4462 }
4463 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4464 }
4465
4466 private:
4467 // Dex file for the method to compare against.
4468 const DexFile* const dex_file_;
4469 // MethodId for the method to compare against.
4470 const DexFile::MethodId* const mid_;
4471 // Lazily computed name from the dex file's strings.
4472 const char* name_;
4473 // Lazily computed name length.
4474 uint32_t name_len_;
4475};
4476
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004477class LinkVirtualHashTable {
4478 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004479 LinkVirtualHashTable(Handle<mirror::Class> klass,
4480 size_t hash_size,
4481 uint32_t* hash_table,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004482 size_t image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004483 : klass_(klass),
4484 hash_size_(hash_size),
4485 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07004486 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004487 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4488 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004489
Mathieu Chartier90443472015-07-16 20:32:27 -07004490 void Add(uint32_t virtual_method_index) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004491 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
4492 virtual_method_index, image_pointer_size_);
4493 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004494 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004495 uint32_t index = hash % hash_size_;
4496 // Linear probe until we have an empty slot.
4497 while (hash_table_[index] != invalid_index_) {
4498 if (++index == hash_size_) {
4499 index = 0;
4500 }
4501 }
4502 hash_table_[index] = virtual_method_index;
4503 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004504
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004505 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Mathieu Chartier90443472015-07-16 20:32:27 -07004506 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004507 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004508 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004509 size_t index = hash % hash_size_;
4510 while (true) {
4511 const uint32_t value = hash_table_[index];
4512 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4513 // the block and can safely assume not found.
4514 if (value == invalid_index_) {
4515 break;
4516 }
4517 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004518 ArtMethod* virtual_method =
4519 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
4520 if (comparator->HasSameNameAndSignature(
4521 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004522 hash_table_[index] = removed_index_;
4523 return value;
4524 }
4525 }
4526 if (++index == hash_size_) {
4527 index = 0;
4528 }
4529 }
4530 return GetNotFoundIndex();
4531 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004532
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004533 static uint32_t GetNotFoundIndex() {
4534 return invalid_index_;
4535 }
4536
4537 private:
4538 static const uint32_t invalid_index_;
4539 static const uint32_t removed_index_;
4540
4541 Handle<mirror::Class> klass_;
4542 const size_t hash_size_;
4543 uint32_t* const hash_table_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004544 const size_t image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004545};
4546
4547const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4548const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4549
Alex Lighteb7c1442015-08-31 13:17:42 -07004550bool ClassLinker::LinkVirtualMethods(
4551 Thread* self,
4552 Handle<mirror::Class> klass,
4553 /*out*/std::unordered_map<size_t, ArtMethod*>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004554 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07004555 if (klass->IsInterface()) {
4556 // No vtable.
4557 if (!IsUint<16>(num_virtual_methods)) {
4558 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
4559 return false;
4560 }
4561 bool has_defaults = false;
4562 // TODO May need to replace this with real VTable for invoke_super
4563 // Assign each method an IMT index and set the default flag.
4564 for (size_t i = 0; i < num_virtual_methods; ++i) {
4565 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
4566 m->SetMethodIndex(i);
4567 if (!m->IsAbstract()) {
4568 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
4569 has_defaults = true;
4570 }
4571 }
4572 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
4573 // during initialization. This is a performance optimization. We could simply traverse the
4574 // virtual_methods_ array again during initialization.
4575 if (has_defaults) {
4576 klass->SetHasDefaultMethods();
4577 }
4578 return true;
4579 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004580 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4581 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004582 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004583 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07004584 MutableHandle<mirror::PointerArray> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004585 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004586 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004587 if (UNLIKELY(vtable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004588 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004589 return false;
4590 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004591 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004592 vtable->SetElementPtrSize(
4593 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004594 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004595 // We might need to change vtable if we have new virtual methods or new interfaces (since that
4596 // might give us new default methods). If no new interfaces then we can skip the rest since
4597 // the class cannot override any of the super-class's methods. This is required for
4598 // correctness since without it we might not update overridden default method vtable entries
4599 // correctly.
4600 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004601 klass->SetVTable(vtable.Get());
4602 return true;
4603 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004604 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07004605 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004606 auto* super_vtable = super_class->GetVTable();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004607 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07004608 // We might need to change vtable if we have new virtual methods or new interfaces (since that
4609 // might give us new default methods). See comment above.
4610 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004611 klass->SetVTable(super_vtable);
4612 return true;
4613 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004614 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
4615 super_vtable->CopyOf(self, max_count)));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004616 if (UNLIKELY(vtable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004617 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004618 return false;
4619 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004620 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004621 // How the algorithm works:
4622 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4623 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4624 // method which has not been matched to a vtable method, and j if the virtual method at the
4625 // index overrode the super virtual method at index j.
4626 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4627 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4628 // the need for the initial vtable which we later shrink back down).
4629 // 3. Add non overridden methods to the end of the vtable.
4630 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07004631 // + 1 so that even if we only have new default methods we will still be able to use this hash
4632 // table (i.e. it will never have 0 size).
4633 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004634 uint32_t* hash_table_ptr;
4635 std::unique_ptr<uint32_t[]> hash_heap_storage;
4636 if (hash_table_size <= kMaxStackHash) {
4637 hash_table_ptr = reinterpret_cast<uint32_t*>(
4638 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4639 } else {
4640 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4641 hash_table_ptr = hash_heap_storage.get();
4642 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004643 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004644 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004645 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004646 DCHECK(klass->GetVirtualMethodDuringLinking(
4647 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004648 hash_table.Add(i);
4649 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004650 // 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 -07004651 // the hash table.
4652 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07004653 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004654 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004655 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07004656 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004657 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4658 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004659 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
4660 hash_index, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004661 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4662 super_method->GetAccessFlags())) {
4663 if (super_method->IsFinal()) {
4664 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4665 PrettyMethod(virtual_method).c_str(),
4666 super_method->GetDeclaringClassDescriptor());
4667 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004668 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004669 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004670 virtual_method->SetMethodIndex(j);
4671 } else {
4672 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004673 << " would have incorrectly overridden the package-private method in "
4674 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004675 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004676 } else if (super_method->IsDefault()) {
4677 // We didn't directly override this method but we might through default methods...
4678 // Check for default method update.
4679 ArtMethod* default_method = nullptr;
4680 std::string icce_message;
4681 if (!FindDefaultMethodImplementation(self,
4682 super_method,
4683 klass,
4684 /*out*/&default_method,
4685 /*out*/&icce_message)) {
4686 // An error occurred while finding default methods.
4687 // TODO This should actually be thrown when we attempt to invoke this method.
4688 ThrowIncompatibleClassChangeError(klass.Get(), "%s", icce_message.c_str());
4689 return false;
4690 }
4691 // This should always work because we inherit superclass interfaces. We should either get
4692 // 1) An IncompatibleClassChangeError because of conflicting default method
4693 // implementations.
4694 // 2) The same default method implementation as the superclass.
4695 // 3) A default method that overrides the superclass's.
4696 // Therefore this check should never fail.
4697 CHECK(default_method != nullptr);
4698 if (UNLIKELY(default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
4699 // TODO Refactor this add default methods to virtuals here and not in
4700 // LinkInterfaceMethods maybe.
4701 // The problem is default methods might override previously present default-method or
4702 // miranda-method vtable entries from the superclass. Unfortunately we need these to
4703 // be entries in this class's virtuals. We do not give these entries there until
4704 // LinkInterfaceMethods so we pass this map around to let it know which vtable
4705 // entries need to be updated.
4706 // Make a note that vtable entry j must be updated, store what it needs to be updated to.
4707 // We will allocate a virtual method slot in LinkInterfaceMethods and fix it up then.
4708 default_translations->insert({j, default_method});
4709 VLOG(class_linker) << "Method " << PrettyMethod(super_method) << " overridden by default "
4710 << PrettyMethod(default_method) << " in " << PrettyClass(klass.Get());
4711 } else {
4712 // They are the same method/no override
4713 // Cannot do direct comparison because we had to copy the ArtMethod object into the
4714 // superclass's vtable.
4715 continue;
4716 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004717 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004718 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004719 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07004720 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004721 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004722 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004723 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4724 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07004725 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004726 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004727 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004728 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004729 local_method->SetMethodIndex(actual_count);
4730 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004731 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004732 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004733 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004734 return false;
4735 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004736 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004737 CHECK_LE(actual_count, max_count);
4738 if (actual_count < max_count) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004739 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004740 if (UNLIKELY(vtable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004741 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07004742 return false;
4743 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004744 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004745 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004746 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004747 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004748 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004749 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4750 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004751 return false;
4752 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004753 auto* vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004754 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004755 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07004756 return false;
4757 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004758 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004759 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
4760 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004761 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004762 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004763 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004764 }
4765 return true;
4766}
4767
Alex Lighteb7c1442015-08-31 13:17:42 -07004768// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
4769// out_default_method and returns true on success. If no default method was found stores nullptr
4770// into out_default_method and returns true. If an error occurs (such as a default_method conflict)
4771// it will fill the icce_message with an appropriate message for an IncompatibleClassChangeError,
4772// which should then be thrown by the caller.
4773bool ClassLinker::FindDefaultMethodImplementation(Thread* self,
4774 ArtMethod* target_method,
4775 Handle<mirror::Class> klass,
4776 /*out*/ArtMethod** out_default_method,
4777 /*out*/std::string* icce_message) const {
4778 DCHECK(self != nullptr);
4779 DCHECK(target_method != nullptr);
4780 DCHECK(out_default_method != nullptr);
4781 DCHECK(icce_message != nullptr);
4782
4783 *out_default_method = nullptr;
4784 mirror::Class* chosen_iface = nullptr;
4785
4786 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
4787 // table. This lets us walk the table backwards when searching for default methods. The first one
4788 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
4789 // track of it and then continue checking all other interfaces, since we need to throw an error if
4790 // we encounter conflicting default method implementations (one is not a subtype of the other).
4791 //
4792 // The order of unrelated interfaces does not matter and is not defined.
4793 size_t iftable_count = klass->GetIfTableCount();
4794 if (iftable_count == 0) {
4795 // No interfaces. We have already reset out to null so just return true.
4796 return true;
4797 }
4798
4799 StackHandleScope<1> hs(self);
4800 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
4801 MethodNameAndSignatureComparator target_name_comparator(
4802 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
4803 // Iterates over the klass's iftable in reverse
4804 // We have a break at the end because size_t is unsigned.
4805 for (size_t k = iftable_count - 1; /* break if k == 0 at end */; --k) {
4806 DCHECK_LT(k, iftable->Count());
4807 mirror::Class* iface = iftable->GetInterface(k);
4808 size_t num_instance_methods = iface->NumVirtualMethods();
4809 // Iterate through every method on this interface. The order does not matter so we go forwards.
4810 for (size_t m = 0; m < num_instance_methods; m++) {
4811 ArtMethod* current_method = iface->GetVirtualMethodUnchecked(m, image_pointer_size_);
4812 // Skip abstract methods and methods with different names.
4813 if (current_method->IsAbstract() ||
4814 !target_name_comparator.HasSameNameAndSignature(
4815 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
4816 continue;
4817 }
4818 // The verifier should have caught the non-public method.
4819 DCHECK(current_method->IsPublic()) << "Interface method is not public!";
4820 if (UNLIKELY(chosen_iface != nullptr)) {
4821 // We have multiple default impls of the same method. We need to check they do not
4822 // conflict and throw an error if they do. Conflicting means that the current iface is not
4823 // masked by the chosen interface.
4824 if (!iface->IsAssignableFrom(chosen_iface)) {
4825 *icce_message = StringPrintf("Conflicting default method implementations: '%s' and '%s'",
4826 PrettyMethod(current_method).c_str(),
4827 PrettyMethod(*out_default_method).c_str());
4828 return false;
4829 } else {
4830 break; // Continue checking at the next interface.
4831 }
4832 } else {
4833 *out_default_method = current_method;
4834 chosen_iface = iface;
4835 // We should now finish traversing the graph to find if we have default methods that
4836 // conflict.
4837 break;
4838 }
4839 }
4840 if (k == 0) {
4841 break;
4842 }
4843 }
4844 return true;
4845}
4846
4847// Sets imt_ref appropriately for LinkInterfaceMethods.
4848// If there is no method in the imt location of imt_ref it will store the given method there.
4849// Otherwise it will set the conflict method which will figure out which method to use during
4850// runtime.
4851static void SetIMTRef(ArtMethod* unimplemented_method,
4852 ArtMethod* conflict_method,
4853 size_t image_pointer_size,
4854 ArtMethod* current_method,
4855 /*out*/ArtMethod** imt_ref)
4856 SHARED_REQUIRES(Locks::mutator_lock_) {
4857 // Place method in imt if entry is empty, place conflict otherwise.
4858 if (*imt_ref == unimplemented_method) {
4859 *imt_ref = current_method;
4860 } else if (*imt_ref != conflict_method) {
4861 // If we are not a conflict and we have the same signature and name as the imt
4862 // entry, it must be that we overwrote a superclass vtable entry.
4863 MethodNameAndSignatureComparator imt_comparator(
4864 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size));
4865 if (imt_comparator.HasSameNameAndSignature(
4866 current_method->GetInterfaceMethodIfProxy(image_pointer_size))) {
4867 *imt_ref = current_method;
4868 } else {
4869 *imt_ref = conflict_method;
4870 }
4871 }
4872}
4873
4874// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
4875// set.
4876static bool NotSubinterfaceOfAny(const std::unordered_set<mirror::Class*>& classes,
4877 mirror::Class* val)
4878 REQUIRES(Roles::uninterruptible_)
4879 SHARED_REQUIRES(Locks::mutator_lock_) {
4880 DCHECK(val != nullptr);
4881 for (auto c : classes) {
4882 if (val->IsAssignableFrom(&*c)) {
4883 return false;
4884 }
4885 }
4886 return true;
4887}
4888
4889// Fills in and flattens the interface inheritance hierarchy.
4890//
4891// By the end of this function all interfaces in the transitive closure of to_process are added to
4892// the iftable and every interface precedes all of its sub-interfaces in this list.
4893//
4894// all I, J: Interface | I <: J implies J precedes I
4895//
4896// (note A <: B means that A is a subtype of B)
4897//
4898// This returns the total number of items in the iftable. The iftable might be resized down after
4899// this call.
4900//
4901// We order this backwards so that we do not need to reorder superclass interfaces when new
4902// interfaces are added in subclass's interface tables.
4903//
4904// Upon entry into this function iftable is a copy of the superclass's iftable with the first
4905// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
4906// The other entries are uninitialized. We will fill in the remaining entries in this function. The
4907// iftable must be large enough to hold all interfaces without changing its size.
4908static size_t FillIfTable(mirror::IfTable* iftable,
4909 size_t super_ifcount,
4910 std::vector<mirror::Class*> to_process)
4911 REQUIRES(Roles::uninterruptible_)
4912 SHARED_REQUIRES(Locks::mutator_lock_) {
4913 // This is the set of all class's already in the iftable. Used to make checking if a class has
4914 // already been added quicker.
4915 std::unordered_set<mirror::Class*> classes_in_iftable;
4916 // The first super_ifcount elements are from the superclass. We note that they are already added.
4917 for (size_t i = 0; i < super_ifcount; i++) {
4918 mirror::Class* iface = iftable->GetInterface(i);
4919 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
4920 classes_in_iftable.insert(iface);
4921 }
4922 size_t filled_ifcount = super_ifcount;
4923 for (mirror::Class* interface : to_process) {
4924 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
4925 // At this point in the loop current-iface-list has the invariant that:
4926 // for every pair of interfaces I,J within it:
4927 // if index_of(I) < index_of(J) then I is not a subtype of J
4928
4929 // If we have already seen this element then all of its super-interfaces must already be in the
4930 // current-iface-list so we can skip adding it.
4931 if (!ContainsElement(classes_in_iftable, interface)) {
4932 // We haven't seen this interface so add all of its super-interfaces onto the
4933 // current-iface-list, skipping those already on it.
4934 int32_t ifcount = interface->GetIfTableCount();
4935 for (int32_t j = 0; j < ifcount; j++) {
4936 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
4937 if (!ContainsElement(classes_in_iftable, super_interface)) {
4938 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
4939 classes_in_iftable.insert(super_interface);
4940 iftable->SetInterface(filled_ifcount, super_interface);
4941 filled_ifcount++;
4942 }
4943 }
4944 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
4945 // Place this interface onto the current-iface-list after all of its super-interfaces.
4946 classes_in_iftable.insert(interface);
4947 iftable->SetInterface(filled_ifcount, interface);
4948 filled_ifcount++;
4949 } else if (kIsDebugBuild) {
4950 // Check all super-interfaces are already in the list.
4951 int32_t ifcount = interface->GetIfTableCount();
4952 for (int32_t j = 0; j < ifcount; j++) {
4953 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
4954 DCHECK(ContainsElement(classes_in_iftable, super_interface))
4955 << "Iftable does not contain " << PrettyClass(super_interface)
4956 << ", a superinterface of " << PrettyClass(interface);
4957 }
4958 }
4959 }
4960 if (kIsDebugBuild) {
4961 // Check that the iftable is ordered correctly.
4962 for (size_t i = 0; i < filled_ifcount; i++) {
4963 mirror::Class* if_a = iftable->GetInterface(i);
4964 for (size_t j = i + 1; j < filled_ifcount; j++) {
4965 mirror::Class* if_b = iftable->GetInterface(j);
4966 // !(if_a <: if_b)
4967 CHECK(!if_b->IsAssignableFrom(if_a))
4968 << "Bad interface order: " << PrettyClass(if_a) << " (index " << i << ") extends "
4969 << PrettyClass(if_b) << " (index " << j << ") and so should be after it in the "
4970 << "interface list.";
4971 }
4972 }
4973 }
4974 return filled_ifcount;
4975}
4976
4977bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
4978 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
4979 StackHandleScope<1> hs(self);
4980 const size_t super_ifcount =
4981 klass->HasSuperClass() ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004982 const bool have_interfaces = interfaces.Get() != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07004983 const size_t num_interfaces =
4984 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004985 if (num_interfaces == 0) {
4986 if (super_ifcount == 0) {
4987 // Class implements no interfaces.
4988 DCHECK_EQ(klass->GetIfTableCount(), 0);
4989 DCHECK(klass->GetIfTable() == nullptr);
4990 return true;
4991 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004992 // Class implements same interfaces as parent, are any of these not marker interfaces?
4993 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004994 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004995 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004996 if (super_iftable->GetMethodArrayCount(i) > 0) {
4997 has_non_marker_interface = true;
4998 break;
4999 }
5000 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005001 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07005002 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005003 klass->SetIfTable(super_iftable);
5004 return true;
5005 }
5006 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005007 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07005008 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005009 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005010 mirror::Class* interface = have_interfaces
5011 ? interfaces->GetWithoutChecks(i)
5012 : mirror::Class::GetDirectInterface(self, klass, i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005013 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005014 if (UNLIKELY(!interface->IsInterface())) {
5015 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005016 ThrowIncompatibleClassChangeError(klass.Get(),
5017 "Class %s implements non-interface class %s",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005018 PrettyDescriptor(klass.Get()).c_str(),
5019 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
5020 return false;
5021 }
5022 ifcount += interface->GetIfTableCount();
5023 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005024 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005025 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005026 if (UNLIKELY(iftable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005027 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005028 return false;
5029 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005030 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005031 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005032 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005033 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005034 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07005035 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005036 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005037 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005038
5039 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
5040 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
5041 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07005042 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005043
5044 size_t new_ifcount;
5045 {
5046 ScopedAssertNoThreadSuspension nts(self, "Copying mirror::Class*'s for FillIfTable");
5047 std::vector<mirror::Class*> to_add;
5048 for (size_t i = 0; i < num_interfaces; i++) {
5049 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
5050 mirror::Class::GetDirectInterface(self, klass, i);
5051 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005052 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005053
5054 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005055 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005056
Ian Rogers7b078e82014-09-10 14:44:24 -07005057 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005058
Ian Rogersb52b01a2012-01-12 17:01:38 -08005059 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07005060 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005061 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005062 iftable.Assign(down_cast<mirror::IfTable*>(
Alex Lighteb7c1442015-08-31 13:17:42 -07005063 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005064 if (UNLIKELY(iftable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005065 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005066 return false;
5067 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005068 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08005069 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07005070 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005071 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005072 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07005073 return true;
5074}
5075
5076bool ClassLinker::LinkInterfaceMethods(
5077 Thread* self,
5078 Handle<mirror::Class> klass,
5079 const std::unordered_map<size_t, ArtMethod*>& default_translations,
5080 ArtMethod** out_imt) {
5081 StackHandleScope<3> hs(self);
5082 Runtime* const runtime = Runtime::Current();
5083 const bool has_superclass = klass->HasSuperClass();
5084 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
5085 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
5086 const size_t method_size = ArtMethod::Size(image_pointer_size_);
5087 const size_t ifcount = klass->GetIfTableCount();
5088
5089 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
5090
Elliott Hughes4681c802011-09-25 18:04:37 -07005091 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07005092 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005093 return true;
5094 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005095 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
5096 // the virtual methods array.
5097 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
5098 // during cross compilation.
5099 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
5100 ArenaStack stack(runtime->GetLinearAlloc()->GetArenaPool());
5101 ScopedArenaAllocator allocator(&stack);
5102 ScopedArenaVector<ArtMethod*> miranda_methods(allocator.Adapter());
Alex Lighteb7c1442015-08-31 13:17:42 -07005103 ScopedArenaVector<ArtMethod*> default_methods(allocator.Adapter());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005104
5105 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
5106 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
5107 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005108 // Copy the IMT from the super class if possible.
5109 bool extend_super_iftable = false;
5110 if (has_superclass) {
5111 mirror::Class* super_class = klass->GetSuperClass();
5112 extend_super_iftable = true;
5113 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5114 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005115 out_imt[i] = super_class->GetEmbeddedImTableEntry(i, image_pointer_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005116 }
5117 } else {
5118 // No imt in the super class, need to reconstruct from the iftable.
5119 mirror::IfTable* if_table = super_class->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005120 const size_t length = super_class->GetIfTableCount();
5121 for (size_t i = 0; i < length; ++i) {
5122 mirror::Class* interface = iftable->GetInterface(i);
5123 const size_t num_virtuals = interface->NumVirtualMethods();
5124 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5125 DCHECK_EQ(num_virtuals, method_array_count);
5126 if (method_array_count == 0) {
5127 continue;
5128 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005129 auto* method_array = if_table->GetMethodArray(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005130 for (size_t j = 0; j < num_virtuals; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005131 auto method = method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
5132 DCHECK(method != nullptr) << PrettyClass(super_class);
Alex Lighteb7c1442015-08-31 13:17:42 -07005133 // Miranda methods cannot be used to implement an interface method and defaults should be
5134 // skipped in case we override it.
5135 if (method->IsDefault() || method->IsMiranda()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005136 continue;
5137 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005138 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005139 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
Mathieu Chartiercf3b1a32015-06-01 14:30:06 -07005140 auto** imt_ref = &out_imt[imt_index];
5141 if (*imt_ref == unimplemented_method) {
5142 *imt_ref = method;
5143 } else if (*imt_ref != conflict_method) {
5144 *imt_ref = conflict_method;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005145 }
5146 }
5147 }
5148 }
5149 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005150 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
5151 // thread suspension.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005152 for (size_t i = 0; i < ifcount; ++i) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005153 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005154 if (num_methods > 0) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005155 const bool is_super = i < super_ifcount;
Alex Lighteb7c1442015-08-31 13:17:42 -07005156 // This is an interface implemented by a super-class. Therefore we can just copy the method
5157 // array from the superclass.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005158 const bool super_interface = is_super && extend_super_iftable;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005159 mirror::PointerArray* method_array;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005160 if (super_interface) {
5161 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5162 DCHECK(if_table != nullptr);
5163 DCHECK(if_table->GetMethodArray(i) != nullptr);
5164 // If we are working on a super interface, try extending the existing method array.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005165 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005166 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005167 method_array = AllocPointerArray(self, num_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005168 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005169 if (UNLIKELY(method_array == nullptr)) {
5170 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005171 return false;
5172 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005173 iftable->SetMethodArray(i, method_array);
5174 }
5175 }
5176
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005177 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005178 "Copying ArtMethods for LinkInterfaceMethods");
5179 for (size_t i = 0; i < ifcount; ++i) {
5180 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
5181 if (num_methods > 0) {
5182 StackHandleScope<2> hs2(self);
5183 const bool is_super = i < super_ifcount;
5184 const bool super_interface = is_super && extend_super_iftable;
5185 auto method_array(hs2.NewHandle(iftable->GetMethodArray(i)));
5186
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005187 LengthPrefixedArray<ArtMethod>* input_virtual_methods = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005188 Handle<mirror::PointerArray> input_vtable_array = NullHandle<mirror::PointerArray>();
5189 int32_t input_array_length = 0;
5190 if (super_interface) {
5191 // We are overwriting a super class interface, try to only virtual methods instead of the
5192 // whole vtable.
5193 input_virtual_methods = klass->GetVirtualMethodsPtr();
5194 input_array_length = klass->NumVirtualMethods();
5195 } else {
5196 // A new interface, we need the whole vtable in case a new interface method is implemented
5197 // in the whole superclass.
5198 input_vtable_array = vtable;
5199 input_array_length = input_vtable_array->GetLength();
5200 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005201 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08005202 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005203 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005204 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005205 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07005206 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5207 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07005208 // For each method listed in the interface's method list, find the
5209 // matching method in our class's method list. We want to favor the
5210 // subclass over the superclass, which just requires walking
5211 // back from the end of the vtable. (This only matters if the
5212 // superclass defines a private method and this class redefines
5213 // it -- otherwise it would use the same vtable slot. In .dex files
5214 // those don't end up in the virtual method table, so it shouldn't
5215 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07005216 //
5217 // To find defaults we need to do the same but also go over interfaces.
5218 bool found_impl = false;
5219 ArtMethod* default_impl = nullptr;
5220 bool found_default_impl = false;
5221 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005222 ArtMethod* vtable_method = input_virtual_methods != nullptr ?
Vladimir Markocf36d492015-08-12 19:27:26 +01005223 &input_virtual_methods->At(k, method_size, method_alignment) :
Mathieu Chartiere401d142015-04-22 13:56:20 -07005224 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
5225 ArtMethod* vtable_method_for_name_comparison =
5226 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005227 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005228 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005229 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07005230 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
5231 // allocations.
5232 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005233 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07005234 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartiere401d142015-04-22 13:56:20 -07005235 PrettyMethod(vtable_method).c_str(), PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005236 return false;
Alex Lighteb7c1442015-08-31 13:17:42 -07005237 } else if (vtable_method->IsDefault()) {
5238 // We might have a newer, better, default method for this, so we just skip it. If we
5239 // are still using this we will select it again when scanning for default methods. To
5240 // obviate the need to copy the method again we will make a note that we already found
5241 // a default here.
5242 // TODO This should be much cleaner.
5243 found_default_impl = true;
5244 default_impl = vtable_method;
5245 break;
5246 } else {
5247 found_impl = true;
Ian Rogers9bc81912012-10-11 21:43:36 -07005248 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005249 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
Jeff Hao88474b42013-10-23 16:24:40 -07005250 // Place method in imt if entry is empty, place conflict otherwise.
Alex Lighteb7c1442015-08-31 13:17:42 -07005251 SetIMTRef(unimplemented_method,
5252 conflict_method,
5253 image_pointer_size_,
5254 vtable_method,
5255 /*out*/imt_ptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005256 break;
5257 }
5258 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005259 // We should only search for default implementations when the class does not implement the
5260 // method directly and either (1) the interface is newly implemented on this class and not
5261 // on any of its superclasses, (2) the superclass's implementation is a default method, or
5262 // (3) the superclass does not have an implementation.
5263 if (!found_impl && (!super_interface ||
5264 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_)
5265 ->IsOverridableByDefaultMethod())) {
5266 ArtMethod* current_method = nullptr;
5267 std::string icce_message;
5268 if (!FindDefaultMethodImplementation(self,
5269 interface_method,
5270 klass,
5271 /*out*/&current_method,
5272 /*out*/&icce_message)) {
5273 // There was a conflict with default method implementations.
5274 self->EndAssertNoThreadSuspension(old_cause);
5275 // TODO This should actually be thrown when we attempt to invoke this method.
5276 ThrowIncompatibleClassChangeError(klass.Get(), "%s", icce_message.c_str());
5277 return false;
5278 } else if (current_method != nullptr) {
5279 if (found_default_impl &&
5280 current_method->GetDeclaringClass() == default_impl->GetDeclaringClass()) {
5281 // We found a default method but it was the same one we already have from our
5282 // superclass. Don't bother adding it to our vtable again.
5283 current_method = default_impl;
5284 } else {
5285 // We found a default method implementation and there were no conflicts.
5286 // Save the default method. We need to add it to the vtable.
5287 default_methods.push_back(current_method);
5288 }
5289 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
5290 SetIMTRef(unimplemented_method,
5291 conflict_method,
5292 image_pointer_size_,
5293 current_method,
5294 /*out*/imt_ptr);
5295 found_impl = true;
5296 }
5297 }
5298 if (!found_impl && !super_interface) {
5299 // It is defined in this class or any of its subclasses.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005300 ArtMethod* miranda_method = nullptr;
5301 for (auto& mir_method : miranda_methods) {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005302 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005303 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005304 break;
5305 }
5306 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005307 if (miranda_method == nullptr) {
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005308 miranda_method = reinterpret_cast<ArtMethod*>(allocator.Alloc(method_size));
Mathieu Chartiere401d142015-04-22 13:56:20 -07005309 CHECK(miranda_method != nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07005310 // Point the interface table at a phantom slot.
Nicolas Geoffray22cf3d32015-11-02 11:57:11 +00005311 new(miranda_method) ArtMethod(interface_method, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005312 miranda_methods.push_back(miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005313 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005314 method_array->SetElementPtrSize(j, miranda_method, image_pointer_size_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005315 }
5316 }
5317 }
5318 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005319 if (!miranda_methods.empty() || !default_methods.empty()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005320 const size_t old_method_count = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07005321 const size_t new_method_count =
5322 old_method_count + miranda_methods.size() + default_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005323 // Attempt to realloc to save RAM if possible.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005324 LengthPrefixedArray<ArtMethod>* old_virtuals = klass->GetVirtualMethodsPtr();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005325 // The Realloced virtual methods aren't visiblef from the class roots, so there is no issue
5326 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
5327 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
5328 // CopyFrom has internal read barriers.
Vladimir Markocf36d492015-08-12 19:27:26 +01005329 const size_t old_size = old_virtuals != nullptr
5330 ? LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
5331 method_size,
5332 method_alignment)
5333 : 0u;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005334 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
Vladimir Markocf36d492015-08-12 19:27:26 +01005335 method_size,
5336 method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07005337 auto* virtuals = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
5338 runtime->GetLinearAlloc()->Realloc(self, old_virtuals, old_size, new_size));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005339 if (UNLIKELY(virtuals == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005340 self->AssertPendingOOMException();
Mathieu Chartier4e2cb092015-07-22 16:17:51 -07005341 self->EndAssertNoThreadSuspension(old_cause);
Ian Rogersa436fde2013-08-27 23:34:06 -07005342 return false;
5343 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005344 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table(allocator.Adapter());
5345 if (virtuals != old_virtuals) {
5346 // Maps from heap allocated miranda method to linear alloc miranda method.
Vladimir Marko35831e82015-09-11 11:59:18 +01005347 StrideIterator<ArtMethod> out = virtuals->begin(method_size, method_alignment);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005348 // Copy over the old methods + miranda methods.
5349 for (auto& m : klass->GetVirtualMethods(image_pointer_size_)) {
5350 move_table.emplace(&m, &*out);
5351 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
5352 // barriers when it copies.
5353 out->CopyFrom(&m, image_pointer_size_);
5354 ++out;
5355 }
5356 }
Vladimir Marko35831e82015-09-11 11:59:18 +01005357 StrideIterator<ArtMethod> out(virtuals->begin(method_size, method_alignment)
Alex Lighteb7c1442015-08-31 13:17:42 -07005358 + old_method_count);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005359 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
5360 // we want the roots of the miranda methods to get visited.
5361 for (ArtMethod* mir_method : miranda_methods) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005362 ArtMethod& new_method = *out;
5363 new_method.CopyFrom(mir_method, image_pointer_size_);
5364 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda);
5365 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
5366 << "Miranda method should be abstract!";
5367 move_table.emplace(mir_method, &new_method);
5368 ++out;
5369 }
5370 // We need to copy the default methods into our own virtual method table since the runtime
5371 // requires that every method on a class's vtable be in that respective class's virtual method
5372 // table.
5373 // NOTE This means that two classes might have the same implementation of a method from the same
5374 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
5375 // default method found on a class with one found on the declaring interface directly and must
5376 // look at the declaring class to determine if they are the same.
5377 for (ArtMethod* def_method : default_methods) {
5378 ArtMethod& new_method = *out;
5379 new_method.CopyFrom(def_method, image_pointer_size_);
5380 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccDefault);
5381 // Clear the preverified flag if it is present. Since this class hasn't been verified yet it
5382 // shouldn't have methods that are preverified.
5383 // TODO This is rather arbitrary. We should maybe support classes where only some of its
5384 // methods are preverified.
5385 new_method.SetAccessFlags(new_method.GetAccessFlags() & ~kAccPreverified);
5386 move_table.emplace(def_method, &new_method);
Mathieu Chartiercf3b1a32015-06-01 14:30:06 -07005387 ++out;
Mathieu Chartiercf3b1a32015-06-01 14:30:06 -07005388 }
Vladimir Marko35831e82015-09-11 11:59:18 +01005389 virtuals->SetSize(new_method_count);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005390 UpdateClassVirtualMethods(klass.Get(), virtuals);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005391 // 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 -07005392 // suspension assert.
5393 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005394
5395 const size_t old_vtable_count = vtable->GetLength();
Alex Lighteb7c1442015-08-31 13:17:42 -07005396 const size_t new_vtable_count =
5397 old_vtable_count + miranda_methods.size() + default_methods.size();
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005398 miranda_methods.clear();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005399 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, new_vtable_count)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005400 if (UNLIKELY(vtable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005401 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005402 return false;
5403 }
Vladimir Marko35831e82015-09-11 11:59:18 +01005404 out = virtuals->begin(method_size, method_alignment) + old_method_count;
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005405 size_t vtable_pos = old_vtable_count;
5406 for (size_t i = old_method_count; i < new_method_count; ++i) {
5407 // Leave the declaring class alone as type indices are relative to it
5408 out->SetMethodIndex(0xFFFF & vtable_pos);
5409 vtable->SetElementPtrSize(vtable_pos, &*out, image_pointer_size_);
5410 ++out;
5411 ++vtable_pos;
5412 }
5413 CHECK_EQ(vtable_pos, new_vtable_count);
Alex Lighteb7c1442015-08-31 13:17:42 -07005414 // Update old vtable methods. We use the default_translations map to figure out what each vtable
5415 // entry should be updated to, if they need to be at all.
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005416 for (size_t i = 0; i < old_vtable_count; ++i) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005417 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, image_pointer_size_);
5418 // Try and find what we need to change this method to.
5419 auto translation_it = default_translations.find(i);
5420 bool found_translation = false;
5421 if (translation_it != default_translations.end()) {
5422 size_t vtable_index;
5423 std::tie(vtable_index, translated_method) = *translation_it;
5424 DCHECK_EQ(vtable_index, i);
5425 found_translation = true;
5426 }
5427 DCHECK(translated_method != nullptr);
5428 auto it = move_table.find(translated_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005429 if (it != move_table.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005430 auto* new_method = it->second;
5431 DCHECK(new_method != nullptr);
5432 vtable->SetElementPtrSize(i, new_method, image_pointer_size_);
5433 } else {
5434 // If it was not going to be updated we wouldn't have put it into the default_translations
5435 // map.
5436 CHECK(!found_translation) << "We were asked to update this vtable entry. Must not fail.";
Mathieu Chartiere401d142015-04-22 13:56:20 -07005437 }
5438 }
Mathieu Chartiercf3b1a32015-06-01 14:30:06 -07005439
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005440 klass->SetVTable(vtable.Get());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005441 // Go fix up all the stale miranda pointers.
5442 for (size_t i = 0; i < ifcount; ++i) {
5443 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
5444 auto* method_array = iftable->GetMethodArray(i);
5445 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
5446 DCHECK(m != nullptr) << PrettyClass(klass.Get());
5447 auto it = move_table.find(m);
5448 if (it != move_table.end()) {
5449 auto* new_m = it->second;
5450 DCHECK(new_m != nullptr) << PrettyClass(klass.Get());
5451 method_array->SetElementPtrSize(j, new_m, image_pointer_size_);
5452 }
5453 }
5454 }
Mathieu Chartiera40c74a2015-06-02 09:56:04 -07005455 // Fix up IMT in case it has any miranda methods in it.
5456 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5457 auto it = move_table.find(out_imt[i]);
5458 if (it != move_table.end()) {
5459 out_imt[i] = it->second;
5460 }
5461 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005462 // Check that there are no stale methods are in the dex cache array.
5463 if (kIsDebugBuild) {
5464 auto* resolved_methods = klass->GetDexCache()->GetResolvedMethods();
Vladimir Marko05792b92015-08-03 11:56:49 +01005465 for (size_t i = 0, count = klass->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
5466 auto* m = mirror::DexCache::GetElementPtrSize(resolved_methods, i, image_pointer_size_);
Alex Lighteb7c1442015-08-31 13:17:42 -07005467 // We don't remove default methods from the move table since we need them to update the
5468 // vtable. Therefore just skip them for this check.
5469 if (!m->IsDefault()) {
5470 CHECK(move_table.find(m) == move_table.end()) << PrettyMethod(m);
5471 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005472 }
5473 }
5474 // Put some random garbage in old virtuals to help find stale pointers.
5475 if (virtuals != old_virtuals) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005476 memset(old_virtuals, 0xFEu, old_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005477 }
5478 } else {
5479 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005480 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005481 if (kIsDebugBuild) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005482 auto* check_vtable = klass->GetVTableDuringLinking();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005483 for (int i = 0; i < check_vtable->GetLength(); ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005484 CHECK(check_vtable->GetElementPtrSize<ArtMethod*>(i, image_pointer_size_) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005485 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005486 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005487 return true;
5488}
5489
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005490bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005491 CHECK(klass.Get() != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005492 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005493}
5494
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005495bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005496 CHECK(klass.Get() != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005497 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005498}
5499
Brian Carlstromdbc05252011-09-09 01:59:59 -07005500struct LinkFieldsComparator {
Mathieu Chartier90443472015-07-16 20:32:27 -07005501 explicit LinkFieldsComparator() SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005502 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005503 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005504 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005505 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005506 // 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 -07005507 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5508 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005509 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005510 if (type1 == Primitive::kPrimNot) {
5511 // Reference always goes first.
5512 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005513 }
Vladimir Markod5777482014-11-12 17:02:02 +00005514 if (type2 == Primitive::kPrimNot) {
5515 // Reference always goes first.
5516 return false;
5517 }
5518 size_t size1 = Primitive::ComponentSize(type1);
5519 size_t size2 = Primitive::ComponentSize(type2);
5520 if (size1 != size2) {
5521 // Larger primitive types go first.
5522 return size1 > size2;
5523 }
5524 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5525 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005526 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005527 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5528 // by name and for equal names by type id index.
5529 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5530 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005531 }
5532};
5533
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005534bool ClassLinker::LinkFields(Thread* self,
5535 Handle<mirror::Class> klass,
5536 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005537 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005538 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005539 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005540 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
5541 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005542
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005543 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005544 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005545 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005546 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005547 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005548 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005549 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005550 CHECK(super_class->IsResolved())
5551 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005552 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005553 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005554 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005555
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005556 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005557
Brian Carlstromdbc05252011-09-09 01:59:59 -07005558 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005559 // minimizes disruption of C++ version such as Class and Method.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005560 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005561 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005562 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005563 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005564 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005565 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005566 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5567 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005568
Fred Shih381e4ca2014-08-25 17:24:27 -07005569 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005570 size_t current_field = 0;
5571 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005572 FieldGaps gaps;
5573
Brian Carlstromdbc05252011-09-09 01:59:59 -07005574 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005575 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005576 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005577 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005578 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005579 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005580 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005581 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5582 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005583 MemberOffset old_offset = field_offset;
5584 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5585 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5586 }
Roland Levillain14d90572015-07-16 10:52:26 +01005587 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005588 grouped_and_sorted_fields.pop_front();
5589 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005590 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005591 field_offset = MemberOffset(field_offset.Uint32Value() +
5592 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005593 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005594 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5595 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005596 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5597 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5598 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5599 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005600 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5601 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005602 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005603
Elliott Hughesadb460d2011-10-05 17:02:34 -07005604 // 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 -07005605 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005606 // We know there are no non-reference fields in the Reference classes, and we know
5607 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005608 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005609 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
5610 << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005611 --num_reference_fields;
5612 }
5613
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005614 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005615 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005616 if (is_static) {
5617 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005618 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005619 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005620 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005621 mirror::Class* super_class = klass->GetSuperClass();
5622 if (num_reference_fields == 0 || super_class == nullptr) {
5623 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005624 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005625 if (super_class == nullptr ||
5626 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
5627 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005628 }
5629 }
5630 if (kIsDebugBuild) {
5631 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
5632 size_t total_reference_instance_fields = 0;
5633 mirror::Class* cur_super = klass.Get();
5634 while (cur_super != nullptr) {
5635 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
5636 cur_super = cur_super->GetSuperClass();
5637 }
5638 if (super_class == nullptr) {
5639 CHECK_EQ(total_reference_instance_fields, 1u) << PrettyDescriptor(klass.Get());
5640 } else {
5641 // Check that there is at least num_reference_fields other than Object.class.
5642 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
5643 << PrettyClass(klass.Get());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005644 }
5645 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005646 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005647 std::string temp;
5648 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5649 size_t previous_size = klass->GetObjectSize();
5650 if (previous_size != 0) {
5651 // Make sure that we didn't originally have an incorrect size.
5652 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005653 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005654 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005655 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005656 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005657
5658 if (kIsDebugBuild) {
5659 // Make sure that the fields array is ordered by name but all reference
5660 // offsets are at the beginning as far as alignment allows.
5661 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07005662 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00005663 : klass->GetFirstReferenceInstanceFieldOffset();
5664 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5665 num_reference_fields *
5666 sizeof(mirror::HeapReference<mirror::Object>));
5667 MemberOffset current_ref_offset = start_ref_offset;
5668 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005669 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005670 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
5671 << " class=" << PrettyClass(klass.Get()) << " field=" << PrettyField(field) << " offset="
Nicolas Geoffray555b3d02015-06-23 12:11:24 +01005672 << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005673 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005674 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005675 // NOTE: The field names can be the same. This is not possible in the Java language
5676 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005677 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005678 }
5679 Primitive::Type type = field->GetTypeAsPrimitiveType();
5680 bool is_primitive = type != Primitive::kPrimNot;
5681 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5682 strcmp("referent", field->GetName()) == 0) {
5683 is_primitive = true; // We lied above, so we have to expect a lie here.
5684 }
5685 MemberOffset offset = field->GetOffsetDuringLinking();
5686 if (is_primitive) {
5687 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5688 // Shuffled before references.
5689 size_t type_size = Primitive::ComponentSize(type);
5690 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5691 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5692 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5693 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5694 }
5695 } else {
5696 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5697 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5698 sizeof(mirror::HeapReference<mirror::Object>));
5699 }
5700 }
5701 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5702 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005703 return true;
5704}
5705
Vladimir Marko76649e82014-11-10 18:32:59 +00005706// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005707void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005708 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005709 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005710 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005711 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005712 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005713 // Compute reference offsets unless our superclass overflowed.
5714 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5715 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005716 if (num_reference_fields != 0u) {
5717 // All of the fields that contain object references are guaranteed be grouped in memory
5718 // starting at an appropriately aligned address after super class object data.
5719 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5720 sizeof(mirror::HeapReference<mirror::Object>));
5721 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005722 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005723 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005724 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005725 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005726 reference_offsets |= (0xffffffffu << start_bit) &
5727 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005728 }
5729 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005730 }
5731 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005732 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005733}
5734
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005735mirror::String* ClassLinker::ResolveString(const DexFile& dex_file,
5736 uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005737 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005738 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005739 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005740 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005741 return resolved;
5742 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005743 uint32_t utf16_length;
5744 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005745 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005746 dex_cache->SetResolvedString(string_idx, string);
5747 return string;
5748}
5749
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005750mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
5751 uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005752 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005753 StackHandleScope<2> hs(Thread::Current());
5754 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5755 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005756 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5757}
5758
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005759mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
5760 uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005761 Handle<mirror::DexCache> dex_cache,
5762 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005763 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005764 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005765 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005766 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005767 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005768 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005769 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005770 // TODO: we used to throw here if resolved's class loader was not the
5771 // boot class loader. This was to permit different classes with the
5772 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005773 dex_cache->SetResolvedType(type_idx, resolved);
5774 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005775 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005776 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005777 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005778 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005779 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08005780 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005781 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005782 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005783 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005784 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005785 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005786 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005787 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005788 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Mathieu Chartiere401d142015-04-22 13:56:20 -07005789 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005790 return resolved;
5791}
5792
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005793ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file,
5794 uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005795 Handle<mirror::DexCache> dex_cache,
5796 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005797 ArtMethod* referrer,
5798 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005799 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005800 // Check for hit in the dex cache.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005801 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005802 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005803 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005804 return resolved;
5805 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005806 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005807 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005808 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005809 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005810 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005811 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005812 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005813 // Scan using method_idx, this saves string compares but will only hit for matching dex
5814 // caches/files.
5815 switch (type) {
5816 case kDirect: // Fall-through.
5817 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005818 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
5819 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005820 break;
5821 case kInterface:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005822 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005823 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005824 break;
5825 case kSuper: // Fall-through.
5826 case kVirtual:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005827 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07005828 break;
5829 default:
5830 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005831 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005832 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005833 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005834 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005835 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005836 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005837 switch (type) {
5838 case kDirect: // Fall-through.
5839 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005840 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_);
5841 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005842 break;
5843 case kInterface:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005844 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005845 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005846 break;
5847 case kSuper: // Fall-through.
5848 case kVirtual:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005849 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07005850 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005851 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005852 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005853 // If we found a method, check for incompatible class changes.
5854 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005855 // Be a good citizen and update the dex cache to speed subsequent calls.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005856 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07005857 return resolved;
5858 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005859 // If we had a method, it's an incompatible-class-change error.
5860 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005861 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005862 } else {
5863 // We failed to find the method which means either an access error, an incompatible class
5864 // change, or no such method. First try to find the method among direct and virtual methods.
5865 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5866 const Signature signature = dex_file.GetMethodSignature(method_id);
5867 switch (type) {
5868 case kDirect:
5869 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005870 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005871 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5872 // have had a resolved method before, which triggers the "true" branch above.
5873 break;
5874 case kInterface:
5875 case kVirtual:
5876 case kSuper:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005877 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005878 break;
5879 }
5880
5881 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005882 bool exception_generated = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005883 if (resolved != nullptr && referrer != nullptr) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005884 mirror::Class* methods_class = resolved->GetDeclaringClass();
5885 mirror::Class* referring_class = referrer->GetDeclaringClass();
5886 if (!referring_class->CanAccess(methods_class)) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005887 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class,
5888 methods_class,
5889 resolved,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005890 type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005891 exception_generated = true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005892 } else if (!referring_class->CanAccessMember(methods_class, resolved->GetAccessFlags())) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005893 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005894 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005895 }
5896 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005897 if (!exception_generated) {
5898 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5899 // interface methods and throw if we find the method there. If we find nothing, throw a
5900 // NoSuchMethodError.
5901 switch (type) {
5902 case kDirect:
5903 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005904 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005905 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005906 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005907 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005908 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005909 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005910 } else {
5911 ThrowNoSuchMethodError(type, klass, name, signature);
5912 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005913 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005914 break;
5915 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005916 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005917 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005918 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005919 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005920 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005921 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005922 } else {
5923 ThrowNoSuchMethodError(type, klass, name, signature);
5924 }
5925 }
5926 break;
5927 case kSuper:
5928 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005929 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005930 } else {
5931 ThrowNoSuchMethodError(type, klass, name, signature);
5932 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005933 break;
5934 case kVirtual:
5935 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005936 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005937 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005938 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005939 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005940 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005941 } else {
5942 ThrowNoSuchMethodError(type, klass, name, signature);
5943 }
5944 }
5945 break;
5946 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005947 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005948 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005949 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005950 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005951 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005952}
5953
Jeff Hao13e748b2015-08-25 20:44:19 +00005954ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(const DexFile& dex_file,
5955 uint32_t method_idx,
5956 Handle<mirror::DexCache> dex_cache,
5957 Handle<mirror::ClassLoader> class_loader) {
5958 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
5959 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
5960 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
5961 return resolved;
5962 }
5963 // Fail, get the declaring class.
5964 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
5965 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
5966 if (klass == nullptr) {
5967 Thread::Current()->AssertPendingException();
5968 return nullptr;
5969 }
5970 if (klass->IsInterface()) {
5971 LOG(FATAL) << "ResolveAmbiguousMethod: unexpected method in interface: " << PrettyClass(klass);
5972 return nullptr;
5973 }
5974
5975 // Search both direct and virtual methods
5976 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
5977 if (resolved == nullptr) {
5978 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
5979 }
5980
5981 return resolved;
5982}
5983
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005984ArtField* ClassLinker::ResolveField(const DexFile& dex_file,
5985 uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07005986 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005987 Handle<mirror::ClassLoader> class_loader,
5988 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005989 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005990 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005991 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005992 return resolved;
5993 }
5994 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005995 Thread* const self = Thread::Current();
5996 StackHandleScope<1> hs(self);
5997 Handle<mirror::Class> klass(
5998 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005999 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08006000 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07006001 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07006002 }
6003
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07006004 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07006005 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07006006 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006007 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07006008 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08006009
Andreas Gampe58a5af82014-07-31 16:23:49 -07006010 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08006011 const char* name = dex_file.GetFieldName(field_id);
6012 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
6013 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07006014 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08006015 } else {
6016 resolved = klass->FindInstanceField(name, type);
6017 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07006018 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07006019 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006020 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08006021 }
Ian Rogersb067ac22011-12-13 18:05:09 -08006022 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07006023 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08006024 return resolved;
6025}
6026
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006027ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
6028 uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07006029 Handle<mirror::DexCache> dex_cache,
6030 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006031 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07006032 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07006033 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08006034 return resolved;
6035 }
6036 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07006037 Thread* self = Thread::Current();
6038 StackHandleScope<1> hs(self);
6039 Handle<mirror::Class> klass(
6040 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006041 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08006042 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006043 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08006044 }
6045
Ian Rogersdfb325e2013-10-30 01:00:44 -07006046 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
6047 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07006048 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07006049 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006050 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07006051 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08006052 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07006053 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07006054 }
6055 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07006056}
6057
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006058const char* ClassLinker::MethodShorty(uint32_t method_idx,
6059 ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08006060 uint32_t* length) {
6061 mirror::Class* declaring_class = referrer->GetDeclaringClass();
6062 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07006063 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07006064 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08006065 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07006066}
6067
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07006068class DumpClassVisitor : public ClassVisitor {
6069 public:
6070 explicit DumpClassVisitor(int flags) : flags_(flags) {}
6071
6072 bool Visit(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
6073 klass->DumpClass(LOG(ERROR), flags_);
6074 return true;
6075 }
6076
6077 private:
6078 const int flags_;
6079};
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07006080
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006081void ClassLinker::DumpAllClasses(int flags) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07006082 DumpClassVisitor visitor(flags);
6083 VisitClasses(&visitor);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07006084}
6085
Elliott Hughes956af0f2014-12-11 14:34:28 -08006086static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006087 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08006088 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
6089 base -= sizeof(void*); // Move backward so that code_offset != 0.
6090 const uint32_t code_offset = sizeof(void*);
6091 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006092}
6093
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006094bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
6095 return (entry_point == GetQuickResolutionStub()) ||
6096 (quick_resolution_trampoline_ == entry_point);
6097}
6098
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006099bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
6100 return (entry_point == GetQuickToInterpreterBridge()) ||
6101 (quick_to_interpreter_bridge_trampoline_ == entry_point);
6102}
6103
6104bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
6105 return (entry_point == GetQuickGenericJniStub()) ||
6106 (quick_generic_jni_trampoline_ == entry_point);
6107}
6108
6109const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
6110 return GetQuickGenericJniStub();
6111}
6112
Mathieu Chartiere401d142015-04-22 13:56:20 -07006113void ClassLinker::SetEntryPointsToCompiledCode(ArtMethod* method,
Elliott Hughes956af0f2014-12-11 14:34:28 -08006114 const void* method_code) const {
6115 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006116 oat_method.LinkMethod(method);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006117}
6118
Mathieu Chartiere401d142015-04-22 13:56:20 -07006119void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006120 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006121 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
6122 } else {
6123 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08006124 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006125 oat_method.LinkMethod(method);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006126 }
6127}
6128
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006129void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07006130 ScopedObjectAccess soa(Thread::Current());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006131 if (dex_cache_image_class_lookup_required_) {
6132 MoveImageClassesToClassTable();
6133 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07006134 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006135 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
6136 << NumNonZygoteClasses() << "\n";
6137}
6138
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006139class CountClassesVisitor : public ClassLoaderVisitor {
6140 public:
6141 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
6142
6143 void Visit(mirror::ClassLoader* class_loader)
6144 SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
6145 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07006146 if (class_table != nullptr) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006147 num_zygote_classes += class_table->NumZygoteClasses();
6148 num_non_zygote_classes += class_table->NumNonZygoteClasses();
Mathieu Chartier6b069532015-08-05 15:08:12 -07006149 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006150 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006151
6152 size_t num_zygote_classes;
6153 size_t num_non_zygote_classes;
6154};
6155
6156size_t ClassLinker::NumZygoteClasses() const {
6157 CountClassesVisitor visitor;
6158 VisitClassLoaders(&visitor);
6159 return visitor.num_zygote_classes + boot_class_table_.NumZygoteClasses();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006160}
6161
6162size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006163 CountClassesVisitor visitor;
6164 VisitClassLoaders(&visitor);
6165 return visitor.num_non_zygote_classes + boot_class_table_.NumNonZygoteClasses();
Elliott Hughescac6cc72011-11-03 20:31:21 -07006166}
6167
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006168size_t ClassLinker::NumLoadedClasses() {
6169 if (dex_cache_image_class_lookup_required_) {
6170 MoveImageClassesToClassTable();
6171 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07006172 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006173 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006174 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07006175}
6176
Brian Carlstrom47d237a2011-10-18 15:08:33 -07006177pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07006178 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07006179}
6180
6181pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07006182 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07006183}
6184
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08006185void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006186 DCHECK(!init_done_);
6187
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006188 DCHECK(klass != nullptr);
6189 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006190
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07006191 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006192 DCHECK(class_roots != nullptr);
6193 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07006194 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006195}
6196
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006197const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
6198 static const char* class_roots_descriptors[] = {
6199 "Ljava/lang/Class;",
6200 "Ljava/lang/Object;",
6201 "[Ljava/lang/Class;",
6202 "[Ljava/lang/Object;",
6203 "Ljava/lang/String;",
6204 "Ljava/lang/DexCache;",
6205 "Ljava/lang/ref/Reference;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07006206 "Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07006207 "Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07006208 "Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006209 "Ljava/lang/reflect/Proxy;",
6210 "[Ljava/lang/String;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07006211 "[Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07006212 "[Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07006213 "[Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006214 "Ljava/lang/ClassLoader;",
6215 "Ljava/lang/Throwable;",
6216 "Ljava/lang/ClassNotFoundException;",
6217 "Ljava/lang/StackTraceElement;",
6218 "Z",
6219 "B",
6220 "C",
6221 "D",
6222 "F",
6223 "I",
6224 "J",
6225 "S",
6226 "V",
6227 "[Z",
6228 "[B",
6229 "[C",
6230 "[D",
6231 "[F",
6232 "[I",
6233 "[J",
6234 "[S",
6235 "[Ljava/lang/StackTraceElement;",
6236 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08006237 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
6238 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006239
6240 const char* descriptor = class_roots_descriptors[class_root];
6241 CHECK(descriptor != nullptr);
6242 return descriptor;
6243}
6244
Mathieu Chartiere401d142015-04-22 13:56:20 -07006245bool ClassLinker::MayBeCalledWithDirectCodePointer(ArtMethod* m) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07006246 Runtime* const runtime = Runtime::Current();
6247 if (runtime->UseJit()) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07006248 // JIT can have direct code pointers from any method to any other method.
6249 return true;
6250 }
Sebastien Hertz6963e442014-11-26 22:11:27 +01006251 // Non-image methods don't use direct code pointer.
6252 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
6253 return false;
6254 }
6255 if (m->IsPrivate()) {
6256 // The method can only be called inside its own oat file. Therefore it won't be called using
6257 // its direct code if the oat file has been compiled in PIC mode.
Sebastien Hertz6963e442014-11-26 22:11:27 +01006258 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
Richard Uhler07b3c232015-03-31 15:57:54 -07006259 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Sebastien Hertz6963e442014-11-26 22:11:27 +01006260 if (oat_dex_file == nullptr) {
6261 // No oat file: the method has not been compiled.
6262 return false;
6263 }
6264 const OatFile* oat_file = oat_dex_file->GetOatFile();
6265 return oat_file != nullptr && !oat_file->IsPic();
6266 } else {
6267 // The method can be called outside its own oat file. Therefore it won't be called using its
6268 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07006269 return runtime->GetOatFileManager().HaveNonPicOatFile();
Sebastien Hertz6963e442014-11-26 22:11:27 +01006270 }
6271}
6272
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006273jobject ClassLinker::CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006274 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
6275 // We could move the jobject to the callers, but all call-sites do this...
6276 ScopedObjectAccessUnchecked soa(self);
6277
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006278 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Mathieu Chartierc7853442015-03-27 14:35:38 -07006279 StackHandleScope<10> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006280
Mathieu Chartierc7853442015-03-27 14:35:38 -07006281 ArtField* dex_elements_field =
6282 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006283
Mathieu Chartierc7853442015-03-27 14:35:38 -07006284 mirror::Class* dex_elements_class = dex_elements_field->GetType<true>();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006285 DCHECK(dex_elements_class != nullptr);
6286 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07006287 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
6288 mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006289 Handle<mirror::Class> h_dex_element_class =
6290 hs.NewHandle(dex_elements_class->GetComponentType());
6291
Mathieu Chartierc7853442015-03-27 14:35:38 -07006292 ArtField* element_file_field =
6293 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
6294 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006295
Mathieu Chartierc7853442015-03-27 14:35:38 -07006296 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
6297 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006298
6299 // Fill the elements array.
6300 int32_t index = 0;
6301 for (const DexFile* dex_file : dex_files) {
6302 StackHandleScope<3> hs2(self);
6303
Mathieu Chartiere58991b2015-10-13 07:59:34 -07006304 // CreatePathClassLoader is only used by gtests. Index 0 of h_long_array is supposed to be the
6305 // oat file but we can leave it null.
6306 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
6307 self,
6308 kDexFileIndexStart + 1));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006309 DCHECK(h_long_array.Get() != nullptr);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07006310 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006311
6312 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07006313 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006314 DCHECK(h_dex_file.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07006315 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006316
6317 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
6318 DCHECK(h_element.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07006319 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006320
6321 h_dex_elements->Set(index, h_element.Get());
6322 index++;
6323 }
6324 DCHECK_EQ(index, h_dex_elements->GetLength());
6325
6326 // Create DexPathList.
6327 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07006328 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006329 DCHECK(h_dex_path_list.Get() != nullptr);
6330 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07006331 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006332
6333 // Create PathClassLoader.
6334 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
6335 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
6336 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
6337 h_path_class_class->AllocObject(self));
6338 DCHECK(h_path_class_loader.Get() != nullptr);
6339 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07006340 ArtField* path_list_field =
6341 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList);
6342 DCHECK(path_list_field != nullptr);
6343 path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006344
6345 // Make a pretend boot-classpath.
6346 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07006347 ArtField* const parent_field =
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006348 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07006349 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01006350 DCHECK(parent_field != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006351 mirror::Object* boot_cl =
6352 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07006353 parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006354
6355 // Make it a global ref and return.
6356 ScopedLocalRef<jobject> local_ref(
6357 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
6358 return soa.Env()->NewGlobalRef(local_ref.get());
6359}
6360
Mathieu Chartiere401d142015-04-22 13:56:20 -07006361ArtMethod* ClassLinker::CreateRuntimeMethod() {
Vladimir Marko14632852015-08-17 12:07:23 +01006362 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
6363 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006364 LengthPrefixedArray<ArtMethod>* method_array = AllocArtMethodArray(
6365 Thread::Current(),
6366 Runtime::Current()->GetLinearAlloc(),
6367 1);
Vladimir Markocf36d492015-08-12 19:27:26 +01006368 ArtMethod* method = &method_array->At(0, method_size, method_alignment);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006369 CHECK(method != nullptr);
6370 method->SetDexMethodIndex(DexFile::kDexNoIndex);
6371 CHECK(method->IsRuntimeMethod());
6372 return method;
6373}
6374
Andreas Gampe8ac75952015-06-02 21:01:45 -07006375void ClassLinker::DropFindArrayClassCache() {
6376 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
6377 find_array_class_cache_next_victim_ = 0;
6378}
6379
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006380void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006381 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006382 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07006383 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
6384 auto* const class_loader = down_cast<mirror::ClassLoader*>(self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006385 if (class_loader != nullptr) {
6386 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006387 }
6388 }
6389}
6390
Mathieu Chartier00310e02015-10-17 12:46:42 -07006391void ClassLinker::InsertDexFileInToClassLoader(mirror::Object* dex_file,
6392 mirror::ClassLoader* class_loader) {
6393 DCHECK(dex_file != nullptr);
6394 DCHECK(class_loader != nullptr);
6395 Thread* const self = Thread::Current();
6396 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
6397 ClassTable* const table = class_loader->GetClassTable();
6398 DCHECK(table != nullptr);
6399 if (table->InsertDexFile(dex_file)) {
6400 // It was not already inserted, perform the write barrier to let the GC know the class loader's
6401 // class table was modified.
6402 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
6403 }
6404}
6405
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006406void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006407 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006408 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006409 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
6410 const ClassLoaderData& data = *it;
Mathieu Chartier4843bd52015-10-01 17:08:44 -07006411 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
6412 auto* const class_loader = down_cast<mirror::ClassLoader*>(self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006413 if (class_loader != nullptr) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006414 ++it;
6415 } else {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01006416 DeleteClassLoader(self, data);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006417 it = class_loaders_.erase(it);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006418 }
6419 }
6420}
6421
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006422} // namespace art