blob: d6d6448f7a9519beb0d15b6cec83e0b86a4e921b [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
Mathieu Chartier90443472015-07-16 20:32:27 -0700107bool ClassLinker::HasInitWithString(Thread* self, const char* descriptor) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700108 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700109 StackHandleScope<1> hs(self);
110 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700111 method->GetDeclaringClass()->GetClassLoader() : nullptr));
112 mirror::Class* exception_class = FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700113
114 if (exception_class == nullptr) {
115 // No exc class ~ no <init>-with-string.
116 CHECK(self->IsExceptionPending());
117 self->ClearException();
118 return false;
119 }
120
Mathieu Chartiere401d142015-04-22 13:56:20 -0700121 ArtMethod* exception_init_method = exception_class->FindDeclaredDirectMethod(
122 "<init>", "(Ljava/lang/String;)V", image_pointer_size_);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700123 return exception_init_method != nullptr;
124}
125
126void ClassLinker::ThrowEarlierClassFailure(mirror::Class* c) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700127 // The class failed to initialize on a previous attempt, so we want to throw
128 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
129 // failed in verification, in which case v2 5.4.1 says we need to re-throw
130 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800131 Runtime* const runtime = Runtime::Current();
132 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700133 std::string extra;
134 if (c->GetVerifyErrorClass() != nullptr) {
135 extra = PrettyDescriptor(c->GetVerifyErrorClass());
136 }
137 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c) << ": " << extra;
Ian Rogers87e552d2012-08-31 15:54:48 -0700138 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700139
Elliott Hughes5c599942012-06-13 16:45:05 -0700140 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800141 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800142 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700143 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
144 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000145 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700146 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700147 if (c->GetVerifyErrorClass() != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700148 // TODO: change the verifier to store an _instance_, with a useful detail message?
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700149 // It's possible the exception doesn't have a <init>(String).
Ian Rogers7b078e82014-09-10 14:44:24 -0700150 std::string temp;
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700151 const char* descriptor = c->GetVerifyErrorClass()->GetDescriptor(&temp);
152
Mathieu Chartier90443472015-07-16 20:32:27 -0700153 if (HasInitWithString(self, descriptor)) {
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700154 self->ThrowNewException(descriptor, PrettyDescriptor(c).c_str());
155 } else {
156 self->ThrowNewException(descriptor, nullptr);
157 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700158 } else {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000159 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
Ian Rogers7b078e82014-09-10 14:44:24 -0700160 PrettyDescriptor(c).c_str());
161 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700162 }
163}
164
Brian Carlstromb23eab12014-10-08 17:55:21 -0700165static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Mathieu Chartier90443472015-07-16 20:32:27 -0700166 SHARED_REQUIRES(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700167 if (VLOG_IS_ON(class_linker)) {
168 std::string temp;
169 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000170 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700171 }
172}
173
174static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Mathieu Chartier90443472015-07-16 20:32:27 -0700175 SHARED_REQUIRES(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700176 Thread* self = Thread::Current();
177 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700178
179 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700180 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700181
182 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700183 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
184 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700185
Elliott Hughesa4f94742012-05-29 16:28:38 -0700186 // We only wrap non-Error exceptions; an Error can just be used as-is.
187 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000188 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700189 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700190 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700191}
192
Fred Shih381e4ca2014-08-25 17:24:27 -0700193// Gap between two fields in object layout.
194struct FieldGap {
195 uint32_t start_offset; // The offset from the start of the object.
196 uint32_t size; // The gap size of 1, 2, or 4 bytes.
197};
198struct FieldGapsComparator {
199 explicit FieldGapsComparator() {
200 }
201 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
202 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800203 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700204 // Note that the priority queue returns the largest element, so operator()
205 // should return true if lhs is less than rhs.
206 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700207 }
208};
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700209typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
Fred Shih381e4ca2014-08-25 17:24:27 -0700210
211// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800212static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700213 DCHECK(gaps != nullptr);
214
215 uint32_t current_offset = gap_start;
216 while (current_offset != gap_end) {
217 size_t remaining = gap_end - current_offset;
218 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
219 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
220 current_offset += sizeof(uint32_t);
221 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
222 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
223 current_offset += sizeof(uint16_t);
224 } else {
225 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
226 current_offset += sizeof(uint8_t);
227 }
228 DCHECK_LE(current_offset, gap_end) << "Overran gap";
229 }
230}
231// Shuffle fields forward, making use of gaps whenever possible.
232template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000233static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700234 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700235 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700236 FieldGaps* gaps)
Mathieu Chartier90443472015-07-16 20:32:27 -0700237 SHARED_REQUIRES(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700238 DCHECK(current_field_idx != nullptr);
239 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700240 DCHECK(gaps != nullptr);
241 DCHECK(field_offset != nullptr);
242
243 DCHECK(IsPowerOfTwo(n));
244 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700245 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700246 Primitive::Type type = field->GetTypeAsPrimitiveType();
247 if (Primitive::ComponentSize(type) < n) {
248 break;
249 }
250 if (!IsAligned<n>(field_offset->Uint32Value())) {
251 MemberOffset old_offset = *field_offset;
252 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
253 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
254 }
255 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
256 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700257 if (!gaps->empty() && gaps->top().size >= n) {
258 FieldGap gap = gaps->top();
259 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100260 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700261 field->SetOffset(MemberOffset(gap.start_offset));
262 if (gap.size > n) {
263 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
264 }
265 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100266 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700267 field->SetOffset(*field_offset);
268 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
269 }
270 ++(*current_field_idx);
271 }
272}
273
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800274ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700275 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700276 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700277 dex_cache_image_class_lookup_required_(false),
278 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800279 class_roots_(nullptr),
280 array_iftable_(nullptr),
281 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700282 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800283 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700284 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800285 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800286 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100287 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800288 quick_to_interpreter_bridge_trampoline_(nullptr),
289 image_pointer_size_(sizeof(void*)) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700290 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700291 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
292 "Array cache size wrong.");
293 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700294}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700295
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800296void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800297 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700298
Mathieu Chartiere401d142015-04-22 13:56:20 -0700299 Thread* const self = Thread::Current();
300 Runtime* const runtime = Runtime::Current();
301 gc::Heap* const heap = runtime->GetHeap();
302
303 CHECK(!heap->HasImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700304 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700305
Mathieu Chartiere401d142015-04-22 13:56:20 -0700306 // Use the pointer size from the runtime since we are probably creating the image.
307 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
308
Elliott Hughes30646832011-10-13 16:59:46 -0700309 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700310 // 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 -0800311 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700312 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700313 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700314 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700315 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700316 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700317 mirror::Class::SetClassClass(java_lang_Class.Get());
318 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700319 if (kUseBakerOrBrooksReadBarrier) {
320 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800321 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700322 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700323 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800324 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800325 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700326
Elliott Hughes418d20f2011-09-22 14:00:39 -0700327 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700328 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700329 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700330 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700331 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700332
Ian Rogers23435d02012-09-24 11:23:12 -0700333 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700334 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700335 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700336 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700337 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700338 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700339 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700340
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700341 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
342 runtime->SetSentinel(heap->AllocObject<true>(self,
343 java_lang_Object.Get(),
344 java_lang_Object->GetObjectSize(),
345 VoidFunctor()));
346
Ian Rogers23435d02012-09-24 11:23:12 -0700347 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700348 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700349 AllocClass(self, java_lang_Class.Get(),
350 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700351 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700352
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700353 // Setup the char (primitive) class to be used for char[].
354 Handle<mirror::Class> char_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700355 AllocClass(self, java_lang_Class.Get(),
356 mirror::Class::PrimitiveClassSize(image_pointer_size_))));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700357 // The primitive char class won't be initialized by
358 // InitializePrimitiveClass until line 459, but strings (and
359 // internal char arrays) will be allocated before that and the
360 // component size, which is computed from the primitive type, needs
361 // to be set here.
362 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700363
Ian Rogers23435d02012-09-24 11:23:12 -0700364 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700365 Handle<mirror::Class> char_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700366 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700367 char_array_class->SetComponentType(char_class.Get());
368 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700369
Ian Rogers23435d02012-09-24 11:23:12 -0700370 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700371 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700372 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700373 java_lang_String->SetStringClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700374 mirror::String::SetClass(java_lang_String.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700375 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400376
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700377 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700378 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700379 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700380 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
381 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700382 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700383
Ian Rogers23435d02012-09-24 11:23:12 -0700384 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700385 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700386 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
387 kClassRootsMax));
388 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700389 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
390 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
391 SetClassRoot(kClassArrayClass, class_array_class.Get());
392 SetClassRoot(kObjectArrayClass, object_array_class.Get());
393 SetClassRoot(kCharArrayClass, char_array_class.Get());
394 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700395 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700396
397 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700398 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
399 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
400 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
401 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
402 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
403 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
404 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
405 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700406
Ian Rogers23435d02012-09-24 11:23:12 -0700407 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700408 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700409
Ian Rogers23435d02012-09-24 11:23:12 -0700410 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700411 Handle<mirror::Class> int_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700412 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700414 mirror::IntArray::SetArrayClass(int_array_class.Get());
415 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700416
Mathieu Chartierc7853442015-03-27 14:35:38 -0700417 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
418 Handle<mirror::Class> long_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700419 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700420 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
421 mirror::LongArray::SetArrayClass(long_array_class.Get());
422 SetClassRoot(kLongArrayClass, long_array_class.Get());
423
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700424 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700425
Ian Rogers52813c92012-10-11 11:50:38 -0700426 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700427 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700428 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700429 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100430 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700431 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700432 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700433
Mathieu Chartier66f19252012-09-18 08:57:04 -0700434 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700435 Handle<mirror::Class> object_array_string(hs.NewHandle(
436 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700437 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700438 object_array_string->SetComponentType(java_lang_String.Get());
439 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700440
Mathieu Chartiere401d142015-04-22 13:56:20 -0700441 // Create runtime resolution and imt conflict methods.
442 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
443 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
444 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700445
Ian Rogers23435d02012-09-24 11:23:12 -0700446 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
447 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
448 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700449 CHECK_NE(0U, boot_class_path.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800450 for (auto& dex_file : boot_class_path) {
451 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700452 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800453 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700454 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455
456 // now we can use FindSystemClass
457
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700458 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700459 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
460 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700461
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700462 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
463 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700464 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800465 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700466 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700467 quick_resolution_trampoline_ = GetQuickResolutionStub();
468 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
469 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700470 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700471
Mathieu Chartier66f19252012-09-18 08:57:04 -0700472 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700473 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700474 CHECK_EQ(java_lang_Object.Get(), FindSystemClass(self, "Ljava/lang/Object;"));
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700475 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700476 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800477 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700478 if (java_lang_String.Get() != String_class) {
479 std::ostringstream os1, os2;
480 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
481 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
482 LOG(FATAL) << os1.str() << "\n\n" << os2.str();
483 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700484 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700485 CHECK_EQ(java_lang_DexCache.Get(), FindSystemClass(self, "Ljava/lang/DexCache;"));
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700486 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700487
Ian Rogers23435d02012-09-24 11:23:12 -0700488 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800489 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800490 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700491
Ian Rogers98379392014-02-24 16:53:16 -0800492 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800493 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700494
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700495 CHECK_EQ(char_array_class.Get(), FindSystemClass(self, "[C"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700496
Ian Rogers98379392014-02-24 16:53:16 -0800497 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800498 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700499
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700500 CHECK_EQ(int_array_class.Get(), FindSystemClass(self, "[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700501
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700502 CHECK_EQ(long_array_class.Get(), FindSystemClass(self, "[J"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700503
Ian Rogers98379392014-02-24 16:53:16 -0800504 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800505 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700506
Ian Rogers98379392014-02-24 16:53:16 -0800507 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800508 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700509
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700510 CHECK_EQ(class_array_class.Get(), FindSystemClass(self, "[Ljava/lang/Class;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700511
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700512 CHECK_EQ(object_array_class.Get(), FindSystemClass(self, "[Ljava/lang/Object;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700513
Ian Rogers23435d02012-09-24 11:23:12 -0700514 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700515 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
516 CHECK(java_lang_Cloneable.Get() != nullptr);
517 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
518 CHECK(java_io_Serializable.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700519 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
520 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700521 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
522 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700523
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700524 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
525 // suspension.
526 CHECK_EQ(java_lang_Cloneable.Get(),
527 mirror::Class::GetDirectInterface(self, class_array_class, 0));
528 CHECK_EQ(java_io_Serializable.Get(),
529 mirror::Class::GetDirectInterface(self, class_array_class, 1));
530 CHECK_EQ(java_lang_Cloneable.Get(),
531 mirror::Class::GetDirectInterface(self, object_array_class, 0));
532 CHECK_EQ(java_io_Serializable.Get(),
533 mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700534 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700535 // dex_cache_ fields and register them in class_table_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700536 CHECK_EQ(java_lang_Class.Get(), FindSystemClass(self, "Ljava/lang/Class;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700537
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700538 CHECK_EQ(object_array_string.Get(),
539 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700540
Ian Rogers23435d02012-09-24 11:23:12 -0700541 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700542
Ian Rogers23435d02012-09-24 11:23:12 -0700543 // Create java.lang.reflect.Proxy root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700544 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700545
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700546 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700547 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
548 CHECK(class_root != nullptr);
549 SetClassRoot(kJavaLangReflectField, class_root);
550 mirror::Field::SetClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700551
552 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700553 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
554 CHECK(class_root != nullptr);
555 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
556 mirror::Field::SetArrayClass(class_root);
557
558 // Create java.lang.reflect.Constructor.class root and array root.
559 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
560 CHECK(class_root != nullptr);
561 SetClassRoot(kJavaLangReflectConstructor, class_root);
562 mirror::Constructor::SetClass(class_root);
563 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
564 CHECK(class_root != nullptr);
565 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
566 mirror::Constructor::SetArrayClass(class_root);
567
568 // Create java.lang.reflect.Method.class root and array root.
569 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
570 CHECK(class_root != nullptr);
571 SetClassRoot(kJavaLangReflectMethod, class_root);
572 mirror::Method::SetClass(class_root);
573 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
574 CHECK(class_root != nullptr);
575 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
576 mirror::Method::SetArrayClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700577
Brian Carlstrom1f870082011-08-23 16:02:11 -0700578 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700579 // finish initializing Reference class
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700580 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700581 CHECK_EQ(java_lang_ref_Reference.Get(), FindSystemClass(self, "Ljava/lang/ref/Reference;"));
Fred Shih4ee7a662014-07-11 09:59:27 -0700582 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700583 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
584 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700585 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700586 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700587 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700588 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700589 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700590 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700591 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700592 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700593 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700594 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700595 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700596 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700597
Ian Rogers23435d02012-09-24 11:23:12 -0700598 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700599 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700600 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700601 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
602 SetClassRoot(kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700603
jeffhao8cd6dda2012-02-22 10:15:34 -0800604 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700605 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800606 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800607 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700608 SetClassRoot(kJavaLangClassNotFoundException,
609 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800610 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700611 SetClassRoot(kJavaLangStackTraceElementArrayClass,
612 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800613 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700614
Andreas Gampe76bd8802014-12-10 16:43:58 -0800615 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
616 // initialized.
617 {
618 const DexFile& dex_file = java_lang_Object->GetDexFile();
619 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
620 CHECK(void_string_id != nullptr);
621 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
622 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
623 CHECK(void_type_id != nullptr);
624 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
625 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
626 // as referrer so the used dex cache is core's one.
627 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
628 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
629 self->AssertNoPendingException();
630 }
631
Ian Rogers98379392014-02-24 16:53:16 -0800632 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700633
Brian Carlstroma004aa92012-02-08 18:05:09 -0800634 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700635}
636
Ian Rogers98379392014-02-24 16:53:16 -0800637void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800638 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700639
640 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700641 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700642 // as the types of the field can't be resolved prior to the runtime being
643 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800644 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700645 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800646 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800647
Mathieu Chartierc7853442015-03-27 14:35:38 -0700648 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700649 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
650 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700651
Mathieu Chartierc7853442015-03-27 14:35:38 -0700652 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700653 CHECK_STREQ(queue->GetName(), "queue");
654 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700655
Mathieu Chartierc7853442015-03-27 14:35:38 -0700656 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700657 CHECK_STREQ(queueNext->GetName(), "queueNext");
658 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700659
Mathieu Chartierc7853442015-03-27 14:35:38 -0700660 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700661 CHECK_STREQ(referent->GetName(), "referent");
662 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700663
Mathieu Chartierc7853442015-03-27 14:35:38 -0700664 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700665 CHECK_STREQ(zombie->GetName(), "zombie");
666 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700667
Brian Carlstroma663ea52011-08-19 23:33:41 -0700668 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700669 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700670 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800671 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700672 CHECK(klass != nullptr);
673 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700674 // note SetClassRoot does additional validation.
675 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700676 }
677
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700678 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700679
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700680 // disable the slow paths in FindClass and CreatePrimitiveClass now
681 // that Object, Class, and Object[] are setup
682 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700683
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800684 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700685}
686
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700687void ClassLinker::RunRootClinits() {
688 Thread* self = Thread::Current();
689 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800690 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700691 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700692 StackHandleScope<1> hs(self);
693 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700694 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700695 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700696 }
697 }
698}
699
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -0700700static void SanityCheckArtMethod(ArtMethod* m,
701 mirror::Class* expected_class,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700702 gc::space::ImageSpace* space)
Mathieu Chartier90443472015-07-16 20:32:27 -0700703 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700704 if (m->IsRuntimeMethod()) {
705 CHECK(m->GetDeclaringClass() == nullptr) << PrettyMethod(m);
706 } else if (m->IsMiranda()) {
707 CHECK(m->GetDeclaringClass() != nullptr) << PrettyMethod(m);
708 } else if (expected_class != nullptr) {
709 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << PrettyMethod(m);
710 }
711 if (space != nullptr) {
712 auto& header = space->GetImageHeader();
713 auto& methods = header.GetMethodsSection();
714 auto offset = reinterpret_cast<uint8_t*>(m) - space->Begin();
715 CHECK(methods.Contains(offset)) << m << " not in " << methods;
716 }
717}
718
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -0700719static void SanityCheckArtMethodPointerArray(mirror::PointerArray* arr,
720 mirror::Class* expected_class,
721 size_t pointer_size,
722 gc::space::ImageSpace* space)
723 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700724 CHECK(arr != nullptr);
725 for (int32_t j = 0; j < arr->GetLength(); ++j) {
726 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size);
727 // expected_class == null means we are a dex cache.
728 if (expected_class != nullptr) {
729 CHECK(method != nullptr);
730 }
731 if (method != nullptr) {
732 SanityCheckArtMethod(method, expected_class, space);
Ian Rogers848871b2013-08-05 10:56:33 -0700733 }
734 }
735}
736
Vladimir Marko05792b92015-08-03 11:56:49 +0100737static void SanityCheckArtMethodPointerArray(
738 ArtMethod** arr,
739 size_t size,
740 size_t pointer_size,
741 gc::space::ImageSpace* space) SHARED_REQUIRES(Locks::mutator_lock_) {
742 CHECK_EQ(arr != nullptr, size != 0u);
743 if (arr != nullptr) {
744 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
745 CHECK(space->GetImageHeader().GetImageSection(
746 ImageHeader::kSectionDexCacheArrays).Contains(offset));
747 }
748 for (size_t j = 0; j < size; ++j) {
749 ArtMethod* method = mirror::DexCache::GetElementPtrSize(arr, j, pointer_size);
750 // expected_class == null means we are a dex cache.
751 if (method != nullptr) {
752 SanityCheckArtMethod(method, nullptr, space);
753 }
754 }
755}
756
Mathieu Chartiere401d142015-04-22 13:56:20 -0700757static void SanityCheckObjectsCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700758 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700759 DCHECK(obj != nullptr);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700760 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700761 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
762 if (obj->IsClass()) {
763 auto klass = obj->AsClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700764 for (ArtField& field : klass->GetIFields()) {
765 CHECK_EQ(field.GetDeclaringClass(), klass);
766 }
767 for (ArtField& field : klass->GetSFields()) {
768 CHECK_EQ(field.GetDeclaringClass(), klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700769 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700770 auto* runtime = Runtime::Current();
771 auto* image_space = runtime->GetHeap()->GetImageSpace();
772 auto pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
773 for (auto& m : klass->GetDirectMethods(pointer_size)) {
774 SanityCheckArtMethod(&m, klass, image_space);
775 }
776 for (auto& m : klass->GetVirtualMethods(pointer_size)) {
777 SanityCheckArtMethod(&m, klass, image_space);
778 }
779 auto* vtable = klass->GetVTable();
780 if (vtable != nullptr) {
781 SanityCheckArtMethodPointerArray(vtable, nullptr, pointer_size, image_space);
782 }
783 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
784 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
785 SanityCheckArtMethod(klass->GetEmbeddedImTableEntry(i, pointer_size), nullptr, image_space);
786 }
787 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
788 SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr, image_space);
789 }
790 }
791 auto* iftable = klass->GetIfTable();
792 if (iftable != nullptr) {
793 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
794 if (iftable->GetMethodArrayCount(i) > 0) {
795 SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr, pointer_size,
796 image_space);
797 }
798 }
799 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700800 }
801}
802
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200803// Set image methods' entry point to interpreter.
804class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
805 public:
806 explicit SetInterpreterEntrypointArtMethodVisitor(size_t image_pointer_size)
807 : image_pointer_size_(image_pointer_size) {}
808
809 void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
810 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
811 CHECK(method->GetDeclaringClass() != nullptr);
812 }
813 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
814 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
815 image_pointer_size_);
816 }
817 }
818
819 private:
820 const size_t image_pointer_size_;
821
822 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
823};
824
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700825void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800826 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700827 CHECK(!init_done_);
828
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700829 Runtime* const runtime = Runtime::Current();
830 Thread* const self = Thread::Current();
831 gc::Heap* const heap = runtime->GetHeap();
832 gc::space::ImageSpace* const space = heap->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700833 CHECK(space != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700834 image_pointer_size_ = space->GetImageHeader().GetPointerSize();
835 dex_cache_image_class_lookup_required_ = true;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700836 const OatFile* oat_file = runtime->GetOatFileManager().RegisterImageOatFile(space);
837 DCHECK(oat_file != nullptr);
838 CHECK_EQ(oat_file->GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
839 CHECK_EQ(oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
840 const char* image_file_location = oat_file->GetOatHeader().
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700841 GetStoreValueByKey(OatHeader::kImageLocationKey);
842 CHECK(image_file_location == nullptr || *image_file_location == 0);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700843 quick_resolution_trampoline_ = oat_file->GetOatHeader().GetQuickResolutionTrampoline();
844 quick_imt_conflict_trampoline_ = oat_file->GetOatHeader().GetQuickImtConflictTrampoline();
845 quick_generic_jni_trampoline_ = oat_file->GetOatHeader().GetQuickGenericJniTrampoline();
846 quick_to_interpreter_bridge_trampoline_ = oat_file->GetOatHeader().GetQuickToInterpreterBridge();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700847 StackHandleScope<2> hs(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800848 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700849 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
850 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700851
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700852 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
853 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
854 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700855 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700856
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700857 // Special case of setting up the String class early so that we can test arbitrary objects
858 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700859 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800860
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700861 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
862 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
863 Runtime::Current()->SetSentinel(Runtime::Current()->GetHeap()->AllocObject<true>(self,
864 java_lang_Object,
865 java_lang_Object->GetObjectSize(),
866 VoidFunctor()));
867
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700868 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700869 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700870 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800871 StackHandleScope<1> hs2(self);
872 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700873 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700874 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location.c_str(),
875 nullptr);
876 CHECK(oat_dex_file != nullptr) << oat_file->GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700877 std::string error_msg;
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700878 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700879 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700880 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700881 << " from within oat file " << oat_file->GetLocation()
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700882 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -0800883 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700884 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700885
Mathieu Chartiere401d142015-04-22 13:56:20 -0700886 if (kSanityCheckObjects) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100887 SanityCheckArtMethodPointerArray(dex_cache->GetResolvedMethods(),
888 dex_cache->NumResolvedMethods(),
889 image_pointer_size_,
890 space);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700891 }
892
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700893 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
894
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800895 AppendToBootClassPath(*dex_file.get(), dex_cache);
896 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700897 }
898
Mathieu Chartiere401d142015-04-22 13:56:20 -0700899 CHECK(ValidPointerSize(image_pointer_size_)) << image_pointer_size_;
900
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700901 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
902 // bitmap walk.
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700903 if (!runtime->IsAotCompiler()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700904 // Only the Aot compiler supports having an image with a different pointer size than the
905 // runtime. This happens on the host for compile 32 bit tests since we use a 64 bit libart
906 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
907 CHECK_EQ(image_pointer_size_, sizeof(void*));
Mathieu Chartier2d721012014-11-10 11:08:06 -0800908 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700909
Mathieu Chartierc7853442015-03-27 14:35:38 -0700910 if (kSanityCheckObjects) {
911 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
912 auto* dex_cache = dex_caches->Get(i);
913 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
914 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
915 if (field != nullptr) {
916 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
917 }
918 }
919 }
920 heap->VisitObjects(SanityCheckObjectsCallback, nullptr);
921 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700922
Mathieu Chartiere401d142015-04-22 13:56:20 -0700923 // Set entry point to interpreter if in InterpretOnly mode.
924 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200925 const ImageHeader& header = space->GetImageHeader();
926 const ImageSection& methods = header.GetMethodsSection();
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200927 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +0100928 methods.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700929 }
930
Brian Carlstroma663ea52011-08-19 23:33:41 -0700931 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800932 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700933 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700934
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800935 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700936 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800937 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800938 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700939 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
940 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700941 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
942 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
943 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
944 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
Fred Shih4ee7a662014-07-11 09:59:27 -0700945 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800946 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
947 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
948 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
949 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
950 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
951 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
952 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
953 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
954 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
955 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700956
Ian Rogers98379392014-02-24 16:53:16 -0800957 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700958
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800959 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700960}
961
Mathieu Chartiere401d142015-04-22 13:56:20 -0700962bool ClassLinker::ClassInClassTable(mirror::Class* klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -0700963 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
964 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700965}
966
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700967void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -0700968 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
969 // enabling tracing requires the mutator lock, there are no race conditions here.
970 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -0700971 Thread* const self = Thread::Current();
972 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700973 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
974 visitor, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700975 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700976 // Argument for how root visiting deals with ArtField and ArtMethod roots.
977 // There is 3 GC cases to handle:
978 // Non moving concurrent:
979 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700980 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700981 //
982 // Moving non-concurrent:
983 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
984 // To prevent missing roots, this case needs to ensure that there is no
985 // suspend points between the point which we allocate ArtMethod arrays and place them in a
986 // class which is in the class table.
987 //
988 // Moving concurrent:
989 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
990 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700991 boot_class_table_.VisitRoots(buffered_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -0700992
993 // If tracing is enabled, then mark all the class loaders to prevent unloading.
994 if (tracing_enabled) {
995 for (const ClassLoaderData& data : class_loaders_) {
996 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
997 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
998 }
999 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001000 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001001 for (auto& root : new_class_roots_) {
1002 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001003 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001004 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001005 // Concurrent moving GC marked new roots through the to-space invariant.
1006 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001007 }
1008 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001009 buffered_visitor.Flush(); // Flush before clearing new_class_roots_.
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001010 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1011 new_class_roots_.clear();
1012 }
1013 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1014 log_new_class_table_roots_ = true;
1015 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1016 log_new_class_table_roots_ = false;
1017 }
1018 // We deliberately ignore the class roots in the image since we
1019 // handle image roots by using the MS/CMS rescanning of dirty cards.
1020}
1021
Brian Carlstroma663ea52011-08-19 23:33:41 -07001022// Keep in sync with InitCallback. Anything we visit, we need to
1023// reinit references to when reinitializing a ClassLinker from a
1024// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001025void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07001026 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001027 VisitClassRoots(visitor, flags);
Mathieu Chartier31000802015-06-14 14:14:37 -07001028 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07001029 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
1030 // unloading if we are marking roots.
1031 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001032}
1033
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001034class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
1035 public:
1036 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
1037 : visitor_(visitor),
1038 done_(false) {}
1039
1040 void Visit(mirror::ClassLoader* class_loader)
1041 SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
1042 ClassTable* const class_table = class_loader->GetClassTable();
1043 if (!done_ && class_table != nullptr && !class_table->Visit(visitor_)) {
1044 // If the visitor ClassTable returns false it means that we don't need to continue.
1045 done_ = true;
1046 }
1047 }
1048
1049 private:
1050 ClassVisitor* const visitor_;
1051 // If done is true then we don't need to do any more visiting.
1052 bool done_;
1053};
1054
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001055void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07001056 if (boot_class_table_.Visit(visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001057 VisitClassLoaderClassesVisitor loader_visitor(visitor);
1058 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001059 }
1060}
1061
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001062void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001063 if (dex_cache_image_class_lookup_required_) {
1064 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001065 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001066 Thread* const self = Thread::Current();
1067 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1068 // Not safe to have thread suspension when we are holding a lock.
1069 if (self != nullptr) {
1070 ScopedAssertNoThreadSuspension nts(self, __FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001071 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07001072 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001073 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08001074 }
1075}
1076
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001077class GetClassesInToVector : public ClassVisitor {
1078 public:
1079 bool Visit(mirror::Class* klass) OVERRIDE {
1080 classes_.push_back(klass);
1081 return true;
1082 }
1083 std::vector<mirror::Class*> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07001084};
1085
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001086class GetClassInToObjectArray : public ClassVisitor {
1087 public:
1088 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
1089 : arr_(arr), index_(0) {}
1090
1091 bool Visit(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
1092 ++index_;
1093 if (index_ <= arr_->GetLength()) {
1094 arr_->Set(index_ - 1, klass);
1095 return true;
1096 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001097 return false;
1098 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001099
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001100 bool Succeeded() const SHARED_REQUIRES(Locks::mutator_lock_) {
1101 return index_ <= arr_->GetLength();
1102 }
1103
1104 private:
1105 mirror::ObjectArray<mirror::Class>* const arr_;
1106 int32_t index_;
1107};
1108
1109void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001110 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1111 // is avoiding duplicates.
1112 if (!kMovingClasses) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001113 GetClassesInToVector accumulator;
1114 VisitClasses(&accumulator);
1115 for (mirror::Class* klass : accumulator.classes_) {
1116 if (!visitor->Visit(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001117 return;
1118 }
1119 }
1120 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001121 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001122 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001123 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07001124 // We size the array assuming classes won't be added to the class table during the visit.
1125 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001126 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001127 size_t class_table_size;
1128 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001129 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001130 // Add 100 in case new classes get loaded when we are filling in the object array.
1131 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07001132 }
1133 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1134 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1135 classes.Assign(
1136 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1137 CHECK(classes.Get() != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001138 GetClassInToObjectArray accumulator(classes.Get());
1139 VisitClasses(&accumulator);
1140 if (accumulator.Succeeded()) {
1141 break;
1142 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001143 }
1144 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1145 // If the class table shrank during creation of the clases array we expect null elements. If
1146 // the class table grew then the loop repeats. If classes are created after the loop has
1147 // finished then we don't visit.
1148 mirror::Class* klass = classes->Get(i);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001149 if (klass != nullptr && !visitor->Visit(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001150 return;
1151 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001152 }
1153 }
1154}
1155
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001156ClassLinker::~ClassLinker() {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001157 mirror::Class::ResetClass();
1158 mirror::Constructor::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001159 mirror::Field::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001160 mirror::Method::ResetClass();
1161 mirror::Reference::ResetClass();
1162 mirror::StackTraceElement::ResetClass();
1163 mirror::String::ResetClass();
1164 mirror::Throwable::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001165 mirror::BooleanArray::ResetArrayClass();
1166 mirror::ByteArray::ResetArrayClass();
1167 mirror::CharArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001168 mirror::Constructor::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001169 mirror::DoubleArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001170 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001171 mirror::FloatArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001172 mirror::Method::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001173 mirror::IntArray::ResetArrayClass();
1174 mirror::LongArray::ResetArrayClass();
1175 mirror::ShortArray::ResetArrayClass();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001176 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07001177 for (const ClassLoaderData& data : class_loaders_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001178 DeleteClassLoader(self, data);
Mathieu Chartier6b069532015-08-05 15:08:12 -07001179 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07001180 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001181}
1182
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001183void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data) {
1184 Runtime* const runtime = Runtime::Current();
1185 JavaVMExt* const vm = runtime->GetJavaVM();
1186 vm->DeleteWeakGlobalRef(self, data.weak_root);
1187 if (runtime->GetJit() != nullptr) {
1188 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
1189 if (code_cache != nullptr) {
1190 code_cache->RemoveMethodsIn(self, *data.allocator);
1191 }
1192 }
1193 delete data.allocator;
1194 delete data.class_table;
1195}
1196
Mathieu Chartiere401d142015-04-22 13:56:20 -07001197mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) {
1198 return down_cast<mirror::PointerArray*>(image_pointer_size_ == 8u ?
1199 static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length)) :
1200 static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length)));
1201}
1202
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001203mirror::DexCache* ClassLinker::AllocDexCache(Thread* self,
1204 const DexFile& dex_file,
1205 LinearAlloc* linear_alloc) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001206 StackHandleScope<6> hs(self);
1207 auto dex_cache(hs.NewHandle(down_cast<mirror::DexCache*>(
1208 GetClassRoot(kJavaLangDexCache)->AllocObject(self))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001209 if (dex_cache.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001210 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001211 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001212 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001213 auto location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001214 if (location.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001215 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001216 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001217 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001218 DexCacheArraysLayout layout(image_pointer_size_, &dex_file);
1219 uint8_t* raw_arrays = nullptr;
Vladimir Marko09d09432015-09-08 13:47:48 +01001220 if (dex_file.GetOatDexFile() != nullptr &&
1221 dex_file.GetOatDexFile()->GetDexCacheArrays() != nullptr) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +01001222 raw_arrays = dex_file.GetOatDexFile()->GetDexCacheArrays();
Vladimir Marko09d09432015-09-08 13:47:48 +01001223 } else if (dex_file.NumStringIds() != 0u || dex_file.NumTypeIds() != 0u ||
Vladimir Marko05792b92015-08-03 11:56:49 +01001224 dex_file.NumMethodIds() != 0u || dex_file.NumFieldIds() != 0u) {
1225 // NOTE: We "leak" the raw_arrays because we never destroy the dex cache.
1226 DCHECK(image_pointer_size_ == 4u || image_pointer_size_ == 8u);
Mathieu Chartier32cc9ee2015-10-15 09:19:15 -07001227 // Zero-initialized.
1228 raw_arrays = reinterpret_cast<uint8_t*>(linear_alloc->Alloc(self, layout.Size()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001229 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001230 GcRoot<mirror::String>* strings = (dex_file.NumStringIds() == 0u) ? nullptr :
1231 reinterpret_cast<GcRoot<mirror::String>*>(raw_arrays + layout.StringsOffset());
1232 GcRoot<mirror::Class>* types = (dex_file.NumTypeIds() == 0u) ? nullptr :
1233 reinterpret_cast<GcRoot<mirror::Class>*>(raw_arrays + layout.TypesOffset());
1234 ArtMethod** methods = (dex_file.NumMethodIds() == 0u) ? nullptr :
1235 reinterpret_cast<ArtMethod**>(raw_arrays + layout.MethodsOffset());
1236 ArtField** fields = (dex_file.NumFieldIds() == 0u) ? nullptr :
1237 reinterpret_cast<ArtField**>(raw_arrays + layout.FieldsOffset());
1238 dex_cache->Init(&dex_file,
1239 location.Get(),
1240 strings,
1241 dex_file.NumStringIds(),
1242 types,
1243 dex_file.NumTypeIds(),
1244 methods,
1245 dex_file.NumMethodIds(),
1246 fields,
1247 dex_file.NumFieldIds(),
1248 image_pointer_size_);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001249 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001250}
1251
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001252mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001253 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001254 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001255 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001256 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001257 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001258 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1259 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001260 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001261 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08001262 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001263 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001264 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001265}
1266
Ian Rogers6fac4472014-02-25 17:01:10 -08001267mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001268 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001269}
1270
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001271mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001272 Thread* self,
1273 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001274 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1275 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001276}
1277
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001278mirror::Class* ClassLinker::EnsureResolved(Thread* self,
1279 const char* descriptor,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001280 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001281 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001282
1283 // For temporary classes we must wait for them to be retired.
1284 if (init_done_ && klass->IsTemp()) {
1285 CHECK(!klass->IsResolved());
1286 if (klass->IsErroneous()) {
1287 ThrowEarlierClassFailure(klass);
1288 return nullptr;
1289 }
1290 StackHandleScope<1> hs(self);
1291 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1292 ObjectLock<mirror::Class> lock(self, h_class);
1293 // Loop and wait for the resolving thread to retire this class.
1294 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1295 lock.WaitIgnoringInterrupts();
1296 }
1297 if (h_class->IsErroneous()) {
1298 ThrowEarlierClassFailure(h_class.Get());
1299 return nullptr;
1300 }
1301 CHECK(h_class->IsRetired());
1302 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001303 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
1304 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001305 }
1306
Brian Carlstromaded5f72011-10-07 17:15:04 -07001307 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001308 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001309 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001310 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1311 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001312 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001313 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1314 ThrowClassCircularityError(h_class.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001315 mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001316 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001317 }
1318 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001319 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001320 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001321 }
1322 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001323
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001324 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001325 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001326 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001327 }
1328 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001329 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001330 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001331 return klass;
1332}
1333
Ian Rogers68b56852014-08-29 20:19:11 -07001334typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
1335
1336// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001337ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001338 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001339 for (const DexFile* dex_file : class_path) {
1340 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001341 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07001342 return ClassPathEntry(dex_file, dex_class_def);
1343 }
1344 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001345 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07001346}
1347
Andreas Gampef865ea92015-04-13 22:14:19 -07001348static bool IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1349 mirror::ClassLoader* class_loader)
Mathieu Chartier90443472015-07-16 20:32:27 -07001350 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampef865ea92015-04-13 22:14:19 -07001351 return class_loader == nullptr ||
1352 class_loader->GetClass() ==
1353 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader);
1354}
1355
1356bool ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001357 Thread* self,
1358 const char* descriptor,
Andreas Gampef865ea92015-04-13 22:14:19 -07001359 size_t hash,
1360 Handle<mirror::ClassLoader> class_loader,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001361 mirror::Class** result) {
Andreas Gampef865ea92015-04-13 22:14:19 -07001362 // Termination case: boot class-loader.
1363 if (IsBootClassLoader(soa, class_loader.Get())) {
1364 // The boot class loader, search the boot class path.
1365 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
1366 if (pair.second != nullptr) {
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001367 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Andreas Gampef865ea92015-04-13 22:14:19 -07001368 if (klass != nullptr) {
1369 *result = EnsureResolved(self, descriptor, klass);
1370 } else {
1371 *result = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(),
1372 *pair.first, *pair.second);
1373 }
1374 if (*result == nullptr) {
1375 CHECK(self->IsExceptionPending()) << descriptor;
1376 self->ClearException();
1377 }
Ian Rogers32427292014-11-19 14:05:21 -08001378 } else {
Andreas Gampef865ea92015-04-13 22:14:19 -07001379 *result = nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001380 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001381 return true;
1382 }
1383
1384 // Unsupported class-loader?
1385 if (class_loader->GetClass() !=
1386 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)) {
1387 *result = nullptr;
1388 return false;
1389 }
1390
1391 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
1392 StackHandleScope<4> hs(self);
1393 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
1394 bool recursive_result = FindClassInPathClassLoader(soa, self, descriptor, hash, h_parent, result);
1395
1396 if (!recursive_result) {
1397 // Something wrong up the chain.
1398 return false;
1399 }
1400
1401 if (*result != nullptr) {
1402 // Found the class up the chain.
1403 return true;
1404 }
1405
1406 // Handle this step.
1407 // Handle as if this is the child PathClassLoader.
1408 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
1409 // We need to get the DexPathList and loop through it.
1410 ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
1411 ArtField* const dex_file_field =
1412 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
1413 mirror::Object* dex_path_list =
1414 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
1415 GetObject(class_loader.Get());
1416 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
1417 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1418 mirror::Object* dex_elements_obj =
1419 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1420 GetObject(dex_path_list);
1421 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1422 // at the mCookie which is a DexFile vector.
1423 if (dex_elements_obj != nullptr) {
1424 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
1425 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
1426 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
1427 mirror::Object* element = dex_elements->GetWithoutChecks(i);
1428 if (element == nullptr) {
1429 // Should never happen, fall back to java code to throw a NPE.
1430 break;
1431 }
1432 mirror::Object* dex_file = dex_file_field->GetObject(element);
1433 if (dex_file != nullptr) {
1434 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
1435 if (long_array == nullptr) {
1436 // This should never happen so log a warning.
1437 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001438 break;
1439 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001440 int32_t long_array_size = long_array->GetLength();
Mathieu Chartiere58991b2015-10-13 07:59:34 -07001441 // First element is the oat file.
1442 for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) {
Andreas Gampef865ea92015-04-13 22:14:19 -07001443 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
1444 long_array->GetWithoutChecks(j)));
1445 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
1446 if (dex_class_def != nullptr) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -07001447 mirror::Class* klass = DefineClass(self,
1448 descriptor,
1449 hash,
1450 class_loader,
1451 *cp_dex_file,
1452 *dex_class_def);
Andreas Gampef865ea92015-04-13 22:14:19 -07001453 if (klass == nullptr) {
1454 CHECK(self->IsExceptionPending()) << descriptor;
1455 self->ClearException();
1456 // TODO: Is it really right to break here, and not check the other dex files?
1457 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001458 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001459 *result = klass;
1460 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001461 }
1462 }
1463 }
1464 }
1465 }
Ian Rogers32427292014-11-19 14:05:21 -08001466 self->AssertNoPendingException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001467 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001468
1469 // Result is still null from the parent call, no need to set it again...
1470 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001471}
1472
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001473mirror::Class* ClassLinker::FindClass(Thread* self,
1474 const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001475 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001476 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001477 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001478 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001479 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001480 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1481 // for primitive classes that aren't backed by dex files.
1482 return FindPrimitiveClass(descriptor[0]);
1483 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001484 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001485 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001486 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07001487 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001488 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001489 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001490 // Class is not yet loaded.
1491 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001492 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001493 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001494 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001495 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07001496 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001497 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07001498 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07001499 } else {
1500 // The boot class loader is searched ahead of the application class loader, failures are
1501 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
1502 // trigger the chaining with a proper stack trace.
1503 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001504 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07001505 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05001506 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001507 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001508 ScopedObjectAccessUnchecked soa(self);
Andreas Gampef865ea92015-04-13 22:14:19 -07001509 mirror::Class* cp_klass;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001510 if (FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader, &cp_klass)) {
Andreas Gampef865ea92015-04-13 22:14:19 -07001511 // The chain was understood. So the value in cp_klass is either the class we were looking
1512 // for, or not found.
1513 if (cp_klass != nullptr) {
1514 return cp_klass;
1515 }
1516 // TODO: We handle the boot classpath loader in FindClassInPathClassLoader. Try to unify this
1517 // and the branch above. TODO: throw the right exception here.
1518
1519 // We'll let the Java-side rediscover all this and throw the exception with the right stack
1520 // trace.
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07001521 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001522
1523 if (Runtime::Current()->IsAotCompiler()) {
1524 // Oops, compile-time, can't run actual class-loader code.
1525 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
1526 self->SetException(pre_allocated);
1527 return nullptr;
1528 }
1529
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001530 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001531 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001532 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07001533 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07001534 {
1535 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001536 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1537 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07001538 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001539 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07001540 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07001541 }
Ian Rogers68b56852014-08-29 20:19:11 -07001542 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001543 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1544 WellKnownClasses::java_lang_ClassLoader_loadClass,
1545 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001546 }
Ian Rogers98379392014-02-24 16:53:16 -08001547 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001548 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07001549 return nullptr;
1550 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08001551 // broken loader - throw NPE to be compatible with Dalvik
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001552 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
1553 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07001554 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08001555 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001556 // success, return mirror::Class*
1557 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001558 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001559 }
Ian Rogers07140832014-09-30 15:43:59 -07001560 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001561}
1562
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001563mirror::Class* ClassLinker::DefineClass(Thread* self,
1564 const char* descriptor,
1565 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001566 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001567 const DexFile& dex_file,
1568 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001569 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001570 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001571
Brian Carlstromaded5f72011-10-07 17:15:04 -07001572 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001573 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001574 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001575 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001576 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001577 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001578 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001579 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001580 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001581 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1582 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001583 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001584 klass.Assign(GetClassRoot(kJavaLangDexCache));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001585 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001586 }
1587
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001588 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001589 // Allocate a class with the status of not ready.
1590 // Interface object should get the right size here. Regular class will
1591 // figure out the right size later and be replaced with one of the right
1592 // size when the class becomes resolved.
1593 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001594 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001595 if (UNLIKELY(klass.Get() == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001596 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07001597 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001598 }
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001599 mirror::DexCache* dex_cache = RegisterDexFile(
1600 dex_file,
1601 GetOrCreateAllocatorForClassLoader(class_loader.Get()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001602 if (dex_cache == nullptr) {
1603 self->AssertPendingOOMException();
1604 return nullptr;
1605 }
1606 klass->SetDexCache(dex_cache);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001607 SetupClass(dex_file, dex_class_def, klass, class_loader.Get());
1608
Jeff Hao848f70a2014-01-15 13:49:50 -08001609 // Mark the string class by setting its access flag.
1610 if (UNLIKELY(!init_done_)) {
1611 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
1612 klass->SetStringClass();
1613 }
1614 }
1615
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001616 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001617 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001618
Mathieu Chartier590fee92013-09-13 13:46:47 -07001619 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001620 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001621 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001622 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1623 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001624 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001625 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001626
Mathieu Chartierc7853442015-03-27 14:35:38 -07001627 // Load the fields and other things after we are inserted in the table. This is so that we don't
1628 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
1629 // other reason is that the field roots are only visited from the class table. So we need to be
1630 // inserted before we allocate / fill in these fields.
1631 LoadClass(self, dex_file, dex_class_def, klass);
1632 if (self->IsExceptionPending()) {
1633 // An exception occured during load, set status to erroneous while holding klass' lock in case
1634 // notification is necessary.
1635 if (!klass->IsErroneous()) {
1636 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
1637 }
1638 return nullptr;
1639 }
1640
Brian Carlstromaded5f72011-10-07 17:15:04 -07001641 // Finish loading (if necessary) by finding parents
1642 CHECK(!klass->IsLoaded());
1643 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1644 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001645 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001646 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001647 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001648 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001649 }
1650 CHECK(klass->IsLoaded());
1651 // Link the class (if necessary)
1652 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001653 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001654 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001655
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07001656 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001657 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001658 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001659 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001660 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001661 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001662 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001663 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07001664 self->AssertNoPendingException();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07001665 CHECK(h_new_class.Get() != nullptr) << descriptor;
1666 CHECK(h_new_class->IsResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001667
Sebastien Hertza8a697f2015-01-15 12:28:47 +01001668 // Instrumentation may have updated entrypoints for all methods of all
1669 // classes. However it could not update methods of this class while we
1670 // were loading it. Now the class is resolved, we can update entrypoints
1671 // as required by instrumentation.
1672 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
1673 // We must be in the kRunnable state to prevent instrumentation from
1674 // suspending all threads to update entrypoints while we are doing it
1675 // for this class.
1676 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07001677 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01001678 }
1679
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001680 /*
1681 * We send CLASS_PREPARE events to the debugger from here. The
1682 * definition of "preparation" is creating the static fields for a
1683 * class and initializing them to the standard default values, but not
1684 * executing any code (that comes later, during "initialization").
1685 *
1686 * We did the static preparation in LinkClass.
1687 *
1688 * The class has been prepared and resolved but possibly not yet verified
1689 * at this point.
1690 */
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07001691 Dbg::PostClassPrepare(h_new_class.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001692
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07001693 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001694}
1695
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001696uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
1697 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07001698 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001699 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07001700 size_t num_8 = 0;
1701 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001702 size_t num_32 = 0;
1703 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001704 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001705 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1706 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001707 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001708 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07001709 switch (c) {
1710 case 'L':
1711 case '[':
1712 num_ref++;
1713 break;
1714 case 'J':
1715 case 'D':
1716 num_64++;
1717 break;
1718 case 'I':
1719 case 'F':
1720 num_32++;
1721 break;
1722 case 'S':
1723 case 'C':
1724 num_16++;
1725 break;
1726 case 'B':
1727 case 'Z':
1728 num_8++;
1729 break;
1730 default:
1731 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08001732 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001733 }
1734 }
1735 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001736 return mirror::Class::ComputeClassSize(false,
1737 0,
1738 num_8,
1739 num_16,
1740 num_32,
1741 num_64,
1742 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001743 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001744}
1745
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001746OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file,
1747 uint16_t class_def_idx,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001748 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001749 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Richard Uhler07b3c232015-03-31 15:57:54 -07001750 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001751 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001752 *found = false;
1753 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001754 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001755 *found = true;
1756 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08001757}
1758
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001759static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file,
1760 uint16_t class_def_idx,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001761 uint32_t method_idx) {
1762 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07001763 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001764 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001765 ClassDataItemIterator it(dex_file, class_data);
1766 // Skip fields
1767 while (it.HasNextStaticField()) {
1768 it.Next();
1769 }
1770 while (it.HasNextInstanceField()) {
1771 it.Next();
1772 }
1773 // Process methods
1774 size_t class_def_method_index = 0;
1775 while (it.HasNextDirectMethod()) {
1776 if (it.GetMemberIndex() == method_idx) {
1777 return class_def_method_index;
1778 }
1779 class_def_method_index++;
1780 it.Next();
1781 }
1782 while (it.HasNextVirtualMethod()) {
1783 if (it.GetMemberIndex() == method_idx) {
1784 return class_def_method_index;
1785 }
1786 class_def_method_index++;
1787 it.Next();
1788 }
1789 DCHECK(!it.HasNext());
1790 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08001791 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001792}
1793
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001794const OatFile::OatMethod ClassLinker::FindOatMethodFor(ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08001795 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001796 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001797 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08001798 size_t oat_method_index;
1799 if (method->IsStatic() || method->IsDirect()) {
1800 // Simple case where the oat method index was stashed at load time.
1801 oat_method_index = method->GetMethodIndex();
1802 } else {
1803 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1804 // by search for its position in the declared virtual methods.
1805 oat_method_index = declaring_class->NumDirectMethods();
1806 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001807 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001808 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07001809 // Check method index instead of identity in case of duplicate method definitions.
1810 if (method->GetDexMethodIndex() ==
Mathieu Chartiere401d142015-04-22 13:56:20 -07001811 declaring_class->GetVirtualMethod(i, image_pointer_size_)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001812 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001813 break;
1814 }
Ian Rogersf320b632012-03-13 18:47:47 -07001815 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001816 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001817 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
1818 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001819 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001820 DCHECK_EQ(oat_method_index,
1821 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001822 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001823 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07001824 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
1825 declaring_class->GetDexClassDefIndex(),
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001826 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001827 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001828 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001829 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001830 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07001831}
1832
1833// Special case to get oat code without overwriting a trampoline.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001834const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001835 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07001836 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001837 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07001838 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001839 bool found;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001840 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001841 if (found) {
1842 auto* code = oat_method.GetQuickCode();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001843 if (code != nullptr) {
1844 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08001845 }
1846 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001847 if (method->IsNative()) {
1848 // No code and native? Use generic trampoline.
1849 return GetQuickGenericJniStub();
1850 }
1851 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07001852}
1853
Mathieu Chartiere401d142015-04-22 13:56:20 -07001854const void* ClassLinker::GetOatMethodQuickCodeFor(ArtMethod* method) {
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001855 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
1856 return nullptr;
1857 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001858 bool found;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001859 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001860 if (found) {
1861 return oat_method.GetQuickCode();
1862 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001863 return nullptr;
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001864}
1865
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001866const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file,
1867 uint16_t class_def_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08001868 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001869 bool found;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001870 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
Ian Rogers97b52f82014-08-14 11:34:07 -07001871 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001872 return nullptr;
1873 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001874 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001875 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001876}
1877
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001878// Returns true if the method must run with interpreter, false otherwise.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001879static bool NeedsInterpreter(ArtMethod* method, const void* quick_code)
Mathieu Chartier90443472015-07-16 20:32:27 -07001880 SHARED_REQUIRES(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08001881 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001882 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08001883 // May return true for native code, in the case of generic JNI
1884 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001885 return true;
1886 }
1887 // If interpreter mode is enabled, every method (except native and proxy) must
1888 // be run with interpreter.
1889 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
1890 !method->IsNative() && !method->IsProxyMethod();
1891}
1892
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001893void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08001894 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07001895 if (klass->NumDirectMethods() == 0) {
1896 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08001897 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001898 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001899 if (!runtime->IsStarted()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001900 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001901 return; // OAT file unavailable.
1902 }
Ian Rogers19846512012-02-24 11:42:47 -08001903 }
Alex Light64ad14d2014-08-19 14:23:13 -07001904
Mathieu Chartierf8322842014-05-16 10:59:25 -07001905 const DexFile& dex_file = klass->GetDexFile();
1906 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07001907 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07001908 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07001909 // There should always be class data if there were direct methods.
1910 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08001911 ClassDataItemIterator it(dex_file, class_data);
1912 // Skip fields
1913 while (it.HasNextStaticField()) {
1914 it.Next();
1915 }
1916 while (it.HasNextInstanceField()) {
1917 it.Next();
1918 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001919 bool has_oat_class;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07001920 OatFile::OatClass oat_class = FindOatClass(dex_file,
1921 klass->GetDexClassDefIndex(),
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001922 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07001923 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001924 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001925 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001926 if (!method->IsStatic()) {
1927 // Only update static methods.
1928 continue;
Ian Rogers19846512012-02-24 11:42:47 -08001929 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001930 const void* quick_code = nullptr;
1931 if (has_oat_class) {
1932 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001933 quick_code = oat_method.GetQuickCode();
1934 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001935 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001936 if (enter_interpreter) {
1937 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07001938 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001939 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001940 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08001941 } else {
1942 quick_code = GetQuickToInterpreterBridge();
1943 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001944 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001945 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08001946 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001947 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08001948}
1949
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001950void ClassLinker::LinkCode(ArtMethod* method, const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001951 uint32_t class_def_method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001952 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001953 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001954 // The following code only applies to a non-compiler runtime.
1955 return;
1956 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001957 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001958 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001959 if (oat_class != nullptr) {
1960 // Every kind of method should at least get an invoke stub from the oat_method.
1961 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001962 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001963 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001964 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001965
Jeff Hao16743632013-05-08 10:59:04 -07001966 // Install entry point from interpreter.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001967 bool enter_interpreter = NeedsInterpreter(method, method->GetEntryPointFromQuickCompiledCode());
Jeff Hao16743632013-05-08 10:59:04 -07001968
Brian Carlstrom92827a52011-10-10 15:50:01 -07001969 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001970 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001971 return;
1972 }
Ian Rogers19846512012-02-24 11:42:47 -08001973
1974 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001975 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001976 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
1977 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001978 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001979 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001980 if (!method->IsNative()) {
1981 // Set entry point from compiled code if there's no code or in interpreter only mode.
1982 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001983 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001984 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001985 }
Ian Rogers0d6de042012-02-29 08:50:26 -08001986 }
jeffhao26c0a1a2012-01-17 16:28:33 -08001987
Ian Rogers62d6c772013-02-27 08:32:07 -08001988 if (method->IsNative()) {
1989 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001990 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07001991
1992 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001993 // We have a native method here without code. Then it should have either the generic JNI
1994 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
1995 // TODO: this doesn't handle all the cases where trampolines may be installed.
1996 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1997 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07001998 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001999 }
2000}
2001
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002002void ClassLinker::SetupClass(const DexFile& dex_file,
2003 const DexFile::ClassDef& dex_class_def,
2004 Handle<mirror::Class> klass,
2005 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002006 CHECK(klass.Get() != nullptr);
2007 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002008 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002009 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002010 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002011
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002012 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07002013 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002014 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002015 klass->SetAccessFlags(access_flags);
2016 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002017 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002018 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002019
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002020 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002021 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002022 CHECK(klass->GetDexCacheStrings() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002023}
Brian Carlstrom934486c2011-07-12 23:42:50 -07002024
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002025void ClassLinker::LoadClass(Thread* self,
2026 const DexFile& dex_file,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002027 const DexFile::ClassDef& dex_class_def,
2028 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07002029 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002030 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002031 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002032 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002033 bool has_oat_class = false;
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002034 if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002035 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002036 &has_oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002037 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002038 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002039 }
2040 }
2041 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002042 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002043 }
2044}
2045
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002046LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
2047 LinearAlloc* allocator,
2048 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002049 if (length == 0) {
2050 return nullptr;
2051 }
Vladimir Markocf36d492015-08-12 19:27:26 +01002052 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
2053 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
2054 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002055 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01002056 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002057 CHECK(ret != nullptr);
2058 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
2059 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07002060}
2061
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002062LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
2063 LinearAlloc* allocator,
2064 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002065 if (length == 0) {
2066 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002067 }
Vladimir Marko14632852015-08-17 12:07:23 +01002068 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
2069 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01002070 const size_t storage_size =
2071 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002072 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01002073 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002074 CHECK(ret != nullptr);
2075 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01002076 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002077 }
2078 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002079}
2080
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002081LinearAlloc* ClassLinker::GetAllocatorForClassLoader(mirror::ClassLoader* class_loader) {
2082 if (class_loader == nullptr) {
2083 return Runtime::Current()->GetLinearAlloc();
2084 }
2085 LinearAlloc* allocator = class_loader->GetAllocator();
2086 DCHECK(allocator != nullptr);
2087 return allocator;
2088}
2089
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002090LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(mirror::ClassLoader* class_loader) {
2091 if (class_loader == nullptr) {
2092 return Runtime::Current()->GetLinearAlloc();
2093 }
2094 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2095 LinearAlloc* allocator = class_loader->GetAllocator();
2096 if (allocator == nullptr) {
2097 allocator = Runtime::Current()->CreateLinearAlloc();
2098 class_loader->SetAllocator(allocator);
2099 }
2100 return allocator;
2101}
2102
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002103void ClassLinker::LoadClassMembers(Thread* self,
2104 const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002105 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002106 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002107 const OatFile::OatClass* oat_class) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002108 {
2109 // Note: We cannot have thread suspension until the field and method arrays are setup or else
2110 // Class::VisitFieldRoots may miss some fields or methods.
2111 ScopedAssertNoThreadSuspension nts(self, __FUNCTION__);
2112 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01002113 // We allow duplicate definitions of the same field in a class_data_item
2114 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002115 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002116 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002117 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
2118 allocator,
2119 it.NumStaticFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01002120 size_t num_sfields = 0;
2121 uint32_t last_field_idx = 0u;
2122 for (; it.HasNextStaticField(); it.Next()) {
2123 uint32_t field_idx = it.GetMemberIndex();
2124 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
2125 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
2126 DCHECK_LT(num_sfields, it.NumStaticFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002127 LoadField(it, klass, &sfields->At(num_sfields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01002128 ++num_sfields;
2129 last_field_idx = field_idx;
2130 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002131 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002132 klass->SetSFieldsPtr(sfields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002133 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
2134 // Load instance fields.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002135 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
2136 allocator,
2137 it.NumInstanceFields());
Vladimir Marko23682bf2015-06-24 14:28:03 +01002138 size_t num_ifields = 0u;
2139 last_field_idx = 0u;
2140 for (; it.HasNextInstanceField(); it.Next()) {
2141 uint32_t field_idx = it.GetMemberIndex();
2142 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
2143 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
2144 DCHECK_LT(num_ifields, it.NumInstanceFields());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002145 LoadField(it, klass, &ifields->At(num_ifields));
Vladimir Marko23682bf2015-06-24 14:28:03 +01002146 ++num_ifields;
2147 last_field_idx = field_idx;
2148 }
2149 }
2150 if (UNLIKELY(num_sfields != it.NumStaticFields()) ||
2151 UNLIKELY(num_ifields != it.NumInstanceFields())) {
2152 LOG(WARNING) << "Duplicate fields in class " << PrettyDescriptor(klass.Get())
2153 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields()
2154 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
2155 // NOTE: Not shrinking the over-allocated sfields/ifields.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002156 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002157 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002158 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
2159 // Load methods.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002160 klass->SetDirectMethodsPtr(AllocArtMethodArray(self, allocator, it.NumDirectMethods()));
2161 klass->SetVirtualMethodsPtr(AllocArtMethodArray(self, allocator, it.NumVirtualMethods()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002162 size_t class_def_method_index = 0;
2163 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2164 size_t last_class_def_method_index = 0;
2165 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
2166 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
2167 LoadMethod(self, dex_file, it, klass, method);
2168 LinkCode(method, oat_class, class_def_method_index);
2169 uint32_t it_method_index = it.GetMemberIndex();
2170 if (last_dex_method_index == it_method_index) {
2171 // duplicate case
2172 method->SetMethodIndex(last_class_def_method_index);
2173 } else {
2174 method->SetMethodIndex(class_def_method_index);
2175 last_dex_method_index = it_method_index;
2176 last_class_def_method_index = class_def_method_index;
2177 }
2178 class_def_method_index++;
2179 }
2180 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
2181 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
2182 LoadMethod(self, dex_file, it, klass, method);
2183 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
2184 LinkCode(method, oat_class, class_def_method_index);
2185 class_def_method_index++;
2186 }
2187 DCHECK(!it.HasNext());
Ian Rogers0571d352011-11-03 19:51:38 -07002188 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07002189 // Ensure that the card is marked so that remembered sets pick up native roots.
2190 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07002191 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07002192}
2193
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002194void ClassLinker::LoadField(const ClassDataItemIterator& it,
2195 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07002196 ArtField* dst) {
2197 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002198 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002199 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002200 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002201}
2202
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002203void ClassLinker::LoadMethod(Thread* self,
2204 const DexFile& dex_file,
2205 const ClassDataItemIterator& it,
2206 Handle<mirror::Class> klass,
2207 ArtMethod* dst) {
Ian Rogers19846512012-02-24 11:42:47 -08002208 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002209 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002210 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002211
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002212 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002213 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002214 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002215 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002216
Vladimir Marko05792b92015-08-03 11:56:49 +01002217 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods(), image_pointer_size_);
2218 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes(), image_pointer_size_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002219
Andreas Gampe51829322014-08-25 15:05:04 -07002220 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002221
Ian Rogersdfb325e2013-10-30 01:00:44 -07002222 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002223 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002224 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2225 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002226 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002227 klass->SetFinalizable();
2228 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002229 std::string temp;
2230 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002231 // The Enum class declares a "final" finalize() method to prevent subclasses from
2232 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2233 // subclasses, so we exclude it here.
2234 // We also want to avoid setting the flag on Object, where we know that finalize() is
2235 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002236 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2237 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002238 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002239 }
2240 }
2241 }
2242 } else if (method_name[0] == '<') {
2243 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002244 bool is_init = (strcmp("<init>", method_name) == 0);
2245 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002246 if (UNLIKELY(!is_init && !is_clinit)) {
2247 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2248 } else {
2249 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2250 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002251 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002252 access_flags |= kAccConstructor;
2253 }
2254 }
2255 }
2256 dst->SetAccessFlags(access_flags);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002257}
2258
Ian Rogers7b078e82014-09-10 14:44:24 -07002259void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002260 StackHandleScope<1> hs(self);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002261 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(
2262 self,
2263 dex_file,
2264 Runtime::Current()->GetLinearAlloc())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002265 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2266 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002267 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002268}
2269
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002270void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002271 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002272 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002273 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002274 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002275}
2276
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002277void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002278 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002279 Thread* const self = Thread::Current();
2280 dex_lock_.AssertExclusiveHeld(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002281 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002282 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2283 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002284 // Clean up pass to remove null dex caches.
2285 // Null dex caches can occur due to class unloading and we are lazily removing null entries.
2286 JavaVMExt* const vm = self->GetJniEnv()->vm;
2287 for (auto it = dex_caches_.begin(); it != dex_caches_.end();) {
2288 mirror::Object* dex_cache_root = self->DecodeJObject(*it);
2289 if (dex_cache_root == nullptr) {
2290 vm->DeleteWeakGlobalRef(self, *it);
2291 it = dex_caches_.erase(it);
2292 } else {
2293 ++it;
2294 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07002295 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002296 dex_caches_.push_back(vm->AddWeakGlobalRef(self, dex_cache.Get()));
2297 dex_cache->SetDexFile(&dex_file);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002298}
2299
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002300mirror::DexCache* ClassLinker::RegisterDexFile(const DexFile& dex_file, LinearAlloc* linear_alloc) {
Ian Rogers1f539342012-10-03 21:09:42 -07002301 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002302 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002303 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002304 mirror::DexCache* dex_cache = FindDexCacheLocked(self, dex_file, true);
2305 if (dex_cache != nullptr) {
2306 return dex_cache;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002307 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002308 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002309 // Don't alloc while holding the lock, since allocation may need to
2310 // suspend all threads and another thread may need the dex_lock_ to
2311 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002312 StackHandleScope<1> hs(self);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002313 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file, linear_alloc)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002314 WriterMutexLock mu(self, dex_lock_);
2315 mirror::DexCache* dex_cache = FindDexCacheLocked(self, dex_file, true);
2316 if (dex_cache != nullptr) {
2317 return dex_cache;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002318 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002319 if (h_dex_cache.Get() == nullptr) {
2320 self->AssertPendingOOMException();
2321 return nullptr;
2322 }
2323 RegisterDexFileLocked(dex_file, h_dex_cache);
2324 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002325}
2326
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002327void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002328 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002329 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002330 RegisterDexFileLocked(dex_file, dex_cache);
2331}
2332
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002333mirror::DexCache* ClassLinker::FindDexCache(Thread* self,
2334 const DexFile& dex_file,
2335 bool allow_failure) {
2336 ReaderMutexLock mu(self, dex_lock_);
2337 return FindDexCacheLocked(self, dex_file, allow_failure);
2338}
2339
2340mirror::DexCache* ClassLinker::FindDexCacheLocked(Thread* self,
2341 const DexFile& dex_file,
2342 bool allow_failure) {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002343 // Search assuming unique-ness of dex file.
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002344 for (jweak weak_root : dex_caches_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07002345 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
Mathieu Chartierca330892015-09-01 20:00:10 -07002346 if (dex_cache != nullptr && dex_cache->GetDexFile() == &dex_file) {
2347 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002348 }
2349 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002350 if (allow_failure) {
2351 return nullptr;
2352 }
Mathieu Chartierac8f4392015-08-27 13:54:20 -07002353 std::string location(dex_file.GetLocation());
Brian Carlstrom81a90872015-08-28 09:07:14 -07002354 // Failure, dump diagnostic and abort.
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002355 for (jobject weak_root : dex_caches_) {
2356 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
2357 if (dex_cache != nullptr) {
2358 LOG(ERROR) << "Registered dex file " << dex_cache->GetDexFile()->GetLocation();
2359 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07002360 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002361 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002362 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002363}
2364
Mathieu Chartiere401d142015-04-22 13:56:20 -07002365void ClassLinker::FixupDexCaches(ArtMethod* resolution_method) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002366 Thread* const self = Thread::Current();
2367 ReaderMutexLock mu(self, dex_lock_);
2368 for (jobject weak_root : dex_caches_) {
2369 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
2370 if (dex_cache != nullptr) {
2371 dex_cache->Fixup(resolution_method, image_pointer_size_);
2372 }
Ian Rogers19846512012-02-24 11:42:47 -08002373 }
2374}
2375
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002376mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002377 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002378 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002379 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002380 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002381 }
2382 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002383}
2384
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002385mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2386 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002387 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07002388 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002389 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002390 StackHandleScope<1> hs(self);
2391 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002392 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002393 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
2394 h_class->SetPrimitiveType(type);
2395 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002396 const char* descriptor = Primitive::Descriptor(type);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002397 mirror::Class* existing = InsertClass(descriptor, h_class.Get(),
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002398 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002399 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002400 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07002401}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002402
Brian Carlstrombe977852011-07-19 14:54:54 -07002403// Create an array class (i.e. the class object for the array, not the
2404// array itself). "descriptor" looks like "[C" or "[[[[B" or
2405// "[Ljava/lang/String;".
2406//
2407// If "descriptor" refers to an array of primitives, look up the
2408// primitive type's internally-generated class object.
2409//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002410// "class_loader" is the class loader of the class that's referring to
2411// us. It's used to ensure that we're looking for the element type in
2412// the right context. It does NOT become the class loader for the
2413// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002414//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002415// Returns null with an exception raised on failure.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002416mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002417 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002418 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002419 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002420 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002421 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
2422 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002423 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002424 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002425 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002426 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
2427 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002428 if (component_type.Get() == nullptr) {
2429 DCHECK(self->IsExceptionPending());
2430 return nullptr;
2431 } else {
2432 self->ClearException();
2433 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002434 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002435 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2436 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2437 return nullptr;
2438 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002439 // See if the component type is already loaded. Array classes are
2440 // always associated with the class loader of their underlying
2441 // element type -- an array of Strings goes with the loader for
2442 // java/lang/String -- so we need to look for it there. (The
2443 // caller should have checked for the existence of the class
2444 // before calling here, but they did so with *their* class loader,
2445 // not the component type's loader.)
2446 //
2447 // If we find it, the caller adds "loader" to the class' initiating
2448 // loader list, which should prevent us from going through this again.
2449 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002450 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002451 // are the same, because our caller (FindClass) just did the
2452 // lookup. (Even if we get this wrong we still have correct behavior,
2453 // because we effectively do this lookup again when we add the new
2454 // class to the hash table --- necessary because of possible races with
2455 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002456 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002457 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002458 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002459 return new_class;
2460 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002461 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002462
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002463 // Fill out the fields in the Class.
2464 //
2465 // It is possible to execute some methods against arrays, because
2466 // all arrays are subclasses of java_lang_Object_, so we need to set
2467 // up a vtable. We can just point at the one in java_lang_Object_.
2468 //
2469 // Array classes are simple enough that we don't need to do a full
2470 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002471 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002472 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002473 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002474 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002475 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002476 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002477 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002478 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002479 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002480 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002481 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002482 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002483 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002484 } else if (strcmp(descriptor, "[J") == 0) {
2485 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002486 }
2487 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002488 if (new_class.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002489 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002490 if (new_class.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002491 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002492 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002493 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002494 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002495 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002496 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002497 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002498 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002499 new_class->SetSuperClass(java_lang_Object);
2500 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002501 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002502 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07002503 if (component_type->IsPrimitive()) {
2504 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
2505 } else {
2506 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
2507 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002508 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002509 {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002510 ArtMethod* imt[mirror::Class::kImtSize];
2511 std::fill_n(imt, arraysize(imt), Runtime::Current()->GetImtUnimplementedMethod());
2512 new_class->PopulateEmbeddedImtAndVTable(imt, image_pointer_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002513 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002514 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002515 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002516 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002517
2518
2519 // All arrays have java/lang/Cloneable and java/io/Serializable as
2520 // interfaces. We need to set that up here, so that stuff like
2521 // "instanceof" works right.
2522 //
2523 // Note: The GC could run during the call to FindSystemClass,
2524 // so we need to make sure the class object is GC-valid while we're in
2525 // there. Do this by clearing the interface list so the GC will just
2526 // think that the entries are null.
2527
2528
2529 // Use the single, global copies of "interfaces" and "iftable"
2530 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002531 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002532 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002533 CHECK(array_iftable != nullptr);
2534 new_class->SetIfTable(array_iftable);
2535 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002536
Elliott Hughes00626c22013-06-14 15:04:14 -07002537 // Inherit access flags from the component type.
2538 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2539 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2540 access_flags &= kAccJavaFlagsMask;
2541 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002542 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002543 access_flags |= kAccAbstract | kAccFinal;
2544 access_flags &= ~kAccInterface;
2545
2546 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002547
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002548 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002549 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002550 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002551 }
2552 // Another thread must have loaded the class after we
2553 // started but before we finished. Abandon what we've
2554 // done.
2555 //
2556 // (Yes, this happens.)
2557
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002558 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002559}
2560
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002561mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002562 switch (type) {
2563 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002564 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002565 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002566 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002567 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002568 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002569 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002570 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002571 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002572 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002573 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002574 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002575 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002576 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002577 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002578 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002579 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002580 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002581 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002582 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002583 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002584 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002585 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002586 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002587}
2588
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002589mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass, size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002590 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002591 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002592 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002593 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08002594 source += " from ";
2595 source += dex_cache->GetLocation()->ToModifiedUtf8();
2596 }
2597 LOG(INFO) << "Loaded class " << descriptor << source;
2598 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002599 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002600 mirror::ClassLoader* const class_loader = klass->GetClassLoader();
2601 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
2602 mirror::Class* existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002603 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002604 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002605 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002606 if (kIsDebugBuild && !klass->IsTemp() && class_loader == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002607 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002608 // Check a class loaded with the system class loader matches one in the image if the class
2609 // is in the image.
2610 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002611 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002612 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002613 }
2614 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002615 VerifyObject(klass);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002616 class_table->InsertWithHash(klass, hash);
Mathieu Chartiere4275c02015-08-06 15:34:15 -07002617 if (class_loader != nullptr) {
2618 // This is necessary because we need to have the card dirtied for remembered sets.
2619 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
2620 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08002621 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002622 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002623 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002624 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002625}
2626
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002627void ClassLinker::UpdateClassVirtualMethods(mirror::Class* klass,
2628 LengthPrefixedArray<ArtMethod>* new_methods) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002629 klass->SetVirtualMethodsPtr(new_methods);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002630 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07002631 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002632}
2633
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002634bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002635 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002636 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
2637 return class_table != nullptr && class_table->Remove(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08002638}
2639
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002640mirror::Class* ClassLinker::LookupClass(Thread* self,
2641 const char* descriptor,
2642 size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002643 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002644 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002645 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002646 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
2647 if (class_table != nullptr) {
2648 mirror::Class* result = class_table->Lookup(descriptor, hash);
2649 if (result != nullptr) {
2650 return result;
2651 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002652 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07002653 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002654 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
2655 return nullptr;
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002656 }
2657 // Lookup failed but need to search dex_caches_.
2658 mirror::Class* result = LookupClassFromImage(descriptor);
2659 if (result != nullptr) {
2660 result = InsertClass(descriptor, result, hash);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002661 } else {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002662 // Searching the image dex files/caches failed, we don't want to get into this situation
2663 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2664 // classes into the class table.
2665 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
2666 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2667 MoveImageClassesToClassTable();
Ian Rogers5d76c432011-10-31 21:42:49 -07002668 }
2669 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002670 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002671}
2672
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002673static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
Mathieu Chartier90443472015-07-16 20:32:27 -07002674 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002675 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002676 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002677 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2678 return root->AsObjectArray<mirror::DexCache>();
2679}
2680
2681void ClassLinker::MoveImageClassesToClassTable() {
2682 Thread* self = Thread::Current();
2683 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2684 if (!dex_cache_image_class_lookup_required_) {
2685 return; // All dex cache classes are already in the class table.
2686 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002687 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002688 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002689 std::string temp;
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002690 ClassTable* const class_table = InsertClassTableForClassLoader(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002691 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2692 mirror::DexCache* dex_cache = dex_caches->Get(i);
Vladimir Marko05792b92015-08-03 11:56:49 +01002693 GcRoot<mirror::Class>* types = dex_cache->GetResolvedTypes();
2694 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
2695 mirror::Class* klass = types[j].Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002696 if (klass != nullptr) {
2697 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002698 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002699 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002700 mirror::Class* existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002701 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002702 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002703 << PrettyClassAndClassLoader(klass);
2704 } else {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002705 class_table->Insert(klass);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002706 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002707 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002708 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002709 }
2710 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002711 }
2712 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002713 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002714}
2715
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002716class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
2717 public:
2718 explicit MoveClassTableToPreZygoteVisitor() {}
2719
2720 void Visit(mirror::ClassLoader* class_loader)
2721 REQUIRES(Locks::classlinker_classes_lock_)
2722 SHARED_REQUIRES(Locks::mutator_lock_) OVERRIDE {
2723 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07002724 if (class_table != nullptr) {
2725 class_table->FreezeSnapshot();
2726 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002727 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002728};
2729
2730void ClassLinker::MoveClassTableToPreZygote() {
2731 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2732 boot_class_table_.FreezeSnapshot();
2733 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002734 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002735}
2736
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002737mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002738 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002739 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2740 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
2741 mirror::DexCache* dex_cache = dex_caches->Get(i);
2742 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00002743 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002744 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002745 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002746 const DexFile::TypeId* type_id =
2747 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002748 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002749 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
2750 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002751 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002752 return klass;
2753 }
2754 }
2755 }
2756 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002757 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002758}
2759
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002760// Look up classes by hash and descriptor and put all matching ones in the result array.
2761class LookupClassesVisitor : public ClassLoaderVisitor {
2762 public:
2763 LookupClassesVisitor(const char* descriptor, size_t hash, std::vector<mirror::Class*>* result)
2764 : descriptor_(descriptor),
2765 hash_(hash),
2766 result_(result) {}
2767
2768 void Visit(mirror::ClassLoader* class_loader)
2769 SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
2770 ClassTable* const class_table = class_loader->GetClassTable();
2771 mirror::Class* klass = class_table->Lookup(descriptor_, hash_);
2772 if (klass != nullptr) {
2773 result_->push_back(klass);
2774 }
2775 }
2776
2777 private:
2778 const char* const descriptor_;
2779 const size_t hash_;
2780 std::vector<mirror::Class*>* const result_;
2781};
2782
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002783void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002784 result.clear();
2785 if (dex_cache_image_class_lookup_required_) {
2786 MoveImageClassesToClassTable();
2787 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002788 Thread* const self = Thread::Current();
2789 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002790 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
2791 mirror::Class* klass = boot_class_table_.Lookup(descriptor, hash);
2792 if (klass != nullptr) {
2793 result.push_back(klass);
2794 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002795 LookupClassesVisitor visitor(descriptor, hash, &result);
2796 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002797}
2798
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002799void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002800 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002801 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08002802
Ian Rogers9ffb0392012-09-10 11:56:50 -07002803 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002804 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07002805 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07002806 return;
2807 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002808 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002809 return;
2810 }
jeffhao98eacac2011-09-14 16:11:53 -07002811
Ian Rogers9ffb0392012-09-10 11:56:50 -07002812 // The class might already be erroneous, for example at compile time if we attempted to verify
2813 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002814 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002815 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002816 return;
2817 }
2818
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002819 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002820 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002821 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002822 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002823 << PrettyClass(klass.Get());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002824 CHECK(!Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002825 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002826 }
jeffhao98eacac2011-09-14 16:11:53 -07002827
Igor Murashkin7617abd2015-07-10 18:27:47 -07002828 // Skip verification if we are forcing a soft fail.
2829 // This has to be before the normal verification enabled check,
2830 // since technically verification is disabled in this mode.
2831 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
2832 // Force verification to be a 'soft failure'.
2833 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
2834 // As this is a fake verified status, make sure the methods are _not_ marked preverified
2835 // later.
2836 klass->SetPreverified();
2837 return;
2838 }
2839
Jeff Hao4a200f52014-04-01 14:58:49 -07002840 // Skip verification if disabled.
2841 if (!Runtime::Current()->IsVerificationEnabled()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002842 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07002843 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07002844 return;
2845 }
2846
Ian Rogers9ffb0392012-09-10 11:56:50 -07002847 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002848 StackHandleScope<2> hs(self);
2849 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002850 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07002851 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002852 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002853
2854 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002855 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002856 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002857 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07002858 std::string error_msg(
2859 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
2860 PrettyDescriptor(klass.Get()).c_str(),
2861 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08002862 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002863 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002864 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002865 self->ClearException();
2866 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002867 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
2868 if (cause.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002869 self->GetException()->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002870 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08002871 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002872 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00002873 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
2874 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002875 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002876 return;
2877 }
2878 }
2879
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002880 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07002881 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002882 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002883 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002884 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002885 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002886 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002887 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002888 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
2889 PrettyDescriptor(klass.Get()).c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002890 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07002891 return;
2892 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002893 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08002894 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07002895 if (!preverified) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002896 verifier_failure = verifier::MethodVerifier::VerifyClass(self,
2897 klass.Get(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002898 Runtime::Current()->IsAotCompiler(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002899 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002900 }
2901 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07002902 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002903 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07002904 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2905 << " because: " << error_msg;
2906 }
Ian Rogers1f539342012-10-03 21:09:42 -07002907 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002908 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002909 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002910 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002911 // Even though there were no verifier failures we need to respect whether the super-class
2912 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002913 if (super.Get() == nullptr || super->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002914 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002915 } else {
2916 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002917 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002918 // Pretend a soft failure occured so that we don't consider the class verified below.
2919 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002920 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002921 } else {
2922 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
2923 // Soft failures at compile time should be retried at runtime. Soft
2924 // failures at runtime will be handled by slow paths in the generated
2925 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002926 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002927 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002928 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002929 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002930 // As this is a fake verified status, make sure the methods are _not_ marked preverified
2931 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07002932 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002933 }
2934 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07002935 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002936 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08002937 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2938 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002939 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002940 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002941 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002942 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002943 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002944 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002945 // Let the interpreter know it by setting the kAccPreverified flag onto each
2946 // method.
2947 // Note: we're going here during compilation and at runtime. When we set the
2948 // kAccPreverified flag when compiling image classes, the flag is recorded
2949 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07002950 EnsurePreverifiedMethods(klass);
2951 }
2952}
2953
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002954void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002955 if (!klass->IsPreverified()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002956 klass->SetPreverifiedFlagOnAllMethods(image_pointer_size_);
Ian Rogers7b078e82014-09-10 14:44:24 -07002957 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002958 }
jeffhao98eacac2011-09-14 16:11:53 -07002959}
2960
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002961bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
2962 mirror::Class* klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002963 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002964 // If we're compiling, we can only verify the class using the oat file if
2965 // we are not compiling the image or if the class we're verifying is not part of
2966 // the app. In other words, we will only check for preverification of bootclasspath
2967 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002968 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002969 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002970 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002971 return false;
2972 }
2973 // We are compiling an app (not the image).
2974
2975 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002976 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002977 return false;
2978 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002979 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002980
Richard Uhler07b3c232015-03-31 15:57:54 -07002981 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002982 // In case we run without an image there won't be a backing oat file.
2983 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07002984 return false;
2985 }
2986
Andreas Gampe76bd8802014-12-10 16:43:58 -08002987 // We may be running with a preopted oat file but without image. In this case,
2988 // we don't skip verification of preverified classes to ensure we initialize
2989 // dex caches with all types resolved during verification.
2990 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
2991 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
2992 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
2993 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002994 if (!Runtime::Current()->IsAotCompiler() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08002995 !Runtime::Current()->GetHeap()->HasImageSpace() &&
2996 klass->GetClassLoader() != nullptr) {
2997 return false;
2998 }
2999
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003000 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003001 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003002 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3003 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003004 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003005 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003006 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003007 // Compile time verification failed with a soft error. Compile time verification can fail
3008 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003009 // class ... {
3010 // Foo x;
3011 // .... () {
3012 // if (...) {
3013 // v1 gets assigned a type of resolved class Foo
3014 // } else {
3015 // v1 gets assigned a type of unresolved class Bar
3016 // }
3017 // iput x = v1
3018 // } }
3019 // when we merge v1 following the if-the-else it results in Conflict
3020 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3021 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3022 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3023 // at compile time).
3024 return false;
3025 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003026 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003027 // Compile time verification failed with a hard error. This is caused by invalid instructions
3028 // in the class. These errors are unrecoverable.
3029 return false;
3030 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003031 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003032 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3033 // not loading the class.
3034 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3035 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003036 return false;
3037 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003038 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003039 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003040 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003041 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003042 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003043}
3044
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003045void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003046 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003047 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003048 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i, image_pointer_size_));
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003049 }
3050 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003051 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i, image_pointer_size_));
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003052 }
3053}
3054
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003055void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003056 ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003057 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3058 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003059 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003060 return; // native or abstract method
3061 }
3062 if (code_item->tries_size_ == 0) {
3063 return; // nothing to process
3064 }
Ian Rogers13735952014-10-08 12:43:28 -07003065 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003066 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003067 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3068 CatchHandlerIterator iterator(handlers_ptr);
3069 for (; iterator.HasNext(); iterator.Next()) {
3070 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3071 // unresolved exception types will be ignored by exception delivery
3072 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Mathieu Chartier90443472015-07-16 20:32:27 -07003073 mirror::Class* exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003074 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003075 DCHECK(Thread::Current()->IsExceptionPending());
3076 Thread::Current()->ClearException();
3077 }
3078 }
3079 }
3080 handlers_ptr = iterator.EndDataPointer();
3081 }
3082}
3083
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003084mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
3085 jstring name,
3086 jobjectArray interfaces,
3087 jobject loader,
3088 jobjectArray methods,
3089 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003090 Thread* self = soa.Self();
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003091 StackHandleScope<10> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003092 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003093 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003094 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003095 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003096 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003097 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003098 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003099 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003100 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3101 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003102 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003103 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003104 klass->SetName(soa.Decode<mirror::String*>(name));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003105 klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003106 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003107 std::string descriptor(GetDescriptorForProxy(klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003108 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003109
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003110 // Needs to be before we insert the class so that the allocator field is set.
3111 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(klass->GetClassLoader());
3112
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003113 // Insert the class before loading the fields as the field roots
3114 // (ArtField::declaring_class_) are only visited from the class
3115 // table. There can't be any suspend points between inserting the
3116 // class and setting the field arrays below.
3117 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), hash);
3118 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003119
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003120 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07003121 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003122 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003123 klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003124
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003125 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3126 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003127 ArtField& interfaces_sfield = sfields->At(0);
3128 interfaces_sfield.SetDexFieldIndex(0);
3129 interfaces_sfield.SetDeclaringClass(klass.Get());
3130 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003131
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003132 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003133 ArtField& throws_sfield = sfields->At(1);
3134 throws_sfield.SetDexFieldIndex(1);
3135 throws_sfield.SetDeclaringClass(klass.Get());
3136 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003137
Ian Rogers466bb252011-10-14 03:29:56 -07003138 // Proxies have 1 direct method, the constructor
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003139 LengthPrefixedArray<ArtMethod>* directs = AllocArtMethodArray(self, allocator, 1);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003140 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
3141 // want to throw OOM in the future.
3142 if (UNLIKELY(directs == nullptr)) {
3143 self->AssertPendingOOMException();
3144 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003145 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003146 klass->SetDirectMethodsPtr(directs);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003147 CreateProxyConstructor(klass, klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04003148
Mathieu Chartier590fee92013-09-13 13:46:47 -07003149 // Create virtual method using specified prototypes.
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003150 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>*>(methods));
3151 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003152 << PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003153 const size_t num_virtual_methods = h_methods->GetLength();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003154 auto* virtuals = AllocArtMethodArray(self, allocator, num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003155 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
3156 // want to throw OOM in the future.
3157 if (UNLIKELY(virtuals == nullptr)) {
3158 self->AssertPendingOOMException();
3159 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003160 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003161 klass->SetVirtualMethodsPtr(virtuals);
Jesse Wilson95caa792011-10-12 18:14:17 -04003162 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003163 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
3164 auto* prototype = h_methods->Get(i)->GetArtMethod();
3165 CreateProxyMethod(klass, prototype, virtual_method);
3166 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
3167 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04003168 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003169
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003170 // The super class is java.lang.reflect.Proxy
3171 klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy));
3172 // Now effectively in the loaded state.
3173 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08003174 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003175
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003176 MutableHandle<mirror::Class> new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07003177 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003178 // Must hold lock on object when resolved.
3179 ObjectLock<mirror::Class> resolution_lock(self, klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003180 // Link the fields and virtual methods, creating vtable and iftables.
3181 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003182 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003183 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003184 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003185 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003186 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003187 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003188 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003189 CHECK(klass->IsRetired());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003190 CHECK_NE(klass.Get(), new_class.Get());
3191 klass.Assign(new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003192
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003193 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
3194 interfaces_sfield.SetObject<false>(klass.Get(),
3195 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
3196 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
3197 throws_sfield.SetObject<false>(
3198 klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003199
3200 {
3201 // Lock on klass is released. Lock new class object.
3202 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003203 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003204 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003205
3206 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003207 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003208 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003209 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
3210
Ian Rogersc2b44472011-12-14 21:17:17 -08003211 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003212 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
3213 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003214 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003215 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003216
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003217 StackHandleScope<1> hs2(self);
3218 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String*>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003219 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003220 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003221 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3222
3223 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003224 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003225 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003226
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003227 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003228 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003229 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003230 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003231 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003232 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003233}
3234
Ian Rogersef7d42f2014-01-06 12:55:46 -08003235std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003236 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003237 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003238 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003239 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3240}
3241
Mathieu Chartier4e2cb092015-07-22 16:17:51 -07003242ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class, ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003243 DCHECK(proxy_class->IsProxyClass());
3244 DCHECK(proxy_method->IsProxyMethod());
Ian Rogers16f93672012-02-14 12:29:06 -08003245 {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003246 Thread* const self = Thread::Current();
3247 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003248 // Locate the dex cache of the original interface/Object
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003249 for (jobject weak_root : dex_caches_) {
3250 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
3251 if (dex_cache != nullptr &&
Vladimir Marko05792b92015-08-03 11:56:49 +01003252 proxy_method->HasSameDexCacheResolvedTypes(dex_cache->GetResolvedTypes(),
3253 image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003254 ArtMethod* resolved_method = dex_cache->GetResolvedMethod(
3255 proxy_method->GetDexMethodIndex(), image_pointer_size_);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003256 CHECK(resolved_method != nullptr);
3257 return resolved_method;
Ian Rogers16f93672012-02-14 12:29:06 -08003258 }
3259 }
3260 }
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003261 LOG(FATAL) << "Didn't find dex cache for " << PrettyClass(proxy_class) << " "
3262 << PrettyMethod(proxy_method);
3263 UNREACHABLE();
Ian Rogers16f93672012-02-14 12:29:06 -08003264}
3265
Mathieu Chartiere401d142015-04-22 13:56:20 -07003266void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
3267 // Create constructor for Proxy that must initialize the method.
3268 CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 16u);
3269 ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->GetDirectMethodUnchecked(
3270 2, image_pointer_size_);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003271 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3272 // constructor method.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003273 GetClassRoot(kJavaLangReflectProxy)->GetDexCache()->SetResolvedMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -07003274 proxy_constructor->GetDexMethodIndex(), proxy_constructor, image_pointer_size_);
Jeff Haodb8a6642014-08-14 17:18:52 -07003275 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3276 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07003277 DCHECK(out != nullptr);
3278 out->CopyFrom(proxy_constructor, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07003279 // Make this constructor public and fix the class to be our Proxy version
Mathieu Chartiere401d142015-04-22 13:56:20 -07003280 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) | kAccPublic);
3281 out->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003282}
3283
Mathieu Chartiere401d142015-04-22 13:56:20 -07003284void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07003285 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07003286 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
3287 CHECK_STREQ(np->GetName(), "<init>");
3288 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003289 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003290}
3291
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003292void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003293 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003294 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3295 // prototype method
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003296 auto* dex_cache = prototype->GetDeclaringClass()->GetDexCache();
3297 // Avoid dirtying the dex cache unless we need to.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003298 if (dex_cache->GetResolvedMethod(prototype->GetDexMethodIndex(), image_pointer_size_) !=
3299 prototype) {
3300 dex_cache->SetResolvedMethod(
3301 prototype->GetDexMethodIndex(), prototype, image_pointer_size_);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003302 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003303 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003304 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07003305 DCHECK(out != nullptr);
3306 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07003307
3308 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3309 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiere401d142015-04-22 13:56:20 -07003310 out->SetDeclaringClass(klass.Get());
3311 out->SetAccessFlags((out->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003312
Ian Rogers466bb252011-10-14 03:29:56 -07003313 // At runtime the method looks like a reference and argument saving method, clone the code
3314 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003315 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08003316}
Jesse Wilson95caa792011-10-12 18:14:17 -04003317
Mathieu Chartiere401d142015-04-22 13:56:20 -07003318void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07003319 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003320 CHECK(!prototype->IsFinal());
3321 CHECK(method->IsFinal());
3322 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003323
3324 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3325 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Vladimir Marko05792b92015-08-03 11:56:49 +01003326 CHECK(prototype->HasSameDexCacheResolvedMethods(method, image_pointer_size_));
3327 CHECK(prototype->HasSameDexCacheResolvedTypes(method, image_pointer_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07003328 auto* np = method->GetInterfaceMethodIfProxy(image_pointer_size_);
3329 CHECK_EQ(prototype->GetDeclaringClass()->GetDexCache(), np->GetDexCache());
Ian Rogers19846512012-02-24 11:42:47 -08003330 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3331
Mathieu Chartiere401d142015-04-22 13:56:20 -07003332 CHECK_STREQ(np->GetName(), prototype->GetName());
3333 CHECK_STREQ(np->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003334 // More complex sanity - via dex cache
Vladimir Marko05792b92015-08-03 11:56:49 +01003335 CHECK_EQ(np->GetReturnType(true /* resolve */, image_pointer_size_),
3336 prototype->GetReturnType(true /* resolve */, image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04003337}
3338
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003339bool ClassLinker::CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003340 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003341 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003342 return true;
3343 }
3344 if (!can_init_statics) {
3345 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07003346 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003347 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003348 return false;
3349 }
3350 // Check if there are encoded static values needing initialization.
3351 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003352 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003353 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003354 if (dex_class_def->static_values_off_ != 0) {
3355 return false;
3356 }
3357 }
Alex Lighteb7c1442015-08-31 13:17:42 -07003358 // If we are a class we need to initialize all interfaces with default methods when we are
3359 // initialized. Check all of them.
3360 if (!klass->IsInterface()) {
3361 size_t num_interfaces = klass->GetIfTableCount();
3362 for (size_t i = 0; i < num_interfaces; i++) {
3363 mirror::Class* iface = klass->GetIfTable()->GetInterface(i);
3364 if (iface->HasDefaultMethods() &&
3365 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
3366 return false;
3367 }
3368 }
3369 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003370 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003371 if (klass->IsInterface() || !klass->HasSuperClass()) {
3372 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003373 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003374 mirror::Class* super_class = klass->GetSuperClass();
3375 if (!can_init_parents && !super_class->IsInitialized()) {
3376 return false;
3377 }
3378 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003379}
3380
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003381bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
3382 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003383 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3384
3385 // Are we already initialized and therefore done?
3386 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3387 // an initialized class will never change its state.
3388 if (klass->IsInitialized()) {
3389 return true;
3390 }
3391
3392 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003393 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003394 return false;
3395 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003396
Ian Rogers7b078e82014-09-10 14:44:24 -07003397 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003398 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003399 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003400 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003401
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003402 // Re-check under the lock in case another thread initialized ahead of us.
3403 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003404 return true;
3405 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003406
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003407 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003408 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003409 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003410 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003411 return false;
3412 }
3413
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003414 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003415
3416 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003417 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003418 if (!klass->IsVerified()) {
3419 // We failed to verify, expect either the klass to be erroneous or verification failed at
3420 // compile time.
3421 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003422 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003423 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003424 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003425 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003426 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003427 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003428 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07003429 } else {
3430 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003431 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003432 }
3433
Brian Carlstromd1422f82011-09-28 11:37:09 -07003434 // If the class is kStatusInitializing, either this thread is
3435 // initializing higher up the stack or another thread has beat us
3436 // to initializing and we need to wait. Either way, this
3437 // invocation of InitializeClass will not be responsible for
3438 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003439 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07003440 // Could have got an exception during verification.
3441 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003442 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003443 return false;
3444 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003445 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003446 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003447 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003448 return true;
3449 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003450 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003451 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003452 }
3453
3454 if (!ValidateSuperClassDescriptors(klass)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003455 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003456 return false;
3457 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003458 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003459
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003460 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003461
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003462 // From here out other threads may observe that we're initializing and so changes of state
3463 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003464 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003465 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003466
3467 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003468 }
3469
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003470 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003471 if (!klass->IsInterface() && klass->HasSuperClass()) {
3472 mirror::Class* super_class = klass->GetSuperClass();
3473 if (!super_class->IsInitialized()) {
3474 CHECK(!super_class->IsInterface());
3475 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003476 StackHandleScope<1> hs(self);
3477 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07003478 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003479 if (!super_initialized) {
3480 // The super class was verified ahead of entering initializing, we should only be here if
3481 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003482 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003483 << "Super class initialization failed for "
3484 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003485 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003486 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003487 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003488 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003489 // Initialization failed because the super-class is erroneous.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003490 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003491 return false;
3492 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003493 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003494 }
3495
Alex Lighteb7c1442015-08-31 13:17:42 -07003496 if (!klass->IsInterface()) {
3497 // Initialize interfaces with default methods for the JLS.
3498 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07003499 // Only setup the (expensive) handle scope if we actually need to.
3500 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07003501 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07003502 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
3503 for (size_t i = 0; i < num_direct_interfaces; i++) {
3504 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass, i));
3505 CHECK(handle_scope_iface.Get() != nullptr);
3506 CHECK(handle_scope_iface->IsInterface());
3507 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
3508 // We have already done this for this interface. Skip it.
3509 continue;
3510 }
3511 // We cannot just call initialize class directly because we need to ensure that ALL
3512 // interfaces with default methods are initialized. Non-default interface initialization
3513 // will not affect other non-default super-interfaces.
3514 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
3515 handle_scope_iface,
3516 can_init_statics,
3517 can_init_parents);
3518 if (!iface_initialized) {
3519 ObjectLock<mirror::Class> lock(self, klass);
3520 // Initialization failed because one of our interfaces with default methods is erroneous.
3521 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
3522 return false;
3523 }
Alex Lighteb7c1442015-08-31 13:17:42 -07003524 }
3525 }
3526 }
3527
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003528 const size_t num_static_fields = klass->NumStaticFields();
3529 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003530 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003531 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003532 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07003533 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003534 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003535 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003536
3537 // Eagerly fill in static fields so that the we don't have to do as many expensive
3538 // Class::FindStaticField in ResolveField.
3539 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003540 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003541 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003542 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003543 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003544 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07003545 } else {
3546 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003547 }
3548 }
3549
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003550 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
3551 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07003552 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003553 ClassDataItemIterator field_it(dex_file, class_data);
3554 if (value_it.HasNext()) {
3555 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003556 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003557 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003558 ArtField* field = ResolveField(
3559 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003560 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003561 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003562 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003563 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003564 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003565 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003566 }
3567 }
3568 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003569
Mathieu Chartiere401d142015-04-22 13:56:20 -07003570 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003571 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003572 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003573 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003574 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003575 }
3576
Ian Rogers7b078e82014-09-10 14:44:24 -07003577 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003578 uint64_t t1 = NanoTime();
3579
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003580 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003581 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003582 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003583
3584 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003585 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003586 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003587 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003588 } else if (Runtime::Current()->IsTransactionAborted()) {
3589 // The exception thrown when the transaction aborted has been caught and cleared
3590 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01003591 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
3592 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02003593 Runtime::Current()->ThrowTransactionAbortError(self);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003594 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003595 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003596 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003597 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3598 RuntimeStats* thread_stats = self->GetStats();
3599 ++global_stats->class_init_count;
3600 ++thread_stats->class_init_count;
3601 global_stats->class_init_time_ns += (t1 - t0);
3602 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003603 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003604 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003605 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003606 std::string temp;
3607 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003608 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003609 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003610 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003611 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003612 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003613 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003614 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003615}
3616
Alex Lighteb7c1442015-08-31 13:17:42 -07003617// We recursively run down the tree of interfaces. We need to do this in the order they are declared
3618// and perform the initialization only on those interfaces that contain default methods.
3619bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
3620 Handle<mirror::Class> iface,
3621 bool can_init_statics,
3622 bool can_init_parents) {
3623 CHECK(iface->IsInterface());
3624 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07003625 // Only create the (expensive) handle scope if we need it.
3626 if (UNLIKELY(num_direct_ifaces > 0)) {
3627 StackHandleScope<1> hs(self);
3628 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
3629 // First we initialize all of iface's super-interfaces recursively.
3630 for (size_t i = 0; i < num_direct_ifaces; i++) {
3631 mirror::Class* super_iface = mirror::Class::GetDirectInterface(self, iface, i);
3632 if (!super_iface->HasBeenRecursivelyInitialized()) {
3633 // Recursive step
3634 handle_super_iface.Assign(super_iface);
3635 if (!InitializeDefaultInterfaceRecursive(self,
3636 handle_super_iface,
3637 can_init_statics,
3638 can_init_parents)) {
3639 return false;
3640 }
Alex Lighteb7c1442015-08-31 13:17:42 -07003641 }
3642 }
3643 }
3644
3645 bool result = true;
3646 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
3647 // initialize if we don't have default methods.
3648 if (iface->HasDefaultMethods()) {
3649 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
3650 }
3651
3652 // Mark that this interface has undergone recursive default interface initialization so we know we
3653 // can skip it on any later class initializations. We do this even if we are not a default
3654 // interface since we can still avoid the traversal. This is purely a performance optimization.
3655 if (result) {
3656 // TODO This should be done in a better way
3657 ObjectLock<mirror::Class> lock(self, iface);
3658 iface->SetRecursivelyInitialized();
3659 }
3660 return result;
3661}
3662
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003663bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
3664 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003665 ObjectLock<mirror::Class>& lock)
Mathieu Chartier90443472015-07-16 20:32:27 -07003666 SHARED_REQUIRES(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003667 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003668 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003669 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003670 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003671
3672 // When we wake up, repeat the test for init-in-progress. If
3673 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07003674 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003675 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003676 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003677 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003678 return false;
3679 }
3680 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003681 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003682 continue;
3683 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003684 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
3685 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003686 // Compile time initialization failed.
3687 return false;
3688 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003689 if (klass->IsErroneous()) {
3690 // The caller wants an exception, but it was thrown in a
3691 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003692 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003693 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003694 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003695 return false;
3696 }
3697 if (klass->IsInitialized()) {
3698 return true;
3699 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003700 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003701 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003702 }
Ian Rogers07140832014-09-30 15:43:59 -07003703 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003704}
3705
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003706static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
3707 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003708 ArtMethod* method,
3709 ArtMethod* m)
Mathieu Chartier90443472015-07-16 20:32:27 -07003710 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003711 DCHECK(Thread::Current()->IsExceptionPending());
3712 DCHECK(!m->IsProxyMethod());
3713 const DexFile* dex_file = m->GetDexFile();
3714 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
3715 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
3716 uint16_t return_type_idx = proto_id.return_type_idx_;
3717 std::string return_type = PrettyType(return_type_idx, *dex_file);
3718 std::string class_loader = PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
3719 ThrowWrappedLinkageError(klass.Get(),
3720 "While checking class %s method %s signature against %s %s: "
3721 "Failed to resolve return type %s with %s",
3722 PrettyDescriptor(klass.Get()).c_str(),
Mathieu Chartiere401d142015-04-22 13:56:20 -07003723 PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003724 super_klass->IsInterface() ? "interface" : "superclass",
3725 PrettyDescriptor(super_klass.Get()).c_str(),
3726 return_type.c_str(), class_loader.c_str());
3727}
3728
3729static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
3730 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003731 ArtMethod* method,
3732 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003733 uint32_t index,
3734 uint32_t arg_type_idx)
Mathieu Chartier90443472015-07-16 20:32:27 -07003735 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003736 DCHECK(Thread::Current()->IsExceptionPending());
3737 DCHECK(!m->IsProxyMethod());
3738 const DexFile* dex_file = m->GetDexFile();
3739 std::string arg_type = PrettyType(arg_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 arg %u 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 index, arg_type.c_str(), class_loader.c_str());
3749}
3750
3751static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
3752 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003753 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003754 const std::string& error_msg)
Mathieu Chartier90443472015-07-16 20:32:27 -07003755 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003756 ThrowLinkageError(klass.Get(),
3757 "Class %s method %s resolves differently in %s %s: %s",
3758 PrettyDescriptor(klass.Get()).c_str(),
Mathieu Chartiere401d142015-04-22 13:56:20 -07003759 PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003760 super_klass->IsInterface() ? "interface" : "superclass",
3761 PrettyDescriptor(super_klass.Get()).c_str(),
3762 error_msg.c_str());
3763}
3764
Ian Rogersb5fb2072014-12-02 17:22:02 -08003765static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Marko05792b92015-08-03 11:56:49 +01003766 size_t pointer_size,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003767 Handle<mirror::Class> klass,
3768 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003769 ArtMethod* method1,
3770 ArtMethod* method2)
Mathieu Chartier90443472015-07-16 20:32:27 -07003771 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003772 {
3773 StackHandleScope<1> hs(self);
Vladimir Marko05792b92015-08-03 11:56:49 +01003774 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType(true /* resolve */,
3775 pointer_size)));
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003776 if (UNLIKELY(return_type.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003777 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003778 return false;
3779 }
Vladimir Marko05792b92015-08-03 11:56:49 +01003780 mirror::Class* other_return_type = method2->GetReturnType(true /* resolve */,
3781 pointer_size);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003782 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003783 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003784 return false;
3785 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00003786 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003787 ThrowSignatureMismatch(klass, super_klass, method1,
3788 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
3789 PrettyClassAndClassLoader(return_type.Get()).c_str(),
3790 return_type.Get(),
3791 PrettyClassAndClassLoader(other_return_type).c_str(),
3792 other_return_type));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003793 return false;
3794 }
3795 }
3796 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
3797 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
3798 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003799 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003800 ThrowSignatureMismatch(klass, super_klass, method1,
3801 StringPrintf("Type list mismatch with %s",
Mathieu Chartiere401d142015-04-22 13:56:20 -07003802 PrettyMethod(method2, true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003803 return false;
3804 }
3805 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003806 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003807 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003808 ThrowSignatureMismatch(klass, super_klass, method1,
3809 StringPrintf("Type list mismatch with %s",
Mathieu Chartiere401d142015-04-22 13:56:20 -07003810 PrettyMethod(method2, true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003811 return false;
3812 }
3813 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003814 }
3815 uint32_t num_types = types1->Size();
3816 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003817 ThrowSignatureMismatch(klass, super_klass, method1,
3818 StringPrintf("Type list mismatch with %s",
Mathieu Chartiere401d142015-04-22 13:56:20 -07003819 PrettyMethod(method2, true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003820 return false;
3821 }
3822 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00003823 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003824 uint32_t param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00003825 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Marko05792b92015-08-03 11:56:49 +01003826 method1->GetClassFromTypeIndex(param_type_idx, true /* resolve */, pointer_size)));
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003827 if (UNLIKELY(param_type.Get() == nullptr)) {
3828 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003829 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003830 return false;
3831 }
3832 uint32_t other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003833 mirror::Class* other_param_type =
Vladimir Marko05792b92015-08-03 11:56:49 +01003834 method2->GetClassFromTypeIndex(other_param_type_idx, true /* resolve */, pointer_size);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003835 if (UNLIKELY(other_param_type == nullptr)) {
3836 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003837 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003838 return false;
3839 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00003840 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003841 ThrowSignatureMismatch(klass, super_klass, method1,
3842 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
3843 i,
3844 PrettyClassAndClassLoader(param_type.Get()).c_str(),
3845 param_type.Get(),
3846 PrettyClassAndClassLoader(other_param_type).c_str(),
3847 other_param_type));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003848 return false;
3849 }
3850 }
3851 return true;
3852}
3853
3854
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003855bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003856 if (klass->IsInterface()) {
3857 return true;
3858 }
Ian Rogers151f2212014-05-06 11:27:27 -07003859 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07003860 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003861 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003862 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003863 if (klass->HasSuperClass() &&
3864 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003865 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003866 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003867 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
3868 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
3869 if (m != super_m) {
Vladimir Marko05792b92015-08-03 11:56:49 +01003870 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, image_pointer_size_,
3871 klass, super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003872 m, super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003873 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003874 return false;
3875 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003876 }
3877 }
3878 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003879 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003880 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
3881 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
3882 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07003883 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003884 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
3885 j, image_pointer_size_);
3886 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
3887 if (m != super_m) {
Vladimir Marko05792b92015-08-03 11:56:49 +01003888 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, image_pointer_size_,
3889 klass, super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003890 m, super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01003891 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003892 return false;
3893 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003894 }
3895 }
3896 }
3897 }
3898 return true;
3899}
3900
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003901bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003902 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003903 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003904 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003905 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003906 return true;
3907 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003908 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003909 if (!success) {
3910 if (can_init_fields && can_init_parents) {
3911 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
3912 }
3913 } else {
3914 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08003915 }
3916 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003917}
3918
Mathieu Chartiere401d142015-04-22 13:56:20 -07003919void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class,
3920 mirror::Class* new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003921 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003922 for (ArtField& field : new_class->GetIFields()) {
3923 if (field.GetDeclaringClass() == temp_class) {
3924 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003925 }
3926 }
3927
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003928 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003929 for (ArtField& field : new_class->GetSFields()) {
3930 if (field.GetDeclaringClass() == temp_class) {
3931 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003932 }
3933 }
3934
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003935 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003936 for (auto& method : new_class->GetDirectMethods(image_pointer_size_)) {
3937 if (method.GetDeclaringClass() == temp_class) {
3938 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003939 }
3940 }
3941
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003942 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003943 for (auto& method : new_class->GetVirtualMethods(image_pointer_size_)) {
3944 if (method.GetDeclaringClass() == temp_class) {
3945 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003946 }
3947 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003948
3949 // Make sure the remembered set and mod-union tables know that we updated some of the native
3950 // roots.
3951 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003952}
3953
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003954ClassTable* ClassLinker::InsertClassTableForClassLoader(mirror::ClassLoader* class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07003955 if (class_loader == nullptr) {
3956 return &boot_class_table_;
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003957 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07003958 ClassTable* class_table = class_loader->GetClassTable();
3959 if (class_table == nullptr) {
3960 class_table = new ClassTable;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07003961 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003962 ClassLoaderData data;
3963 data.weak_root = self->GetJniEnv()->vm->AddWeakGlobalRef(self, class_loader);
3964 data.class_table = class_table;
Mathieu Chartier6b069532015-08-05 15:08:12 -07003965 // Don't already have a class table, add it to the class loader.
Mathieu Chartierc3fcd412015-09-25 16:54:59 -07003966 CHECK(class_loader->GetClassTable() == nullptr);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003967 class_loader->SetClassTable(data.class_table);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003968 // Should have been set when we registered the dex file.
3969 data.allocator = class_loader->GetAllocator();
3970 CHECK(data.allocator != nullptr);
3971 class_loaders_.push_back(data);
Mathieu Chartier6b069532015-08-05 15:08:12 -07003972 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003973 return class_table;
3974}
3975
3976ClassTable* ClassLinker::ClassTableForClassLoader(mirror::ClassLoader* class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07003977 return class_loader == nullptr ? &boot_class_table_ : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07003978}
3979
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003980bool ClassLinker::LinkClass(Thread* self,
3981 const char* descriptor,
3982 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003983 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003984 MutableHandle<mirror::Class>* h_new_class_out) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003985 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003986
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003987 if (!LinkSuperClass(klass)) {
3988 return false;
3989 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003990 ArtMethod* imt[mirror::Class::kImtSize];
3991 std::fill_n(imt, arraysize(imt), Runtime::Current()->GetImtUnimplementedMethod());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003992 if (!LinkMethods(self, klass, interfaces, imt)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003993 return false;
3994 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003995 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003996 return false;
3997 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003998 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003999 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004000 return false;
4001 }
4002 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004003 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004004
4005 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4006 // We don't need to retire this class as it has no embedded tables or it was created the
4007 // correct size during class linker initialization.
4008 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4009
4010 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004011 klass->PopulateEmbeddedImtAndVTable(imt, image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004012 }
4013
4014 // This will notify waiters on klass that saw the not yet resolved
4015 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004016 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004017 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004018 } else {
4019 CHECK(!klass->IsResolved());
4020 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004021 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004022 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07004023 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
4024 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
4025 // may not see any references to the target space and clean the card for a class if another
4026 // class had the same array pointer.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004027 klass->SetDirectMethodsPtrUnchecked(nullptr);
4028 klass->SetVirtualMethodsPtr(nullptr);
4029 klass->SetSFieldsPtrUnchecked(nullptr);
4030 klass->SetIFieldsPtrUnchecked(nullptr);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004031 if (UNLIKELY(h_new_class.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004032 self->AssertPendingOOMException();
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004033 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004034 return false;
4035 }
4036
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004037 CHECK_EQ(h_new_class->GetClassSize(), class_size);
4038 ObjectLock<mirror::Class> lock(self, h_new_class);
4039 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004040
4041 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07004042 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004043 mirror::ClassLoader* const class_loader = h_new_class.Get()->GetClassLoader();
4044 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
4045 mirror::Class* existing = table->UpdateClass(descriptor, h_new_class.Get(),
4046 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07004047 if (class_loader != nullptr) {
4048 // We updated the class in the class table, perform the write barrier so that the GC knows
4049 // about the change.
4050 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
4051 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004052 CHECK_EQ(existing, klass.Get());
4053 if (kIsDebugBuild && class_loader == nullptr && dex_cache_image_class_lookup_required_) {
4054 // Check a class loaded with the system class loader matches one in the image if the class
4055 // is in the image.
4056 mirror::Class* const image_class = LookupClassFromImage(descriptor);
4057 if (image_class != nullptr) {
4058 CHECK_EQ(klass.Get(), existing) << descriptor;
4059 }
4060 }
4061 if (log_new_class_table_roots_) {
4062 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
4063 }
4064 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004065
4066 // This will notify waiters on temp class that saw the not yet resolved class in the
4067 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004068 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004069
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004070 CHECK_EQ(h_new_class->GetStatus(), mirror::Class::kStatusResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004071 // This will notify waiters on new_class that saw the not yet resolved
4072 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004073 mirror::Class::SetStatus(h_new_class, mirror::Class::kStatusResolved, self);
4074 // Return the new class.
4075 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004076 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004077 return true;
4078}
4079
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004080static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
4081 size_t* virtual_methods,
4082 size_t* direct_methods,
4083 size_t* static_fields,
4084 size_t* instance_fields) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08004085 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
4086
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004087 while (dex_data.HasNextStaticField()) {
4088 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08004089 (*static_fields)++;
4090 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004091 while (dex_data.HasNextInstanceField()) {
4092 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08004093 (*instance_fields)++;
4094 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004095 while (dex_data.HasNextDirectMethod()) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08004096 (*direct_methods)++;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004097 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08004098 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004099 while (dex_data.HasNextVirtualMethod()) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08004100 (*virtual_methods)++;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004101 dex_data.Next();
Andreas Gampefd9eb392014-11-06 16:52:58 -08004102 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004103 DCHECK(!dex_data.HasNext());
Andreas Gampefd9eb392014-11-06 16:52:58 -08004104}
4105
4106static void DumpClass(std::ostream& os,
4107 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
4108 const char* suffix) {
4109 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
4110 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
4111 os << " Static fields:\n";
4112 while (dex_data.HasNextStaticField()) {
4113 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4114 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4115 dex_data.Next();
4116 }
4117 os << " Instance fields:\n";
4118 while (dex_data.HasNextInstanceField()) {
4119 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4120 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4121 dex_data.Next();
4122 }
4123 os << " Direct methods:\n";
4124 while (dex_data.HasNextDirectMethod()) {
4125 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4126 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4127 dex_data.Next();
4128 }
4129 os << " Virtual methods:\n";
4130 while (dex_data.HasNextVirtualMethod()) {
4131 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4132 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4133 dex_data.Next();
4134 }
4135}
4136
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004137static std::string DumpClasses(const DexFile& dex_file1,
4138 const DexFile::ClassDef& dex_class_def1,
4139 const DexFile& dex_file2,
4140 const DexFile::ClassDef& dex_class_def2) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08004141 std::ostringstream os;
4142 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
4143 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
4144 return os.str();
4145}
4146
4147
4148// Very simple structural check on whether the classes match. Only compares the number of
4149// methods and fields.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004150static bool SimpleStructuralCheck(const DexFile& dex_file1,
4151 const DexFile::ClassDef& dex_class_def1,
4152 const DexFile& dex_file2,
4153 const DexFile::ClassDef& dex_class_def2,
Andreas Gampefd9eb392014-11-06 16:52:58 -08004154 std::string* error_msg) {
4155 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
4156 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
4157
4158 // Counters for current dex file.
4159 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004160 CountMethodsAndFields(dex_data1,
4161 &dex_virtual_methods1,
4162 &dex_direct_methods1,
4163 &dex_static_fields1,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004164 &dex_instance_fields1);
Andreas Gampefd9eb392014-11-06 16:52:58 -08004165 // Counters for compile-time dex file.
4166 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004167 CountMethodsAndFields(dex_data2,
4168 &dex_virtual_methods2,
4169 &dex_direct_methods2,
4170 &dex_static_fields2,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004171 &dex_instance_fields2);
Andreas Gampefd9eb392014-11-06 16:52:58 -08004172
4173 if (dex_virtual_methods1 != dex_virtual_methods2) {
4174 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004175 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s",
4176 dex_virtual_methods1,
4177 dex_virtual_methods2,
4178 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08004179 return false;
4180 }
4181 if (dex_direct_methods1 != dex_direct_methods2) {
4182 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004183 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s",
4184 dex_direct_methods1,
4185 dex_direct_methods2,
4186 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08004187 return false;
4188 }
4189 if (dex_static_fields1 != dex_static_fields2) {
4190 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004191 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s",
4192 dex_static_fields1,
4193 dex_static_fields2,
4194 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08004195 return false;
4196 }
4197 if (dex_instance_fields1 != dex_instance_fields2) {
4198 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004199 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s",
4200 dex_instance_fields1,
4201 dex_instance_fields2,
4202 class_dump.c_str());
Andreas Gampefd9eb392014-11-06 16:52:58 -08004203 return false;
4204 }
4205
4206 return true;
4207}
4208
4209// Checks whether a the super-class changed from what we had at compile-time. This would
4210// invalidate quickening.
4211static bool CheckSuperClassChange(Handle<mirror::Class> klass,
4212 const DexFile& dex_file,
4213 const DexFile::ClassDef& class_def,
4214 mirror::Class* super_class)
Mathieu Chartier90443472015-07-16 20:32:27 -07004215 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampefd9eb392014-11-06 16:52:58 -08004216 // Check for unexpected changes in the superclass.
4217 // Quick check 1) is the super_class class-loader the boot class loader? This always has
4218 // precedence.
4219 if (super_class->GetClassLoader() != nullptr &&
4220 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
4221 // which is implied by different dex cache.
4222 klass->GetDexCache() != super_class->GetDexCache()) {
4223 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
4224 // definition for the super-class, and (b) the files are in separate oat files. The oat files
4225 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
Richard Uhler07b3c232015-03-31 15:57:54 -07004226 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
4227 const OatFile* class_oat_file = nullptr;
4228 if (class_oat_dex_file != nullptr) {
4229 class_oat_file = class_oat_dex_file->GetOatFile();
4230 }
4231
Andreas Gampefd9eb392014-11-06 16:52:58 -08004232 if (class_oat_file != nullptr) {
Richard Uhler07b3c232015-03-31 15:57:54 -07004233 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
4234 const OatFile* loaded_super_oat_file = nullptr;
4235 if (loaded_super_oat_dex_file != nullptr) {
4236 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
4237 }
4238
Andreas Gampefd9eb392014-11-06 16:52:58 -08004239 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
4240 // Now check (a).
4241 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
4242 if (super_class_def != nullptr) {
4243 // Uh-oh, we found something. Do our check.
4244 std::string error_msg;
4245 if (!SimpleStructuralCheck(dex_file, *super_class_def,
4246 super_class->GetDexFile(), *super_class->GetClassDef(),
4247 &error_msg)) {
4248 // Print a warning to the log. This exception might be caught, e.g., as common in test
4249 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
4250 // only save the type of the exception.
4251 LOG(WARNING) << "Incompatible structural change detected: " <<
4252 StringPrintf(
4253 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4254 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4255 class_oat_file->GetLocation().c_str(),
4256 loaded_super_oat_file->GetLocation().c_str(),
4257 error_msg.c_str());
4258 ThrowIncompatibleClassChangeError(klass.Get(),
4259 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4260 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4261 class_oat_file->GetLocation().c_str(),
4262 loaded_super_oat_file->GetLocation().c_str(),
4263 error_msg.c_str());
4264 return false;
4265 }
4266 }
4267 }
4268 }
4269 }
4270 return true;
4271}
4272
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004273bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004274 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004275 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4276 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004277 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004278 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004279 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004280 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004281 return false;
4282 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004283 // Verify
4284 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004285 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004286 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004287 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004288 return false;
4289 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004290 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004291 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08004292
4293 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
4294 DCHECK(Thread::Current()->IsExceptionPending());
4295 return false;
4296 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004297 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004298 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004299 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004300 for (size_t i = 0; i < interfaces->Size(); i++) {
4301 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004302 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004303 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004304 DCHECK(Thread::Current()->IsExceptionPending());
4305 return false;
4306 }
4307 // Verify
4308 if (!klass->CanAccess(interface)) {
4309 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004310 ThrowIllegalAccessError(klass.Get(),
4311 "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004312 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004313 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004314 return false;
4315 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004316 }
4317 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004318 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004319 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004320 return true;
4321}
4322
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004323bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004324 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004325 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004326 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004327 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004328 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004329 return false;
4330 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004331 return true;
4332 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004333 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004334 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4335 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004336 return false;
4337 }
4338 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004339 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004340 ThrowIncompatibleClassChangeError(klass.Get(),
4341 "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004342 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004343 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004344 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004345 return false;
4346 }
4347 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004348 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004349 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004350 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004351 return false;
4352 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004353
Brian Carlstromf3632832014-05-20 15:36:53 -07004354 // Inherit kAccClassIsFinalizable from the superclass in case this
4355 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004356 if (super->IsFinalizable()) {
4357 klass->SetFinalizable();
4358 }
4359
Mathieu Chartiere4275c02015-08-06 15:34:15 -07004360 // Inherit class loader flag form super class.
4361 if (super->IsClassLoaderClass()) {
4362 klass->SetClassLoaderClass();
4363 }
4364
Elliott Hughes2da50362011-10-10 16:57:08 -07004365 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07004366 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07004367 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07004368 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004369 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07004370 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004371 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004372 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004373 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004374 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004375 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004376 return false;
4377 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004378
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004379 if (kIsDebugBuild) {
4380 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004381 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004382 CHECK(super->IsResolved());
4383 super = super->GetSuperClass();
4384 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004385 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004386 return true;
4387}
4388
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004389// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004390bool ClassLinker::LinkMethods(Thread* self,
4391 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004392 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004393 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004394 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07004395 // A map from vtable indexes to the method they need to be updated to point to. Used because we
4396 // need to have default methods be in the virtuals array of each class but we don't set that up
4397 // until LinkInterfaceMethods.
4398 std::unordered_map<size_t, ArtMethod*> default_translations;
4399 // Link virtual methods then interface methods.
4400 // We set up the interface lookup table first because we need it to determine if we need to update
4401 // any vtable entries with new default method implementations.
4402 return SetupInterfaceLookupTable(self, klass, interfaces)
4403 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
4404 && LinkInterfaceMethods(self, klass, default_translations, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004405}
4406
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004407// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4408// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4409// caches in the implementation below.
4410class MethodNameAndSignatureComparator FINAL : public ValueObject {
4411 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07004412 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07004413 SHARED_REQUIRES(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004414 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4415 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004416 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4417 }
4418
4419 const char* GetName() {
4420 if (name_ == nullptr) {
4421 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4422 }
4423 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004424 }
4425
Mathieu Chartiere401d142015-04-22 13:56:20 -07004426 bool HasSameNameAndSignature(ArtMethod* other)
Mathieu Chartier90443472015-07-16 20:32:27 -07004427 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004428 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4429 const DexFile* other_dex_file = other->GetDexFile();
4430 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4431 if (dex_file_ == other_dex_file) {
4432 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4433 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004434 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004435 uint32_t other_name_len;
4436 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4437 &other_name_len);
4438 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4439 return false;
4440 }
4441 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4442 }
4443
4444 private:
4445 // Dex file for the method to compare against.
4446 const DexFile* const dex_file_;
4447 // MethodId for the method to compare against.
4448 const DexFile::MethodId* const mid_;
4449 // Lazily computed name from the dex file's strings.
4450 const char* name_;
4451 // Lazily computed name length.
4452 uint32_t name_len_;
4453};
4454
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004455class LinkVirtualHashTable {
4456 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004457 LinkVirtualHashTable(Handle<mirror::Class> klass,
4458 size_t hash_size,
4459 uint32_t* hash_table,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004460 size_t image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004461 : klass_(klass),
4462 hash_size_(hash_size),
4463 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07004464 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004465 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4466 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004467
Mathieu Chartier90443472015-07-16 20:32:27 -07004468 void Add(uint32_t virtual_method_index) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004469 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
4470 virtual_method_index, image_pointer_size_);
4471 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004472 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004473 uint32_t index = hash % hash_size_;
4474 // Linear probe until we have an empty slot.
4475 while (hash_table_[index] != invalid_index_) {
4476 if (++index == hash_size_) {
4477 index = 0;
4478 }
4479 }
4480 hash_table_[index] = virtual_method_index;
4481 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004482
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004483 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Mathieu Chartier90443472015-07-16 20:32:27 -07004484 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004485 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004486 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004487 size_t index = hash % hash_size_;
4488 while (true) {
4489 const uint32_t value = hash_table_[index];
4490 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4491 // the block and can safely assume not found.
4492 if (value == invalid_index_) {
4493 break;
4494 }
4495 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004496 ArtMethod* virtual_method =
4497 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
4498 if (comparator->HasSameNameAndSignature(
4499 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004500 hash_table_[index] = removed_index_;
4501 return value;
4502 }
4503 }
4504 if (++index == hash_size_) {
4505 index = 0;
4506 }
4507 }
4508 return GetNotFoundIndex();
4509 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004510
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004511 static uint32_t GetNotFoundIndex() {
4512 return invalid_index_;
4513 }
4514
4515 private:
4516 static const uint32_t invalid_index_;
4517 static const uint32_t removed_index_;
4518
4519 Handle<mirror::Class> klass_;
4520 const size_t hash_size_;
4521 uint32_t* const hash_table_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07004522 const size_t image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004523};
4524
4525const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4526const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4527
Alex Lighteb7c1442015-08-31 13:17:42 -07004528bool ClassLinker::LinkVirtualMethods(
4529 Thread* self,
4530 Handle<mirror::Class> klass,
4531 /*out*/std::unordered_map<size_t, ArtMethod*>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004532 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07004533 if (klass->IsInterface()) {
4534 // No vtable.
4535 if (!IsUint<16>(num_virtual_methods)) {
4536 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
4537 return false;
4538 }
4539 bool has_defaults = false;
4540 // TODO May need to replace this with real VTable for invoke_super
4541 // Assign each method an IMT index and set the default flag.
4542 for (size_t i = 0; i < num_virtual_methods; ++i) {
4543 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
4544 m->SetMethodIndex(i);
4545 if (!m->IsAbstract()) {
4546 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
4547 has_defaults = true;
4548 }
4549 }
4550 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
4551 // during initialization. This is a performance optimization. We could simply traverse the
4552 // virtual_methods_ array again during initialization.
4553 if (has_defaults) {
4554 klass->SetHasDefaultMethods();
4555 }
4556 return true;
4557 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004558 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4559 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004560 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004561 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07004562 MutableHandle<mirror::PointerArray> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004563 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004564 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004565 if (UNLIKELY(vtable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004566 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004567 return false;
4568 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004569 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004570 vtable->SetElementPtrSize(
4571 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004572 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004573 // We might need to change vtable if we have new virtual methods or new interfaces (since that
4574 // might give us new default methods). If no new interfaces then we can skip the rest since
4575 // the class cannot override any of the super-class's methods. This is required for
4576 // correctness since without it we might not update overridden default method vtable entries
4577 // correctly.
4578 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004579 klass->SetVTable(vtable.Get());
4580 return true;
4581 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004582 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07004583 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004584 auto* super_vtable = super_class->GetVTable();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004585 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07004586 // We might need to change vtable if we have new virtual methods or new interfaces (since that
4587 // might give us new default methods). See comment above.
4588 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004589 klass->SetVTable(super_vtable);
4590 return true;
4591 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004592 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
4593 super_vtable->CopyOf(self, max_count)));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004594 if (UNLIKELY(vtable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004595 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004596 return false;
4597 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004598 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004599 // How the algorithm works:
4600 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4601 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4602 // method which has not been matched to a vtable method, and j if the virtual method at the
4603 // index overrode the super virtual method at index j.
4604 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4605 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4606 // the need for the initial vtable which we later shrink back down).
4607 // 3. Add non overridden methods to the end of the vtable.
4608 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07004609 // + 1 so that even if we only have new default methods we will still be able to use this hash
4610 // table (i.e. it will never have 0 size).
4611 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004612 uint32_t* hash_table_ptr;
4613 std::unique_ptr<uint32_t[]> hash_heap_storage;
4614 if (hash_table_size <= kMaxStackHash) {
4615 hash_table_ptr = reinterpret_cast<uint32_t*>(
4616 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4617 } else {
4618 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4619 hash_table_ptr = hash_heap_storage.get();
4620 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004621 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004622 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004623 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004624 DCHECK(klass->GetVirtualMethodDuringLinking(
4625 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004626 hash_table.Add(i);
4627 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004628 // 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 -07004629 // the hash table.
4630 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07004631 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004632 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004633 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07004634 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004635 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4636 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004637 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
4638 hash_index, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004639 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4640 super_method->GetAccessFlags())) {
4641 if (super_method->IsFinal()) {
4642 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4643 PrettyMethod(virtual_method).c_str(),
4644 super_method->GetDeclaringClassDescriptor());
4645 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004646 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004647 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004648 virtual_method->SetMethodIndex(j);
4649 } else {
4650 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004651 << " would have incorrectly overridden the package-private method in "
4652 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004653 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004654 } else if (super_method->IsDefault()) {
4655 // We didn't directly override this method but we might through default methods...
4656 // Check for default method update.
4657 ArtMethod* default_method = nullptr;
4658 std::string icce_message;
4659 if (!FindDefaultMethodImplementation(self,
4660 super_method,
4661 klass,
4662 /*out*/&default_method,
4663 /*out*/&icce_message)) {
4664 // An error occurred while finding default methods.
4665 // TODO This should actually be thrown when we attempt to invoke this method.
4666 ThrowIncompatibleClassChangeError(klass.Get(), "%s", icce_message.c_str());
4667 return false;
4668 }
4669 // This should always work because we inherit superclass interfaces. We should either get
4670 // 1) An IncompatibleClassChangeError because of conflicting default method
4671 // implementations.
4672 // 2) The same default method implementation as the superclass.
4673 // 3) A default method that overrides the superclass's.
4674 // Therefore this check should never fail.
4675 CHECK(default_method != nullptr);
4676 if (UNLIKELY(default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
4677 // TODO Refactor this add default methods to virtuals here and not in
4678 // LinkInterfaceMethods maybe.
4679 // The problem is default methods might override previously present default-method or
4680 // miranda-method vtable entries from the superclass. Unfortunately we need these to
4681 // be entries in this class's virtuals. We do not give these entries there until
4682 // LinkInterfaceMethods so we pass this map around to let it know which vtable
4683 // entries need to be updated.
4684 // Make a note that vtable entry j must be updated, store what it needs to be updated to.
4685 // We will allocate a virtual method slot in LinkInterfaceMethods and fix it up then.
4686 default_translations->insert({j, default_method});
4687 VLOG(class_linker) << "Method " << PrettyMethod(super_method) << " overridden by default "
4688 << PrettyMethod(default_method) << " in " << PrettyClass(klass.Get());
4689 } else {
4690 // They are the same method/no override
4691 // Cannot do direct comparison because we had to copy the ArtMethod object into the
4692 // superclass's vtable.
4693 continue;
4694 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004695 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004696 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004697 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07004698 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004699 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004700 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004701 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4702 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07004703 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004704 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004705 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004706 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004707 local_method->SetMethodIndex(actual_count);
4708 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004709 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004710 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004711 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004712 return false;
4713 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004714 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004715 CHECK_LE(actual_count, max_count);
4716 if (actual_count < max_count) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004717 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004718 if (UNLIKELY(vtable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004719 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07004720 return false;
4721 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004722 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004723 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004724 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004725 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004726 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004727 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4728 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004729 return false;
4730 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004731 auto* vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004732 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004733 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07004734 return false;
4735 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004736 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004737 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
4738 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004739 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004740 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004741 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004742 }
4743 return true;
4744}
4745
Alex Lighteb7c1442015-08-31 13:17:42 -07004746// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
4747// out_default_method and returns true on success. If no default method was found stores nullptr
4748// into out_default_method and returns true. If an error occurs (such as a default_method conflict)
4749// it will fill the icce_message with an appropriate message for an IncompatibleClassChangeError,
4750// which should then be thrown by the caller.
4751bool ClassLinker::FindDefaultMethodImplementation(Thread* self,
4752 ArtMethod* target_method,
4753 Handle<mirror::Class> klass,
4754 /*out*/ArtMethod** out_default_method,
4755 /*out*/std::string* icce_message) const {
4756 DCHECK(self != nullptr);
4757 DCHECK(target_method != nullptr);
4758 DCHECK(out_default_method != nullptr);
4759 DCHECK(icce_message != nullptr);
4760
4761 *out_default_method = nullptr;
4762 mirror::Class* chosen_iface = nullptr;
4763
4764 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
4765 // table. This lets us walk the table backwards when searching for default methods. The first one
4766 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
4767 // track of it and then continue checking all other interfaces, since we need to throw an error if
4768 // we encounter conflicting default method implementations (one is not a subtype of the other).
4769 //
4770 // The order of unrelated interfaces does not matter and is not defined.
4771 size_t iftable_count = klass->GetIfTableCount();
4772 if (iftable_count == 0) {
4773 // No interfaces. We have already reset out to null so just return true.
4774 return true;
4775 }
4776
4777 StackHandleScope<1> hs(self);
4778 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
4779 MethodNameAndSignatureComparator target_name_comparator(
4780 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
4781 // Iterates over the klass's iftable in reverse
4782 // We have a break at the end because size_t is unsigned.
4783 for (size_t k = iftable_count - 1; /* break if k == 0 at end */; --k) {
4784 DCHECK_LT(k, iftable->Count());
4785 mirror::Class* iface = iftable->GetInterface(k);
4786 size_t num_instance_methods = iface->NumVirtualMethods();
4787 // Iterate through every method on this interface. The order does not matter so we go forwards.
4788 for (size_t m = 0; m < num_instance_methods; m++) {
4789 ArtMethod* current_method = iface->GetVirtualMethodUnchecked(m, image_pointer_size_);
4790 // Skip abstract methods and methods with different names.
4791 if (current_method->IsAbstract() ||
4792 !target_name_comparator.HasSameNameAndSignature(
4793 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
4794 continue;
4795 }
4796 // The verifier should have caught the non-public method.
4797 DCHECK(current_method->IsPublic()) << "Interface method is not public!";
4798 if (UNLIKELY(chosen_iface != nullptr)) {
4799 // We have multiple default impls of the same method. We need to check they do not
4800 // conflict and throw an error if they do. Conflicting means that the current iface is not
4801 // masked by the chosen interface.
4802 if (!iface->IsAssignableFrom(chosen_iface)) {
4803 *icce_message = StringPrintf("Conflicting default method implementations: '%s' and '%s'",
4804 PrettyMethod(current_method).c_str(),
4805 PrettyMethod(*out_default_method).c_str());
4806 return false;
4807 } else {
4808 break; // Continue checking at the next interface.
4809 }
4810 } else {
4811 *out_default_method = current_method;
4812 chosen_iface = iface;
4813 // We should now finish traversing the graph to find if we have default methods that
4814 // conflict.
4815 break;
4816 }
4817 }
4818 if (k == 0) {
4819 break;
4820 }
4821 }
4822 return true;
4823}
4824
4825// Sets imt_ref appropriately for LinkInterfaceMethods.
4826// If there is no method in the imt location of imt_ref it will store the given method there.
4827// Otherwise it will set the conflict method which will figure out which method to use during
4828// runtime.
4829static void SetIMTRef(ArtMethod* unimplemented_method,
4830 ArtMethod* conflict_method,
4831 size_t image_pointer_size,
4832 ArtMethod* current_method,
4833 /*out*/ArtMethod** imt_ref)
4834 SHARED_REQUIRES(Locks::mutator_lock_) {
4835 // Place method in imt if entry is empty, place conflict otherwise.
4836 if (*imt_ref == unimplemented_method) {
4837 *imt_ref = current_method;
4838 } else if (*imt_ref != conflict_method) {
4839 // If we are not a conflict and we have the same signature and name as the imt
4840 // entry, it must be that we overwrote a superclass vtable entry.
4841 MethodNameAndSignatureComparator imt_comparator(
4842 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size));
4843 if (imt_comparator.HasSameNameAndSignature(
4844 current_method->GetInterfaceMethodIfProxy(image_pointer_size))) {
4845 *imt_ref = current_method;
4846 } else {
4847 *imt_ref = conflict_method;
4848 }
4849 }
4850}
4851
4852// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
4853// set.
4854static bool NotSubinterfaceOfAny(const std::unordered_set<mirror::Class*>& classes,
4855 mirror::Class* val)
4856 REQUIRES(Roles::uninterruptible_)
4857 SHARED_REQUIRES(Locks::mutator_lock_) {
4858 DCHECK(val != nullptr);
4859 for (auto c : classes) {
4860 if (val->IsAssignableFrom(&*c)) {
4861 return false;
4862 }
4863 }
4864 return true;
4865}
4866
4867// Fills in and flattens the interface inheritance hierarchy.
4868//
4869// By the end of this function all interfaces in the transitive closure of to_process are added to
4870// the iftable and every interface precedes all of its sub-interfaces in this list.
4871//
4872// all I, J: Interface | I <: J implies J precedes I
4873//
4874// (note A <: B means that A is a subtype of B)
4875//
4876// This returns the total number of items in the iftable. The iftable might be resized down after
4877// this call.
4878//
4879// We order this backwards so that we do not need to reorder superclass interfaces when new
4880// interfaces are added in subclass's interface tables.
4881//
4882// Upon entry into this function iftable is a copy of the superclass's iftable with the first
4883// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
4884// The other entries are uninitialized. We will fill in the remaining entries in this function. The
4885// iftable must be large enough to hold all interfaces without changing its size.
4886static size_t FillIfTable(mirror::IfTable* iftable,
4887 size_t super_ifcount,
4888 std::vector<mirror::Class*> to_process)
4889 REQUIRES(Roles::uninterruptible_)
4890 SHARED_REQUIRES(Locks::mutator_lock_) {
4891 // This is the set of all class's already in the iftable. Used to make checking if a class has
4892 // already been added quicker.
4893 std::unordered_set<mirror::Class*> classes_in_iftable;
4894 // The first super_ifcount elements are from the superclass. We note that they are already added.
4895 for (size_t i = 0; i < super_ifcount; i++) {
4896 mirror::Class* iface = iftable->GetInterface(i);
4897 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
4898 classes_in_iftable.insert(iface);
4899 }
4900 size_t filled_ifcount = super_ifcount;
4901 for (mirror::Class* interface : to_process) {
4902 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
4903 // At this point in the loop current-iface-list has the invariant that:
4904 // for every pair of interfaces I,J within it:
4905 // if index_of(I) < index_of(J) then I is not a subtype of J
4906
4907 // If we have already seen this element then all of its super-interfaces must already be in the
4908 // current-iface-list so we can skip adding it.
4909 if (!ContainsElement(classes_in_iftable, interface)) {
4910 // We haven't seen this interface so add all of its super-interfaces onto the
4911 // current-iface-list, skipping those already on it.
4912 int32_t ifcount = interface->GetIfTableCount();
4913 for (int32_t j = 0; j < ifcount; j++) {
4914 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
4915 if (!ContainsElement(classes_in_iftable, super_interface)) {
4916 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
4917 classes_in_iftable.insert(super_interface);
4918 iftable->SetInterface(filled_ifcount, super_interface);
4919 filled_ifcount++;
4920 }
4921 }
4922 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
4923 // Place this interface onto the current-iface-list after all of its super-interfaces.
4924 classes_in_iftable.insert(interface);
4925 iftable->SetInterface(filled_ifcount, interface);
4926 filled_ifcount++;
4927 } else if (kIsDebugBuild) {
4928 // Check all super-interfaces are already in the list.
4929 int32_t ifcount = interface->GetIfTableCount();
4930 for (int32_t j = 0; j < ifcount; j++) {
4931 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
4932 DCHECK(ContainsElement(classes_in_iftable, super_interface))
4933 << "Iftable does not contain " << PrettyClass(super_interface)
4934 << ", a superinterface of " << PrettyClass(interface);
4935 }
4936 }
4937 }
4938 if (kIsDebugBuild) {
4939 // Check that the iftable is ordered correctly.
4940 for (size_t i = 0; i < filled_ifcount; i++) {
4941 mirror::Class* if_a = iftable->GetInterface(i);
4942 for (size_t j = i + 1; j < filled_ifcount; j++) {
4943 mirror::Class* if_b = iftable->GetInterface(j);
4944 // !(if_a <: if_b)
4945 CHECK(!if_b->IsAssignableFrom(if_a))
4946 << "Bad interface order: " << PrettyClass(if_a) << " (index " << i << ") extends "
4947 << PrettyClass(if_b) << " (index " << j << ") and so should be after it in the "
4948 << "interface list.";
4949 }
4950 }
4951 }
4952 return filled_ifcount;
4953}
4954
4955bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
4956 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
4957 StackHandleScope<1> hs(self);
4958 const size_t super_ifcount =
4959 klass->HasSuperClass() ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004960 const bool have_interfaces = interfaces.Get() != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07004961 const size_t num_interfaces =
4962 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004963 if (num_interfaces == 0) {
4964 if (super_ifcount == 0) {
4965 // Class implements no interfaces.
4966 DCHECK_EQ(klass->GetIfTableCount(), 0);
4967 DCHECK(klass->GetIfTable() == nullptr);
4968 return true;
4969 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004970 // Class implements same interfaces as parent, are any of these not marker interfaces?
4971 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004972 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004973 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004974 if (super_iftable->GetMethodArrayCount(i) > 0) {
4975 has_non_marker_interface = true;
4976 break;
4977 }
4978 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004979 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004980 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004981 klass->SetIfTable(super_iftable);
4982 return true;
4983 }
4984 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004985 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07004986 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004987 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004988 mirror::Class* interface = have_interfaces
4989 ? interfaces->GetWithoutChecks(i)
4990 : mirror::Class::GetDirectInterface(self, klass, i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004991 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004992 if (UNLIKELY(!interface->IsInterface())) {
4993 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004994 ThrowIncompatibleClassChangeError(klass.Get(),
4995 "Class %s implements non-interface class %s",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004996 PrettyDescriptor(klass.Get()).c_str(),
4997 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4998 return false;
4999 }
5000 ifcount += interface->GetIfTableCount();
5001 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005002 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005003 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005004 if (UNLIKELY(iftable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005005 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005006 return false;
5007 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005008 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005009 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005010 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005011 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005012 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07005013 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005014 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005015 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005016
5017 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
5018 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
5019 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07005020 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005021
5022 size_t new_ifcount;
5023 {
5024 ScopedAssertNoThreadSuspension nts(self, "Copying mirror::Class*'s for FillIfTable");
5025 std::vector<mirror::Class*> to_add;
5026 for (size_t i = 0; i < num_interfaces; i++) {
5027 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
5028 mirror::Class::GetDirectInterface(self, klass, i);
5029 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005030 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005031
5032 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005033 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005034
Ian Rogers7b078e82014-09-10 14:44:24 -07005035 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005036
Ian Rogersb52b01a2012-01-12 17:01:38 -08005037 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07005038 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005039 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005040 iftable.Assign(down_cast<mirror::IfTable*>(
Alex Lighteb7c1442015-08-31 13:17:42 -07005041 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005042 if (UNLIKELY(iftable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005043 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005044 return false;
5045 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005046 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08005047 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07005048 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005049 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005050 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07005051 return true;
5052}
5053
5054bool ClassLinker::LinkInterfaceMethods(
5055 Thread* self,
5056 Handle<mirror::Class> klass,
5057 const std::unordered_map<size_t, ArtMethod*>& default_translations,
5058 ArtMethod** out_imt) {
5059 StackHandleScope<3> hs(self);
5060 Runtime* const runtime = Runtime::Current();
5061 const bool has_superclass = klass->HasSuperClass();
5062 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
5063 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
5064 const size_t method_size = ArtMethod::Size(image_pointer_size_);
5065 const size_t ifcount = klass->GetIfTableCount();
5066
5067 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
5068
Elliott Hughes4681c802011-09-25 18:04:37 -07005069 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07005070 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005071 return true;
5072 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005073 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
5074 // the virtual methods array.
5075 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
5076 // during cross compilation.
5077 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
5078 ArenaStack stack(runtime->GetLinearAlloc()->GetArenaPool());
5079 ScopedArenaAllocator allocator(&stack);
5080 ScopedArenaVector<ArtMethod*> miranda_methods(allocator.Adapter());
Alex Lighteb7c1442015-08-31 13:17:42 -07005081 ScopedArenaVector<ArtMethod*> default_methods(allocator.Adapter());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005082
5083 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
5084 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
5085 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005086 // Copy the IMT from the super class if possible.
5087 bool extend_super_iftable = false;
5088 if (has_superclass) {
5089 mirror::Class* super_class = klass->GetSuperClass();
5090 extend_super_iftable = true;
5091 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5092 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005093 out_imt[i] = super_class->GetEmbeddedImTableEntry(i, image_pointer_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005094 }
5095 } else {
5096 // No imt in the super class, need to reconstruct from the iftable.
5097 mirror::IfTable* if_table = super_class->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005098 const size_t length = super_class->GetIfTableCount();
5099 for (size_t i = 0; i < length; ++i) {
5100 mirror::Class* interface = iftable->GetInterface(i);
5101 const size_t num_virtuals = interface->NumVirtualMethods();
5102 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5103 DCHECK_EQ(num_virtuals, method_array_count);
5104 if (method_array_count == 0) {
5105 continue;
5106 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005107 auto* method_array = if_table->GetMethodArray(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005108 for (size_t j = 0; j < num_virtuals; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005109 auto method = method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
5110 DCHECK(method != nullptr) << PrettyClass(super_class);
Alex Lighteb7c1442015-08-31 13:17:42 -07005111 // Miranda methods cannot be used to implement an interface method and defaults should be
5112 // skipped in case we override it.
5113 if (method->IsDefault() || method->IsMiranda()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005114 continue;
5115 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005116 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005117 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
Mathieu Chartiercf3b1a32015-06-01 14:30:06 -07005118 auto** imt_ref = &out_imt[imt_index];
5119 if (*imt_ref == unimplemented_method) {
5120 *imt_ref = method;
5121 } else if (*imt_ref != conflict_method) {
5122 *imt_ref = conflict_method;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005123 }
5124 }
5125 }
5126 }
5127 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005128 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
5129 // thread suspension.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005130 for (size_t i = 0; i < ifcount; ++i) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005131 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005132 if (num_methods > 0) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005133 const bool is_super = i < super_ifcount;
Alex Lighteb7c1442015-08-31 13:17:42 -07005134 // This is an interface implemented by a super-class. Therefore we can just copy the method
5135 // array from the superclass.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005136 const bool super_interface = is_super && extend_super_iftable;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005137 mirror::PointerArray* method_array;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005138 if (super_interface) {
5139 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5140 DCHECK(if_table != nullptr);
5141 DCHECK(if_table->GetMethodArray(i) != nullptr);
5142 // If we are working on a super interface, try extending the existing method array.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005143 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005144 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005145 method_array = AllocPointerArray(self, num_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005146 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005147 if (UNLIKELY(method_array == nullptr)) {
5148 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005149 return false;
5150 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005151 iftable->SetMethodArray(i, method_array);
5152 }
5153 }
5154
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005155 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005156 "Copying ArtMethods for LinkInterfaceMethods");
5157 for (size_t i = 0; i < ifcount; ++i) {
5158 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
5159 if (num_methods > 0) {
5160 StackHandleScope<2> hs2(self);
5161 const bool is_super = i < super_ifcount;
5162 const bool super_interface = is_super && extend_super_iftable;
5163 auto method_array(hs2.NewHandle(iftable->GetMethodArray(i)));
5164
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005165 LengthPrefixedArray<ArtMethod>* input_virtual_methods = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005166 Handle<mirror::PointerArray> input_vtable_array = NullHandle<mirror::PointerArray>();
5167 int32_t input_array_length = 0;
5168 if (super_interface) {
5169 // We are overwriting a super class interface, try to only virtual methods instead of the
5170 // whole vtable.
5171 input_virtual_methods = klass->GetVirtualMethodsPtr();
5172 input_array_length = klass->NumVirtualMethods();
5173 } else {
5174 // A new interface, we need the whole vtable in case a new interface method is implemented
5175 // in the whole superclass.
5176 input_vtable_array = vtable;
5177 input_array_length = input_vtable_array->GetLength();
5178 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005179 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08005180 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005181 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005182 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07005183 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07005184 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5185 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07005186 // For each method listed in the interface's method list, find the
5187 // matching method in our class's method list. We want to favor the
5188 // subclass over the superclass, which just requires walking
5189 // back from the end of the vtable. (This only matters if the
5190 // superclass defines a private method and this class redefines
5191 // it -- otherwise it would use the same vtable slot. In .dex files
5192 // those don't end up in the virtual method table, so it shouldn't
5193 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07005194 //
5195 // To find defaults we need to do the same but also go over interfaces.
5196 bool found_impl = false;
5197 ArtMethod* default_impl = nullptr;
5198 bool found_default_impl = false;
5199 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005200 ArtMethod* vtable_method = input_virtual_methods != nullptr ?
Vladimir Markocf36d492015-08-12 19:27:26 +01005201 &input_virtual_methods->At(k, method_size, method_alignment) :
Mathieu Chartiere401d142015-04-22 13:56:20 -07005202 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
5203 ArtMethod* vtable_method_for_name_comparison =
5204 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005205 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005206 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005207 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07005208 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
5209 // allocations.
5210 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005211 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07005212 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartiere401d142015-04-22 13:56:20 -07005213 PrettyMethod(vtable_method).c_str(), PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005214 return false;
Alex Lighteb7c1442015-08-31 13:17:42 -07005215 } else if (vtable_method->IsDefault()) {
5216 // We might have a newer, better, default method for this, so we just skip it. If we
5217 // are still using this we will select it again when scanning for default methods. To
5218 // obviate the need to copy the method again we will make a note that we already found
5219 // a default here.
5220 // TODO This should be much cleaner.
5221 found_default_impl = true;
5222 default_impl = vtable_method;
5223 break;
5224 } else {
5225 found_impl = true;
Ian Rogers9bc81912012-10-11 21:43:36 -07005226 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005227 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
Jeff Hao88474b42013-10-23 16:24:40 -07005228 // Place method in imt if entry is empty, place conflict otherwise.
Alex Lighteb7c1442015-08-31 13:17:42 -07005229 SetIMTRef(unimplemented_method,
5230 conflict_method,
5231 image_pointer_size_,
5232 vtable_method,
5233 /*out*/imt_ptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005234 break;
5235 }
5236 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005237 // We should only search for default implementations when the class does not implement the
5238 // method directly and either (1) the interface is newly implemented on this class and not
5239 // on any of its superclasses, (2) the superclass's implementation is a default method, or
5240 // (3) the superclass does not have an implementation.
5241 if (!found_impl && (!super_interface ||
5242 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_)
5243 ->IsOverridableByDefaultMethod())) {
5244 ArtMethod* current_method = nullptr;
5245 std::string icce_message;
5246 if (!FindDefaultMethodImplementation(self,
5247 interface_method,
5248 klass,
5249 /*out*/&current_method,
5250 /*out*/&icce_message)) {
5251 // There was a conflict with default method implementations.
5252 self->EndAssertNoThreadSuspension(old_cause);
5253 // TODO This should actually be thrown when we attempt to invoke this method.
5254 ThrowIncompatibleClassChangeError(klass.Get(), "%s", icce_message.c_str());
5255 return false;
5256 } else if (current_method != nullptr) {
5257 if (found_default_impl &&
5258 current_method->GetDeclaringClass() == default_impl->GetDeclaringClass()) {
5259 // We found a default method but it was the same one we already have from our
5260 // superclass. Don't bother adding it to our vtable again.
5261 current_method = default_impl;
5262 } else {
5263 // We found a default method implementation and there were no conflicts.
5264 // Save the default method. We need to add it to the vtable.
5265 default_methods.push_back(current_method);
5266 }
5267 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
5268 SetIMTRef(unimplemented_method,
5269 conflict_method,
5270 image_pointer_size_,
5271 current_method,
5272 /*out*/imt_ptr);
5273 found_impl = true;
5274 }
5275 }
5276 if (!found_impl && !super_interface) {
5277 // It is defined in this class or any of its subclasses.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005278 ArtMethod* miranda_method = nullptr;
5279 for (auto& mir_method : miranda_methods) {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005280 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005281 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005282 break;
5283 }
5284 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005285 if (miranda_method == nullptr) {
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005286 miranda_method = reinterpret_cast<ArtMethod*>(allocator.Alloc(method_size));
Mathieu Chartiere401d142015-04-22 13:56:20 -07005287 CHECK(miranda_method != nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07005288 // Point the interface table at a phantom slot.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005289 new(miranda_method) ArtMethod(*interface_method, image_pointer_size_);
5290 miranda_methods.push_back(miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005291 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005292 method_array->SetElementPtrSize(j, miranda_method, image_pointer_size_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005293 }
5294 }
5295 }
5296 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005297 if (!miranda_methods.empty() || !default_methods.empty()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005298 const size_t old_method_count = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07005299 const size_t new_method_count =
5300 old_method_count + miranda_methods.size() + default_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005301 // Attempt to realloc to save RAM if possible.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005302 LengthPrefixedArray<ArtMethod>* old_virtuals = klass->GetVirtualMethodsPtr();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005303 // The Realloced virtual methods aren't visiblef from the class roots, so there is no issue
5304 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
5305 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
5306 // CopyFrom has internal read barriers.
Vladimir Markocf36d492015-08-12 19:27:26 +01005307 const size_t old_size = old_virtuals != nullptr
5308 ? LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
5309 method_size,
5310 method_alignment)
5311 : 0u;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005312 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
Vladimir Markocf36d492015-08-12 19:27:26 +01005313 method_size,
5314 method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07005315 auto* virtuals = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
5316 runtime->GetLinearAlloc()->Realloc(self, old_virtuals, old_size, new_size));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005317 if (UNLIKELY(virtuals == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005318 self->AssertPendingOOMException();
Mathieu Chartier4e2cb092015-07-22 16:17:51 -07005319 self->EndAssertNoThreadSuspension(old_cause);
Ian Rogersa436fde2013-08-27 23:34:06 -07005320 return false;
5321 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005322 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table(allocator.Adapter());
5323 if (virtuals != old_virtuals) {
5324 // Maps from heap allocated miranda method to linear alloc miranda method.
Vladimir Markocf36d492015-08-12 19:27:26 +01005325 StrideIterator<ArtMethod> out = virtuals->Begin(method_size, method_alignment);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005326 // Copy over the old methods + miranda methods.
5327 for (auto& m : klass->GetVirtualMethods(image_pointer_size_)) {
5328 move_table.emplace(&m, &*out);
5329 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
5330 // barriers when it copies.
5331 out->CopyFrom(&m, image_pointer_size_);
5332 ++out;
5333 }
5334 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005335 StrideIterator<ArtMethod> out(virtuals->Begin(method_size, method_alignment)
5336 + old_method_count);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005337 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
5338 // we want the roots of the miranda methods to get visited.
5339 for (ArtMethod* mir_method : miranda_methods) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005340 ArtMethod& new_method = *out;
5341 new_method.CopyFrom(mir_method, image_pointer_size_);
5342 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda);
5343 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
5344 << "Miranda method should be abstract!";
5345 move_table.emplace(mir_method, &new_method);
5346 ++out;
5347 }
5348 // We need to copy the default methods into our own virtual method table since the runtime
5349 // requires that every method on a class's vtable be in that respective class's virtual method
5350 // table.
5351 // NOTE This means that two classes might have the same implementation of a method from the same
5352 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
5353 // default method found on a class with one found on the declaring interface directly and must
5354 // look at the declaring class to determine if they are the same.
5355 for (ArtMethod* def_method : default_methods) {
5356 ArtMethod& new_method = *out;
5357 new_method.CopyFrom(def_method, image_pointer_size_);
5358 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccDefault);
5359 // Clear the preverified flag if it is present. Since this class hasn't been verified yet it
5360 // shouldn't have methods that are preverified.
5361 // TODO This is rather arbitrary. We should maybe support classes where only some of its
5362 // methods are preverified.
5363 new_method.SetAccessFlags(new_method.GetAccessFlags() & ~kAccPreverified);
5364 move_table.emplace(def_method, &new_method);
Mathieu Chartiercf3b1a32015-06-01 14:30:06 -07005365 ++out;
Mathieu Chartiercf3b1a32015-06-01 14:30:06 -07005366 }
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07005367 virtuals->SetLength(new_method_count);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005368 UpdateClassVirtualMethods(klass.Get(), virtuals);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005369 // 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 -07005370 // suspension assert.
5371 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005372
5373 const size_t old_vtable_count = vtable->GetLength();
Alex Lighteb7c1442015-08-31 13:17:42 -07005374 const size_t new_vtable_count =
5375 old_vtable_count + miranda_methods.size() + default_methods.size();
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005376 miranda_methods.clear();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005377 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, new_vtable_count)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005378 if (UNLIKELY(vtable.Get() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005379 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07005380 return false;
5381 }
Vladimir Markocf36d492015-08-12 19:27:26 +01005382 out = virtuals->Begin(method_size, method_alignment) + old_method_count;
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005383 size_t vtable_pos = old_vtable_count;
5384 for (size_t i = old_method_count; i < new_method_count; ++i) {
5385 // Leave the declaring class alone as type indices are relative to it
5386 out->SetMethodIndex(0xFFFF & vtable_pos);
5387 vtable->SetElementPtrSize(vtable_pos, &*out, image_pointer_size_);
5388 ++out;
5389 ++vtable_pos;
5390 }
5391 CHECK_EQ(vtable_pos, new_vtable_count);
Alex Lighteb7c1442015-08-31 13:17:42 -07005392 // Update old vtable methods. We use the default_translations map to figure out what each vtable
5393 // entry should be updated to, if they need to be at all.
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07005394 for (size_t i = 0; i < old_vtable_count; ++i) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005395 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, image_pointer_size_);
5396 // Try and find what we need to change this method to.
5397 auto translation_it = default_translations.find(i);
5398 bool found_translation = false;
5399 if (translation_it != default_translations.end()) {
5400 size_t vtable_index;
5401 std::tie(vtable_index, translated_method) = *translation_it;
5402 DCHECK_EQ(vtable_index, i);
5403 found_translation = true;
5404 }
5405 DCHECK(translated_method != nullptr);
5406 auto it = move_table.find(translated_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005407 if (it != move_table.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005408 auto* new_method = it->second;
5409 DCHECK(new_method != nullptr);
5410 vtable->SetElementPtrSize(i, new_method, image_pointer_size_);
5411 } else {
5412 // If it was not going to be updated we wouldn't have put it into the default_translations
5413 // map.
5414 CHECK(!found_translation) << "We were asked to update this vtable entry. Must not fail.";
Mathieu Chartiere401d142015-04-22 13:56:20 -07005415 }
5416 }
Mathieu Chartiercf3b1a32015-06-01 14:30:06 -07005417
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005418 klass->SetVTable(vtable.Get());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005419 // Go fix up all the stale miranda pointers.
5420 for (size_t i = 0; i < ifcount; ++i) {
5421 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
5422 auto* method_array = iftable->GetMethodArray(i);
5423 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
5424 DCHECK(m != nullptr) << PrettyClass(klass.Get());
5425 auto it = move_table.find(m);
5426 if (it != move_table.end()) {
5427 auto* new_m = it->second;
5428 DCHECK(new_m != nullptr) << PrettyClass(klass.Get());
5429 method_array->SetElementPtrSize(j, new_m, image_pointer_size_);
5430 }
5431 }
5432 }
Mathieu Chartiera40c74a2015-06-02 09:56:04 -07005433 // Fix up IMT in case it has any miranda methods in it.
5434 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5435 auto it = move_table.find(out_imt[i]);
5436 if (it != move_table.end()) {
5437 out_imt[i] = it->second;
5438 }
5439 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005440 // Check that there are no stale methods are in the dex cache array.
5441 if (kIsDebugBuild) {
5442 auto* resolved_methods = klass->GetDexCache()->GetResolvedMethods();
Vladimir Marko05792b92015-08-03 11:56:49 +01005443 for (size_t i = 0, count = klass->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
5444 auto* m = mirror::DexCache::GetElementPtrSize(resolved_methods, i, image_pointer_size_);
Alex Lighteb7c1442015-08-31 13:17:42 -07005445 // We don't remove default methods from the move table since we need them to update the
5446 // vtable. Therefore just skip them for this check.
5447 if (!m->IsDefault()) {
5448 CHECK(move_table.find(m) == move_table.end()) << PrettyMethod(m);
5449 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005450 }
5451 }
5452 // Put some random garbage in old virtuals to help find stale pointers.
5453 if (virtuals != old_virtuals) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005454 memset(old_virtuals, 0xFEu, old_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005455 }
5456 } else {
5457 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005458 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005459 if (kIsDebugBuild) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005460 auto* check_vtable = klass->GetVTableDuringLinking();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005461 for (int i = 0; i < check_vtable->GetLength(); ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005462 CHECK(check_vtable->GetElementPtrSize<ArtMethod*>(i, image_pointer_size_) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005463 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005464 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005465 return true;
5466}
5467
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005468bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005469 CHECK(klass.Get() != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005470 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005471}
5472
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005473bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005474 CHECK(klass.Get() != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005475 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005476}
5477
Brian Carlstromdbc05252011-09-09 01:59:59 -07005478struct LinkFieldsComparator {
Mathieu Chartier90443472015-07-16 20:32:27 -07005479 explicit LinkFieldsComparator() SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005480 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005481 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005482 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005483 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005484 // 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 -07005485 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5486 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005487 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005488 if (type1 == Primitive::kPrimNot) {
5489 // Reference always goes first.
5490 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005491 }
Vladimir Markod5777482014-11-12 17:02:02 +00005492 if (type2 == Primitive::kPrimNot) {
5493 // Reference always goes first.
5494 return false;
5495 }
5496 size_t size1 = Primitive::ComponentSize(type1);
5497 size_t size2 = Primitive::ComponentSize(type2);
5498 if (size1 != size2) {
5499 // Larger primitive types go first.
5500 return size1 > size2;
5501 }
5502 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5503 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005504 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005505 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5506 // by name and for equal names by type id index.
5507 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5508 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005509 }
5510};
5511
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005512bool ClassLinker::LinkFields(Thread* self,
5513 Handle<mirror::Class> klass,
5514 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005515 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005516 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005517 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005518 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
5519 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005520
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005521 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005522 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005523 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005524 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005525 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005526 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005527 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005528 CHECK(super_class->IsResolved())
5529 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005530 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005531 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005532 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005533
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005534 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005535
Brian Carlstromdbc05252011-09-09 01:59:59 -07005536 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005537 // minimizes disruption of C++ version such as Class and Method.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005538 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005539 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005540 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005541 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005542 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005543 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005544 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5545 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005546
Fred Shih381e4ca2014-08-25 17:24:27 -07005547 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005548 size_t current_field = 0;
5549 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005550 FieldGaps gaps;
5551
Brian Carlstromdbc05252011-09-09 01:59:59 -07005552 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005553 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005554 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005555 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005556 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005557 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005558 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005559 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5560 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005561 MemberOffset old_offset = field_offset;
5562 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5563 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5564 }
Roland Levillain14d90572015-07-16 10:52:26 +01005565 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005566 grouped_and_sorted_fields.pop_front();
5567 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005568 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005569 field_offset = MemberOffset(field_offset.Uint32Value() +
5570 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005571 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005572 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5573 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005574 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5575 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5576 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5577 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005578 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5579 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005580 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005581
Elliott Hughesadb460d2011-10-05 17:02:34 -07005582 // 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 -07005583 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005584 // We know there are no non-reference fields in the Reference classes, and we know
5585 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005586 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005587 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
5588 << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005589 --num_reference_fields;
5590 }
5591
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005592 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005593 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005594 if (is_static) {
5595 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005596 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005597 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005598 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005599 mirror::Class* super_class = klass->GetSuperClass();
5600 if (num_reference_fields == 0 || super_class == nullptr) {
5601 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005602 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005603 if (super_class == nullptr ||
5604 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
5605 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005606 }
5607 }
5608 if (kIsDebugBuild) {
5609 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
5610 size_t total_reference_instance_fields = 0;
5611 mirror::Class* cur_super = klass.Get();
5612 while (cur_super != nullptr) {
5613 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
5614 cur_super = cur_super->GetSuperClass();
5615 }
5616 if (super_class == nullptr) {
5617 CHECK_EQ(total_reference_instance_fields, 1u) << PrettyDescriptor(klass.Get());
5618 } else {
5619 // Check that there is at least num_reference_fields other than Object.class.
5620 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
5621 << PrettyClass(klass.Get());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005622 }
5623 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005624 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005625 std::string temp;
5626 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5627 size_t previous_size = klass->GetObjectSize();
5628 if (previous_size != 0) {
5629 // Make sure that we didn't originally have an incorrect size.
5630 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005631 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005632 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005633 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005634 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005635
5636 if (kIsDebugBuild) {
5637 // Make sure that the fields array is ordered by name but all reference
5638 // offsets are at the beginning as far as alignment allows.
5639 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07005640 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00005641 : klass->GetFirstReferenceInstanceFieldOffset();
5642 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5643 num_reference_fields *
5644 sizeof(mirror::HeapReference<mirror::Object>));
5645 MemberOffset current_ref_offset = start_ref_offset;
5646 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005647 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005648 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
5649 << " class=" << PrettyClass(klass.Get()) << " field=" << PrettyField(field) << " offset="
Nicolas Geoffray555b3d02015-06-23 12:11:24 +01005650 << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005651 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005652 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005653 // NOTE: The field names can be the same. This is not possible in the Java language
5654 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005655 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005656 }
5657 Primitive::Type type = field->GetTypeAsPrimitiveType();
5658 bool is_primitive = type != Primitive::kPrimNot;
5659 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5660 strcmp("referent", field->GetName()) == 0) {
5661 is_primitive = true; // We lied above, so we have to expect a lie here.
5662 }
5663 MemberOffset offset = field->GetOffsetDuringLinking();
5664 if (is_primitive) {
5665 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5666 // Shuffled before references.
5667 size_t type_size = Primitive::ComponentSize(type);
5668 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5669 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5670 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5671 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5672 }
5673 } else {
5674 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5675 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5676 sizeof(mirror::HeapReference<mirror::Object>));
5677 }
5678 }
5679 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5680 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005681 return true;
5682}
5683
Vladimir Marko76649e82014-11-10 18:32:59 +00005684// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005685void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005686 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005687 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005688 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005689 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005690 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005691 // Compute reference offsets unless our superclass overflowed.
5692 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5693 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005694 if (num_reference_fields != 0u) {
5695 // All of the fields that contain object references are guaranteed be grouped in memory
5696 // starting at an appropriately aligned address after super class object data.
5697 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5698 sizeof(mirror::HeapReference<mirror::Object>));
5699 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005700 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005701 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005702 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005703 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005704 reference_offsets |= (0xffffffffu << start_bit) &
5705 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005706 }
5707 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005708 }
5709 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005710 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005711}
5712
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005713mirror::String* ClassLinker::ResolveString(const DexFile& dex_file,
5714 uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005715 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005716 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005717 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005718 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005719 return resolved;
5720 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005721 uint32_t utf16_length;
5722 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005723 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005724 dex_cache->SetResolvedString(string_idx, string);
5725 return string;
5726}
5727
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005728mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
5729 uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005730 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005731 StackHandleScope<2> hs(Thread::Current());
5732 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5733 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005734 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5735}
5736
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005737mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
5738 uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005739 Handle<mirror::DexCache> dex_cache,
5740 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005741 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005742 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005743 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005744 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005745 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005746 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005747 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005748 // TODO: we used to throw here if resolved's class loader was not the
5749 // boot class loader. This was to permit different classes with the
5750 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005751 dex_cache->SetResolvedType(type_idx, resolved);
5752 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005753 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005754 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005755 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005756 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005757 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08005758 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005759 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005760 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005761 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005762 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005763 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005764 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005765 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005766 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Mathieu Chartiere401d142015-04-22 13:56:20 -07005767 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005768 return resolved;
5769}
5770
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005771ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file,
5772 uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005773 Handle<mirror::DexCache> dex_cache,
5774 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005775 ArtMethod* referrer,
5776 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005777 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005778 // Check for hit in the dex cache.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005779 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005780 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005781 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005782 return resolved;
5783 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005784 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005785 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005786 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005787 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005788 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005789 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005790 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005791 // Scan using method_idx, this saves string compares but will only hit for matching dex
5792 // caches/files.
5793 switch (type) {
5794 case kDirect: // Fall-through.
5795 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005796 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
5797 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005798 break;
5799 case kInterface:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005800 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005801 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005802 break;
5803 case kSuper: // Fall-through.
5804 case kVirtual:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005805 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07005806 break;
5807 default:
5808 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005809 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005810 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005811 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005812 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005813 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005814 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005815 switch (type) {
5816 case kDirect: // Fall-through.
5817 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005818 resolved = klass->FindDirectMethod(name, signature, 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(name, signature, 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(name, signature, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07005828 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005829 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005830 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005831 // If we found a method, check for incompatible class changes.
5832 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005833 // Be a good citizen and update the dex cache to speed subsequent calls.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005834 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Ian Rogers08f753d2012-08-24 14:35:25 -07005835 return resolved;
5836 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005837 // If we had a method, it's an incompatible-class-change error.
5838 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005839 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005840 } else {
5841 // We failed to find the method which means either an access error, an incompatible class
5842 // change, or no such method. First try to find the method among direct and virtual methods.
5843 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5844 const Signature signature = dex_file.GetMethodSignature(method_id);
5845 switch (type) {
5846 case kDirect:
5847 case kStatic:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005848 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005849 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5850 // have had a resolved method before, which triggers the "true" branch above.
5851 break;
5852 case kInterface:
5853 case kVirtual:
5854 case kSuper:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005855 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005856 break;
5857 }
5858
5859 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005860 bool exception_generated = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005861 if (resolved != nullptr && referrer != nullptr) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005862 mirror::Class* methods_class = resolved->GetDeclaringClass();
5863 mirror::Class* referring_class = referrer->GetDeclaringClass();
5864 if (!referring_class->CanAccess(methods_class)) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005865 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class,
5866 methods_class,
5867 resolved,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005868 type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005869 exception_generated = true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005870 } else if (!referring_class->CanAccessMember(methods_class, resolved->GetAccessFlags())) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005871 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005872 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005873 }
5874 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005875 if (!exception_generated) {
5876 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5877 // interface methods and throw if we find the method there. If we find nothing, throw a
5878 // NoSuchMethodError.
5879 switch (type) {
5880 case kDirect:
5881 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005882 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005883 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005884 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005885 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005886 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005887 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005888 } else {
5889 ThrowNoSuchMethodError(type, klass, name, signature);
5890 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005891 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005892 break;
5893 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005894 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005895 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005896 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005897 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005898 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005899 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005900 } else {
5901 ThrowNoSuchMethodError(type, klass, name, signature);
5902 }
5903 }
5904 break;
5905 case kSuper:
5906 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005907 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005908 } else {
5909 ThrowNoSuchMethodError(type, klass, name, signature);
5910 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005911 break;
5912 case kVirtual:
5913 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005914 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005915 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005916 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005917 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005918 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005919 } else {
5920 ThrowNoSuchMethodError(type, klass, name, signature);
5921 }
5922 }
5923 break;
5924 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005925 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005926 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005927 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005928 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005929 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005930}
5931
Jeff Hao13e748b2015-08-25 20:44:19 +00005932ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(const DexFile& dex_file,
5933 uint32_t method_idx,
5934 Handle<mirror::DexCache> dex_cache,
5935 Handle<mirror::ClassLoader> class_loader) {
5936 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
5937 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
5938 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
5939 return resolved;
5940 }
5941 // Fail, get the declaring class.
5942 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
5943 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
5944 if (klass == nullptr) {
5945 Thread::Current()->AssertPendingException();
5946 return nullptr;
5947 }
5948 if (klass->IsInterface()) {
5949 LOG(FATAL) << "ResolveAmbiguousMethod: unexpected method in interface: " << PrettyClass(klass);
5950 return nullptr;
5951 }
5952
5953 // Search both direct and virtual methods
5954 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
5955 if (resolved == nullptr) {
5956 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
5957 }
5958
5959 return resolved;
5960}
5961
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005962ArtField* ClassLinker::ResolveField(const DexFile& dex_file,
5963 uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07005964 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005965 Handle<mirror::ClassLoader> class_loader,
5966 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005967 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005968 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005969 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005970 return resolved;
5971 }
5972 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005973 Thread* const self = Thread::Current();
5974 StackHandleScope<1> hs(self);
5975 Handle<mirror::Class> klass(
5976 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005977 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005978 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005979 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005980 }
5981
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005982 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005983 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005984 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005985 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005986 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005987
Andreas Gampe58a5af82014-07-31 16:23:49 -07005988 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005989 const char* name = dex_file.GetFieldName(field_id);
5990 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5991 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005992 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005993 } else {
5994 resolved = klass->FindInstanceField(name, type);
5995 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005996 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005997 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005998 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005999 }
Ian Rogersb067ac22011-12-13 18:05:09 -08006000 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07006001 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08006002 return resolved;
6003}
6004
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006005ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
6006 uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07006007 Handle<mirror::DexCache> dex_cache,
6008 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006009 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07006010 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07006011 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08006012 return resolved;
6013 }
6014 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07006015 Thread* self = Thread::Current();
6016 StackHandleScope<1> hs(self);
6017 Handle<mirror::Class> klass(
6018 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006019 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08006020 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006021 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08006022 }
6023
Ian Rogersdfb325e2013-10-30 01:00:44 -07006024 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
6025 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07006026 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07006027 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006028 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07006029 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08006030 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07006031 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07006032 }
6033 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07006034}
6035
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006036const char* ClassLinker::MethodShorty(uint32_t method_idx,
6037 ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08006038 uint32_t* length) {
6039 mirror::Class* declaring_class = referrer->GetDeclaringClass();
6040 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07006041 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07006042 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08006043 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07006044}
6045
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07006046class DumpClassVisitor : public ClassVisitor {
6047 public:
6048 explicit DumpClassVisitor(int flags) : flags_(flags) {}
6049
6050 bool Visit(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
6051 klass->DumpClass(LOG(ERROR), flags_);
6052 return true;
6053 }
6054
6055 private:
6056 const int flags_;
6057};
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07006058
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006059void ClassLinker::DumpAllClasses(int flags) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07006060 DumpClassVisitor visitor(flags);
6061 VisitClasses(&visitor);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07006062}
6063
Elliott Hughes956af0f2014-12-11 14:34:28 -08006064static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006065 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08006066 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
6067 base -= sizeof(void*); // Move backward so that code_offset != 0.
6068 const uint32_t code_offset = sizeof(void*);
6069 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006070}
6071
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006072bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
6073 return (entry_point == GetQuickResolutionStub()) ||
6074 (quick_resolution_trampoline_ == entry_point);
6075}
6076
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006077bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
6078 return (entry_point == GetQuickToInterpreterBridge()) ||
6079 (quick_to_interpreter_bridge_trampoline_ == entry_point);
6080}
6081
6082bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
6083 return (entry_point == GetQuickGenericJniStub()) ||
6084 (quick_generic_jni_trampoline_ == entry_point);
6085}
6086
6087const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
6088 return GetQuickGenericJniStub();
6089}
6090
Mathieu Chartiere401d142015-04-22 13:56:20 -07006091void ClassLinker::SetEntryPointsToCompiledCode(ArtMethod* method,
Elliott Hughes956af0f2014-12-11 14:34:28 -08006092 const void* method_code) const {
6093 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006094 oat_method.LinkMethod(method);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006095}
6096
Mathieu Chartiere401d142015-04-22 13:56:20 -07006097void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006098 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006099 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
6100 } else {
6101 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08006102 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006103 oat_method.LinkMethod(method);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006104 }
6105}
6106
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006107void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07006108 ScopedObjectAccess soa(Thread::Current());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006109 if (dex_cache_image_class_lookup_required_) {
6110 MoveImageClassesToClassTable();
6111 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07006112 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006113 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
6114 << NumNonZygoteClasses() << "\n";
6115}
6116
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006117class CountClassesVisitor : public ClassLoaderVisitor {
6118 public:
6119 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
6120
6121 void Visit(mirror::ClassLoader* class_loader)
6122 SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
6123 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07006124 if (class_table != nullptr) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006125 num_zygote_classes += class_table->NumZygoteClasses();
6126 num_non_zygote_classes += class_table->NumNonZygoteClasses();
Mathieu Chartier6b069532015-08-05 15:08:12 -07006127 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006128 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006129
6130 size_t num_zygote_classes;
6131 size_t num_non_zygote_classes;
6132};
6133
6134size_t ClassLinker::NumZygoteClasses() const {
6135 CountClassesVisitor visitor;
6136 VisitClassLoaders(&visitor);
6137 return visitor.num_zygote_classes + boot_class_table_.NumZygoteClasses();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006138}
6139
6140size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006141 CountClassesVisitor visitor;
6142 VisitClassLoaders(&visitor);
6143 return visitor.num_non_zygote_classes + boot_class_table_.NumNonZygoteClasses();
Elliott Hughescac6cc72011-11-03 20:31:21 -07006144}
6145
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006146size_t ClassLinker::NumLoadedClasses() {
6147 if (dex_cache_image_class_lookup_required_) {
6148 MoveImageClassesToClassTable();
6149 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07006150 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006151 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006152 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07006153}
6154
Brian Carlstrom47d237a2011-10-18 15:08:33 -07006155pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07006156 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07006157}
6158
6159pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07006160 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07006161}
6162
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08006163void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006164 DCHECK(!init_done_);
6165
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006166 DCHECK(klass != nullptr);
6167 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006168
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07006169 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006170 DCHECK(class_roots != nullptr);
6171 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07006172 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006173}
6174
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006175const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
6176 static const char* class_roots_descriptors[] = {
6177 "Ljava/lang/Class;",
6178 "Ljava/lang/Object;",
6179 "[Ljava/lang/Class;",
6180 "[Ljava/lang/Object;",
6181 "Ljava/lang/String;",
6182 "Ljava/lang/DexCache;",
6183 "Ljava/lang/ref/Reference;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07006184 "Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07006185 "Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07006186 "Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006187 "Ljava/lang/reflect/Proxy;",
6188 "[Ljava/lang/String;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07006189 "[Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07006190 "[Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07006191 "[Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006192 "Ljava/lang/ClassLoader;",
6193 "Ljava/lang/Throwable;",
6194 "Ljava/lang/ClassNotFoundException;",
6195 "Ljava/lang/StackTraceElement;",
6196 "Z",
6197 "B",
6198 "C",
6199 "D",
6200 "F",
6201 "I",
6202 "J",
6203 "S",
6204 "V",
6205 "[Z",
6206 "[B",
6207 "[C",
6208 "[D",
6209 "[F",
6210 "[I",
6211 "[J",
6212 "[S",
6213 "[Ljava/lang/StackTraceElement;",
6214 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08006215 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
6216 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006217
6218 const char* descriptor = class_roots_descriptors[class_root];
6219 CHECK(descriptor != nullptr);
6220 return descriptor;
6221}
6222
Mathieu Chartiere401d142015-04-22 13:56:20 -07006223bool ClassLinker::MayBeCalledWithDirectCodePointer(ArtMethod* m) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07006224 Runtime* const runtime = Runtime::Current();
6225 if (runtime->UseJit()) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07006226 // JIT can have direct code pointers from any method to any other method.
6227 return true;
6228 }
Sebastien Hertz6963e442014-11-26 22:11:27 +01006229 // Non-image methods don't use direct code pointer.
6230 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
6231 return false;
6232 }
6233 if (m->IsPrivate()) {
6234 // The method can only be called inside its own oat file. Therefore it won't be called using
6235 // its direct code if the oat file has been compiled in PIC mode.
Sebastien Hertz6963e442014-11-26 22:11:27 +01006236 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
Richard Uhler07b3c232015-03-31 15:57:54 -07006237 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Sebastien Hertz6963e442014-11-26 22:11:27 +01006238 if (oat_dex_file == nullptr) {
6239 // No oat file: the method has not been compiled.
6240 return false;
6241 }
6242 const OatFile* oat_file = oat_dex_file->GetOatFile();
6243 return oat_file != nullptr && !oat_file->IsPic();
6244 } else {
6245 // The method can be called outside its own oat file. Therefore it won't be called using its
6246 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07006247 return runtime->GetOatFileManager().HaveNonPicOatFile();
Sebastien Hertz6963e442014-11-26 22:11:27 +01006248 }
6249}
6250
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006251jobject ClassLinker::CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006252 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
6253 // We could move the jobject to the callers, but all call-sites do this...
6254 ScopedObjectAccessUnchecked soa(self);
6255
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006256 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Mathieu Chartierc7853442015-03-27 14:35:38 -07006257 StackHandleScope<10> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006258
Mathieu Chartierc7853442015-03-27 14:35:38 -07006259 ArtField* dex_elements_field =
6260 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006261
Mathieu Chartierc7853442015-03-27 14:35:38 -07006262 mirror::Class* dex_elements_class = dex_elements_field->GetType<true>();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006263 DCHECK(dex_elements_class != nullptr);
6264 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07006265 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
6266 mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006267 Handle<mirror::Class> h_dex_element_class =
6268 hs.NewHandle(dex_elements_class->GetComponentType());
6269
Mathieu Chartierc7853442015-03-27 14:35:38 -07006270 ArtField* element_file_field =
6271 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
6272 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006273
Mathieu Chartierc7853442015-03-27 14:35:38 -07006274 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
6275 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006276
6277 // Fill the elements array.
6278 int32_t index = 0;
6279 for (const DexFile* dex_file : dex_files) {
6280 StackHandleScope<3> hs2(self);
6281
Mathieu Chartiere58991b2015-10-13 07:59:34 -07006282 // CreatePathClassLoader is only used by gtests. Index 0 of h_long_array is supposed to be the
6283 // oat file but we can leave it null.
6284 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
6285 self,
6286 kDexFileIndexStart + 1));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006287 DCHECK(h_long_array.Get() != nullptr);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07006288 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006289
6290 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07006291 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006292 DCHECK(h_dex_file.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07006293 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006294
6295 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
6296 DCHECK(h_element.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07006297 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006298
6299 h_dex_elements->Set(index, h_element.Get());
6300 index++;
6301 }
6302 DCHECK_EQ(index, h_dex_elements->GetLength());
6303
6304 // Create DexPathList.
6305 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07006306 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006307 DCHECK(h_dex_path_list.Get() != nullptr);
6308 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07006309 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006310
6311 // Create PathClassLoader.
6312 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
6313 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
6314 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
6315 h_path_class_class->AllocObject(self));
6316 DCHECK(h_path_class_loader.Get() != nullptr);
6317 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07006318 ArtField* path_list_field =
6319 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList);
6320 DCHECK(path_list_field != nullptr);
6321 path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006322
6323 // Make a pretend boot-classpath.
6324 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07006325 ArtField* const parent_field =
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006326 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07006327 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01006328 DCHECK(parent_field != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006329 mirror::Object* boot_cl =
6330 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07006331 parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07006332
6333 // Make it a global ref and return.
6334 ScopedLocalRef<jobject> local_ref(
6335 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
6336 return soa.Env()->NewGlobalRef(local_ref.get());
6337}
6338
Mathieu Chartiere401d142015-04-22 13:56:20 -07006339ArtMethod* ClassLinker::CreateRuntimeMethod() {
Vladimir Marko14632852015-08-17 12:07:23 +01006340 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
6341 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006342 LengthPrefixedArray<ArtMethod>* method_array = AllocArtMethodArray(
6343 Thread::Current(),
6344 Runtime::Current()->GetLinearAlloc(),
6345 1);
Vladimir Markocf36d492015-08-12 19:27:26 +01006346 ArtMethod* method = &method_array->At(0, method_size, method_alignment);
Mathieu Chartiere401d142015-04-22 13:56:20 -07006347 CHECK(method != nullptr);
6348 method->SetDexMethodIndex(DexFile::kDexNoIndex);
6349 CHECK(method->IsRuntimeMethod());
6350 return method;
6351}
6352
Andreas Gampe8ac75952015-06-02 21:01:45 -07006353void ClassLinker::DropFindArrayClassCache() {
6354 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
6355 find_array_class_cache_next_victim_ = 0;
6356}
6357
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006358void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006359 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006360 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07006361 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
6362 auto* const class_loader = down_cast<mirror::ClassLoader*>(self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006363 if (class_loader != nullptr) {
6364 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006365 }
6366 }
6367}
6368
Mathieu Chartier00310e02015-10-17 12:46:42 -07006369void ClassLinker::InsertDexFileInToClassLoader(mirror::Object* dex_file,
6370 mirror::ClassLoader* class_loader) {
6371 DCHECK(dex_file != nullptr);
6372 DCHECK(class_loader != nullptr);
6373 Thread* const self = Thread::Current();
6374 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
6375 ClassTable* const table = class_loader->GetClassTable();
6376 DCHECK(table != nullptr);
6377 if (table->InsertDexFile(dex_file)) {
6378 // It was not already inserted, perform the write barrier to let the GC know the class loader's
6379 // class table was modified.
6380 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
6381 }
6382}
6383
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006384void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006385 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006386 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006387 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
6388 const ClassLoaderData& data = *it;
Mathieu Chartier4843bd52015-10-01 17:08:44 -07006389 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
6390 auto* const class_loader = down_cast<mirror::ClassLoader*>(self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006391 if (class_loader != nullptr) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006392 ++it;
6393 } else {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01006394 DeleteClassLoader(self, data);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07006395 it = class_loaders_.erase(it);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07006396 }
6397 }
6398}
6399
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006400} // namespace art