blob: 785adf5e7efe9ef425dae0a75ccc5496734a8475 [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
Brian Carlstromdbc05252011-09-09 01:59:59 -070019#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070020#include <iostream>
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070022#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070023#include <string>
Andreas Gampea696c0a2014-12-10 20:51:45 -080024#include <unistd.h>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070027
Elliott Hughes1aa246d2012-12-13 09:29:36 -080028#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080029#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010030#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080031#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080032#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080033#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000034#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080035#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070037#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070038#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/accounting/card_table-inl.h"
40#include "gc/accounting/heap_bitmap.h"
41#include "gc/heap.h"
42#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070043#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070044#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070045#include "interpreter/interpreter.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080046#include "jit/jit.h"
47#include "jit/jit_code_cache.h"
Ian Rogers0571d352011-11-03 19:51:38 -070048#include "leb128.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080049#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070050#include "oat_file.h"
Richard Uhler66d874d2015-01-15 09:37:19 -080051#include "oat_file_assistant.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070052#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070053#include "mirror/art_field-inl.h"
54#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055#include "mirror/class.h"
56#include "mirror/class-inl.h"
57#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070058#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080060#include "mirror/object-inl.h"
61#include "mirror/object_array-inl.h"
62#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070063#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080064#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070065#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080066#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070067#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070068#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070069#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070070#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070071#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070072#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070073#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080074#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070075#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070076
77namespace art {
78
Ian Rogers00f7d0e2012-07-19 15:28:27 -070079static void ThrowNoClassDefFoundError(const char* fmt, ...)
80 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070081 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070082static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070083 va_list args;
84 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080085 Thread* self = Thread::Current();
86 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
87 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080088 va_end(args);
89}
90
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080091static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070092 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070093 // The class failed to initialize on a previous attempt, so we want to throw
94 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
95 // failed in verification, in which case v2 5.4.1 says we need to re-throw
96 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080097 Runtime* const runtime = Runtime::Current();
98 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -070099 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
100 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700101
Elliott Hughes5c599942012-06-13 16:45:05 -0700102 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800103 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800104 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700105 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
106 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000107 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700108 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700109 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
110 if (c->GetVerifyErrorClass() != NULL) {
111 // TODO: change the verifier to store an _instance_, with a useful detail message?
112 std::string temp;
113 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
114 PrettyDescriptor(c).c_str());
115 } else {
116 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
117 PrettyDescriptor(c).c_str());
118 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700119 }
120}
121
Brian Carlstromb23eab12014-10-08 17:55:21 -0700122static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
123 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
124 if (VLOG_IS_ON(class_linker)) {
125 std::string temp;
126 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000127 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700128 }
129}
130
131static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
132 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700133 Thread* self = Thread::Current();
134 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700135
136 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700137 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700138
139 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700140 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
141 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700142
Elliott Hughesa4f94742012-05-29 16:28:38 -0700143 // We only wrap non-Error exceptions; an Error can just be used as-is.
144 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800145 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700146 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;",
147 nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700148 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700149 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700150}
151
Fred Shih381e4ca2014-08-25 17:24:27 -0700152// Gap between two fields in object layout.
153struct FieldGap {
154 uint32_t start_offset; // The offset from the start of the object.
155 uint32_t size; // The gap size of 1, 2, or 4 bytes.
156};
157struct FieldGapsComparator {
158 explicit FieldGapsComparator() {
159 }
160 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
161 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800162 // Sort by gap size, largest first. Secondary sort by starting offset.
163 return lhs.size > rhs.size || (lhs.size == rhs.size && lhs.start_offset < rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700164 }
165};
166typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
167
168// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800169static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700170 DCHECK(gaps != nullptr);
171
172 uint32_t current_offset = gap_start;
173 while (current_offset != gap_end) {
174 size_t remaining = gap_end - current_offset;
175 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
176 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
177 current_offset += sizeof(uint32_t);
178 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
179 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
180 current_offset += sizeof(uint16_t);
181 } else {
182 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
183 current_offset += sizeof(uint8_t);
184 }
185 DCHECK_LE(current_offset, gap_end) << "Overran gap";
186 }
187}
188// Shuffle fields forward, making use of gaps whenever possible.
189template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000190static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700191 MemberOffset* field_offset,
Fred Shih381e4ca2014-08-25 17:24:27 -0700192 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
193 FieldGaps* gaps)
194 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
195 DCHECK(current_field_idx != nullptr);
196 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700197 DCHECK(gaps != nullptr);
198 DCHECK(field_offset != nullptr);
199
200 DCHECK(IsPowerOfTwo(n));
201 while (!grouped_and_sorted_fields->empty()) {
202 mirror::ArtField* field = grouped_and_sorted_fields->front();
203 Primitive::Type type = field->GetTypeAsPrimitiveType();
204 if (Primitive::ComponentSize(type) < n) {
205 break;
206 }
207 if (!IsAligned<n>(field_offset->Uint32Value())) {
208 MemberOffset old_offset = *field_offset;
209 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
210 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
211 }
212 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
213 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700214 if (!gaps->empty() && gaps->top().size >= n) {
215 FieldGap gap = gaps->top();
216 gaps->pop();
217 DCHECK(IsAligned<n>(gap.start_offset));
218 field->SetOffset(MemberOffset(gap.start_offset));
219 if (gap.size > n) {
220 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
221 }
222 } else {
223 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
224 field->SetOffset(*field_offset);
225 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
226 }
227 ++(*current_field_idx);
228 }
229}
230
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800231ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700232 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700233 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700234 dex_cache_image_class_lookup_required_(false),
235 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800236 class_roots_(nullptr),
237 array_iftable_(nullptr),
238 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700239 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800240 log_new_dex_caches_roots_(false),
241 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700242 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800243 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800244 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100245 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800246 quick_to_interpreter_bridge_trampoline_(nullptr),
247 image_pointer_size_(sizeof(void*)) {
Ian Rogers98379392014-02-24 16:53:16 -0800248 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700249}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700250
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800251void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800252 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700253 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700254
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700255 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700256
Elliott Hughes30646832011-10-13 16:59:46 -0700257 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700258 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700259 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700260 // 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 -0800261 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700262 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
263 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700264 heap->AllocNonMovableObject<true>(self, nullptr,
265 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700266 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700267 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700268 mirror::Class::SetClassClass(java_lang_Class.Get());
269 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700270 if (kUseBakerOrBrooksReadBarrier) {
271 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800272 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700273 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700274 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800275 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800276 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700277
Elliott Hughes418d20f2011-09-22 14:00:39 -0700278 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700279 Handle<mirror::Class> class_array_class(hs.NewHandle(
280 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700281 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700282
Ian Rogers23435d02012-09-24 11:23:12 -0700283 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700284 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
285 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700286 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700287 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700288 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700289 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700290
Ian Rogers23435d02012-09-24 11:23:12 -0700291 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700292 Handle<mirror::Class> object_array_class(hs.NewHandle(
293 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700294 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700295
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700296 // Setup the char (primitive) class to be used for char[].
297 Handle<mirror::Class> char_class(hs.NewHandle(
298 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700299 // The primitive char class won't be initialized by
300 // InitializePrimitiveClass until line 459, but strings (and
301 // internal char arrays) will be allocated before that and the
302 // component size, which is computed from the primitive type, needs
303 // to be set here.
304 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700305
Ian Rogers23435d02012-09-24 11:23:12 -0700306 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700307 Handle<mirror::Class> char_array_class(hs.NewHandle(
308 AllocClass(self, java_lang_Class.Get(),
309 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700310 char_array_class->SetComponentType(char_class.Get());
311 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700312
Ian Rogers23435d02012-09-24 11:23:12 -0700313 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700314 Handle<mirror::Class> java_lang_String(hs.NewHandle(
315 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700316 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700317 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700318 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400319
Fred Shih4ee7a662014-07-11 09:59:27 -0700320 // Setup Reference.
321 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
322 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
323 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
324 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
325 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
326
Ian Rogers23435d02012-09-24 11:23:12 -0700327 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700328 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
329 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
330 kClassRootsMax));
331 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700332 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
333 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
334 SetClassRoot(kClassArrayClass, class_array_class.Get());
335 SetClassRoot(kObjectArrayClass, object_array_class.Get());
336 SetClassRoot(kCharArrayClass, char_array_class.Get());
337 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700338 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700339
340 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700341 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
342 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
343 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
344 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
345 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
346 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
347 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
348 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349
Ian Rogers23435d02012-09-24 11:23:12 -0700350 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700351 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700352
Ian Rogers23435d02012-09-24 11:23:12 -0700353 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700354 Handle<mirror::Class> int_array_class(hs.NewHandle(
355 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700356 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700357 mirror::IntArray::SetArrayClass(int_array_class.Get());
358 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700360 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700361
Ian Rogers52813c92012-10-11 11:50:38 -0700362 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700363 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
364 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700365 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700366 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700367 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700368
Brian Carlstromf3632832014-05-20 15:36:53 -0700369 // Constructor, Field, Method, and AbstractMethod are necessary so
370 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700371 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
372 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700373 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700374 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700375 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700376 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700377 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700378
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700379 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
380 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700381 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800382 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
383 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700384 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700385 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700386 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700387
388 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700389 Handle<mirror::Class> object_array_string(hs.NewHandle(
390 AllocClass(self, java_lang_Class.Get(),
391 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700392 object_array_string->SetComponentType(java_lang_String.Get());
393 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700394
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700395 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
396 AllocClass(self, java_lang_Class.Get(),
397 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700398 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
399 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700400
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700401 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
402 AllocClass(self, java_lang_Class.Get(),
403 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700404 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
405 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700406
Ian Rogers23435d02012-09-24 11:23:12 -0700407 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
408 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
409 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700410 CHECK_NE(0U, boot_class_path.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800411 for (auto& dex_file : boot_class_path) {
412 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700413 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800414 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700415 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700416
417 // now we can use FindSystemClass
418
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700419 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700420 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
421 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700422
Jeff Hao88474b42013-10-23 16:24:40 -0700423 // Create runtime resolution and imt conflict methods. Also setup the default imt.
424 Runtime* runtime = Runtime::Current();
425 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
426 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700427 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700428 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
429
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700430 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
431 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700432 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800433 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700434 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700435 quick_resolution_trampoline_ = GetQuickResolutionStub();
436 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
437 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700438 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700439
Mathieu Chartier66f19252012-09-18 08:57:04 -0700440 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700441 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800442 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700443 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700444 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700445 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800446 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700447 std::ostringstream os1, os2;
448 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
449 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
450 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
451 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700452 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800453 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700454 CHECK_EQ(java_lang_String.Get(), String_class);
455 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700456 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700457
Ian Rogers23435d02012-09-24 11:23:12 -0700458 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800459 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800460 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700461
Ian Rogers98379392014-02-24 16:53:16 -0800462 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800463 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700464
Ian Rogers98379392014-02-24 16:53:16 -0800465 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700466 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700467
Ian Rogers98379392014-02-24 16:53:16 -0800468 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800469 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470
Ian Rogers98379392014-02-24 16:53:16 -0800471 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700472 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700473
Ian Rogers98379392014-02-24 16:53:16 -0800474 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800475 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700476
Ian Rogers98379392014-02-24 16:53:16 -0800477 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800478 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700479
Ian Rogers98379392014-02-24 16:53:16 -0800480 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800481 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700482
Ian Rogers98379392014-02-24 16:53:16 -0800483 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700484 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700485
Ian Rogers98379392014-02-24 16:53:16 -0800486 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700487 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700488
Ian Rogers23435d02012-09-24 11:23:12 -0700489 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800490 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700491 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800492 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700493 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700494 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
495 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700496 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700497 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700498 array_iftable->SetInterface(0, java_lang_Cloneable);
499 array_iftable->SetInterface(1, java_io_Serializable);
500 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700501
Ian Rogers23435d02012-09-24 11:23:12 -0700502 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700503 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
504 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
505 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
506 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700507 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700508 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800509 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700510 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700511
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700512 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800513 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700514 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700515
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700516 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800517 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700518 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700519
Brian Carlstromf3632832014-05-20 15:36:53 -0700520 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700521 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700522 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700523
Brian Carlstromea46f952013-07-30 01:26:50 -0700524 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700525 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700526 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700527
Brian Carlstromea46f952013-07-30 01:26:50 -0700528 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700529 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700530 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700531
Ian Rogers23435d02012-09-24 11:23:12 -0700532 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700533
Ian Rogers23435d02012-09-24 11:23:12 -0700534 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800535 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700536 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
537
Brian Carlstrom1f870082011-08-23 16:02:11 -0700538 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700539 // finish initializing Reference class
540 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
541 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
542 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
543 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
544 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700545 mirror::Class* java_lang_ref_FinalizerReference =
546 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700547 java_lang_ref_FinalizerReference->SetAccessFlags(
548 java_lang_ref_FinalizerReference->GetAccessFlags() |
549 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700550 mirror::Class* java_lang_ref_PhantomReference =
551 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700552 java_lang_ref_PhantomReference->SetAccessFlags(
553 java_lang_ref_PhantomReference->GetAccessFlags() |
554 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700555 mirror::Class* java_lang_ref_SoftReference =
556 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700557 java_lang_ref_SoftReference->SetAccessFlags(
558 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700559 mirror::Class* java_lang_ref_WeakReference =
560 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700561 java_lang_ref_WeakReference->SetAccessFlags(
562 java_lang_ref_WeakReference->GetAccessFlags() |
563 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700564
Ian Rogers23435d02012-09-24 11:23:12 -0700565 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800566 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700567 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700568 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
569
jeffhao8cd6dda2012-02-22 10:15:34 -0800570 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700571 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800572 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800573 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700574 SetClassRoot(kJavaLangClassNotFoundException,
575 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800576 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700577 SetClassRoot(kJavaLangStackTraceElementArrayClass,
578 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800579 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700580
Andreas Gampe76bd8802014-12-10 16:43:58 -0800581 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
582 // initialized.
583 {
584 const DexFile& dex_file = java_lang_Object->GetDexFile();
585 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
586 CHECK(void_string_id != nullptr);
587 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
588 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
589 CHECK(void_type_id != nullptr);
590 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
591 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
592 // as referrer so the used dex cache is core's one.
593 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
594 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
595 self->AssertNoPendingException();
596 }
597
Ian Rogers98379392014-02-24 16:53:16 -0800598 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700599
Brian Carlstroma004aa92012-02-08 18:05:09 -0800600 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700601}
602
Ian Rogers98379392014-02-24 16:53:16 -0800603void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800604 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700605
606 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700607 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700608 // as the types of the field can't be resolved prior to the runtime being
609 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800610 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700611 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800612 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800613
Brian Carlstromea46f952013-07-30 01:26:50 -0700614 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700615 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
616 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700617
Brian Carlstromea46f952013-07-30 01:26:50 -0700618 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700619 CHECK_STREQ(queue->GetName(), "queue");
620 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700621
Brian Carlstromea46f952013-07-30 01:26:50 -0700622 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700623 CHECK_STREQ(queueNext->GetName(), "queueNext");
624 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700625
Brian Carlstromea46f952013-07-30 01:26:50 -0700626 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700627 CHECK_STREQ(referent->GetName(), "referent");
628 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700629
Brian Carlstromea46f952013-07-30 01:26:50 -0700630 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700631 CHECK_STREQ(zombie->GetName(), "zombie");
632 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700633
Brian Carlstroma663ea52011-08-19 23:33:41 -0700634 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700635 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700636 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800637 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700638 CHECK(klass != nullptr);
639 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700640 // note SetClassRoot does additional validation.
641 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700642 }
643
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700644 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700645
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700646 // disable the slow paths in FindClass and CreatePrimitiveClass now
647 // that Object, Class, and Object[] are setup
648 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700649
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800650 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700651}
652
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700653void ClassLinker::RunRootClinits() {
654 Thread* self = Thread::Current();
655 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800656 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700657 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700658 StackHandleScope<1> hs(self);
659 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700660 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700661 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700662 }
663 }
664}
665
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700666const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700667 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800668 if (kIsDebugBuild) {
669 for (size_t i = 0; i < oat_files_.size(); ++i) {
670 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700671 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800672 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700673 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
674 oat_files_.push_back(oat_file);
675 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800676}
677
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700678OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
679 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700680 OatFile* oat_file = space->ReleaseOatFile();
681 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700682 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700683 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700684}
685
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100686const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800687 const char* dex_location = dex_file.GetLocation().c_str();
688 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100689 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800690}
691
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100692const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
693 const char* dex_location,
694 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700695 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100696 for (const OatFile* oat_file : oat_files_) {
697 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700698
699 if (oat_location != nullptr) {
700 if (oat_file->GetLocation() != oat_location) {
701 continue;
702 }
703 }
704
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700705 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800706 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700707 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100708 if (oat_dex_file != nullptr) {
709 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800710 }
711 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100712 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800713}
714
Richard Uhler66d874d2015-01-15 09:37:19 -0800715std::vector<std::unique_ptr<const DexFile>> ClassLinker::OpenDexFilesFromOat(
716 const char* dex_location, const char* oat_location,
717 std::vector<std::string>* error_msgs) {
718 CHECK(error_msgs != nullptr);
Calin Juravle621962a2014-09-02 15:53:55 +0100719
Richard Uhler66d874d2015-01-15 09:37:19 -0800720 // Verify we aren't holding the mutator lock, which could starve GC if we
721 // have to generate or relocate an oat file.
722 Locks::mutator_lock_->AssertNotHeld(Thread::Current());
723
724 OatFileAssistant oat_file_assistant(dex_location, oat_location, kRuntimeISA,
725 !Runtime::Current()->IsAotCompiler());
726
727 // Lock the target oat location to avoid races generating and loading the
728 // oat file.
729 std::string error_msg;
730 if (!oat_file_assistant.Lock(&error_msg)) {
731 // Don't worry too much if this fails. If it does fail, it's unlikely we
732 // can generate an oat file anyway.
733 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700734 }
735
Richard Uhler66d874d2015-01-15 09:37:19 -0800736 // Check if we already have an up-to-date oat file open.
737 const OatFile* source_oat_file = nullptr;
738 {
739 ReaderMutexLock mu(Thread::Current(), dex_lock_);
740 for (const OatFile* oat_file : oat_files_) {
741 CHECK(oat_file != nullptr);
742 if (oat_file_assistant.GivenOatFileIsUpToDate(*oat_file)) {
743 source_oat_file = oat_file;
744 break;
Andreas Gampe833a4852014-05-21 18:46:59 -0700745 }
746 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700747 }
748
Richard Uhler66d874d2015-01-15 09:37:19 -0800749 // If we didn't have an up-to-date oat file open, try to load one from disk.
750 if (source_oat_file == nullptr) {
751 // Update the oat file on disk if we can. This may fail, but that's okay.
752 // Best effort is all that matters here.
753 if (!oat_file_assistant.MakeUpToDate(&error_msg)) {
754 LOG(WARNING) << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700755 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700756
Richard Uhler66d874d2015-01-15 09:37:19 -0800757 // Get the oat file on disk.
758 std::unique_ptr<OatFile> oat_file = oat_file_assistant.GetBestOatFile();
759 if (oat_file.get() != nullptr) {
760 source_oat_file = oat_file.release();
761 RegisterOatFile(source_oat_file);
Andreas Gampe833a4852014-05-21 18:46:59 -0700762 }
763 }
764
Richard Uhler66d874d2015-01-15 09:37:19 -0800765 std::vector<std::unique_ptr<const DexFile>> dex_files;
Andreas Gampe833a4852014-05-21 18:46:59 -0700766
Richard Uhler66d874d2015-01-15 09:37:19 -0800767 // Load the dex files from the oat file.
768 if (source_oat_file != nullptr) {
769 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
770 if (dex_files.empty()) {
771 error_msgs->push_back("Failed to open dex files from "
772 + source_oat_file->GetLocation());
Andreas Gampe833a4852014-05-21 18:46:59 -0700773 }
774 }
775
Richard Uhler66d874d2015-01-15 09:37:19 -0800776 // Fall back to running out of the original dex file if we couldn't load any
777 // dex_files from the oat file.
778 if (dex_files.empty()) {
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700779 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800780 if (!DexFile::Open(dex_location, dex_location, &error_msg, &dex_files)) {
781 LOG(WARNING) << error_msg;
782 error_msgs->push_back("Failed to open dex files from "
783 + std::string(dex_location));
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700784 }
785 } else {
786 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
787 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700788 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800789 return dex_files;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700790}
791
Brian Carlstromae826982011-11-09 01:33:42 -0800792const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700793 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700794 for (size_t i = 0; i < oat_files_.size(); i++) {
795 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700796 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -0800797 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700798 return oat_file;
799 }
800 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700801 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -0700802}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700803
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800804void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700805 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700806 DCHECK(obj != nullptr);
807 DCHECK(class_linker != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700808 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700809 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -0700810 if (!method->IsNative()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800811 const size_t pointer_size = class_linker->image_pointer_size_;
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800812 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800813 if (!method->IsRuntimeMethod() && method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800814 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
815 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -0700816 }
817 }
818 }
819}
820
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700821void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800822 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700823 CHECK(!init_done_);
824
Mathieu Chartier590fee92013-09-13 13:46:47 -0700825 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700826 gc::Heap* heap = Runtime::Current()->GetHeap();
827 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700828 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700829 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700830 OatFile& oat_file = GetImageOatFile(space);
831 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
832 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700833 const char* image_file_location = oat_file.GetOatHeader().
834 GetStoreValueByKey(OatHeader::kImageLocationKey);
835 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700836 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -0700837 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -0800838 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +0100839 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800840 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
841 mirror::ObjectArray<mirror::DexCache>* dex_caches =
842 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700843
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700844 StackHandleScope<1> hs(self);
845 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
846 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
847 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700848 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700849
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700850 // Special case of setting up the String class early so that we can test arbitrary objects
851 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700852 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800853
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700854 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700855 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700856 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800857 StackHandleScope<1> hs2(self);
858 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700859 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700860 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
861 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700862 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700863 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800864 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
865 if (dex_file.get() == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700866 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700867 << " from within oat file " << oat_file.GetLocation()
868 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -0800869 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700870 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700871
872 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
873
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800874 AppendToBootClassPath(*dex_file.get(), dex_cache);
875 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700876 }
877
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700878 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
879 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -0700880 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -0800881 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800882 if (!Runtime::Current()->IsAotCompiler()) {
883 // Aot compiler supports having an image with a different pointer size than the runtime. This
Mathieu Chartier2d721012014-11-10 11:08:06 -0800884 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
885 // also use 32 bit dex2oat on a system with 64 bit apps.
886 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
887 << sizeof(void*);
888 }
889 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
890 image_pointer_size_ = 4;
891 } else {
892 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
893 image_pointer_size_ = 8;
894 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700895
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700896 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800897 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800898 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700899 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700900 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700901
902 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800903 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700904 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700905
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800906 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700907 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800908 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800909 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -0700910 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -0700911 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800912 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
913 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
914 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
915 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
916 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
917 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
918 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
919 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
920 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
921 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700922
Ian Rogers98379392014-02-24 16:53:16 -0800923 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700924
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800925 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700926}
927
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700928void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
929 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
930 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800931 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800932 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800933 }
934 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800935 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700936 }
937 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800938 for (auto& root : new_class_roots_) {
939 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800940 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800941 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700942 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700943 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
944 // corresponding object. This is slow, but luckily for us, this may only happen with a
945 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800946 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800947 DCHECK(it != class_table_.end());
948 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700949 }
950 }
951 }
952 if ((flags & kVisitRootFlagClearRootLog) != 0) {
953 new_class_roots_.clear();
954 }
955 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
956 log_new_class_table_roots_ = true;
957 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
958 log_new_class_table_roots_ = false;
959 }
960 // We deliberately ignore the class roots in the image since we
961 // handle image roots by using the MS/CMS rescanning of dirty cards.
962}
963
Brian Carlstroma663ea52011-08-19 23:33:41 -0700964// Keep in sync with InitCallback. Anything we visit, we need to
965// reinit references to when reinitializing a ClassLinker from a
966// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -0800967void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800968 class_roots_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers50b35e22012-10-04 10:09:15 -0700969 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -0700970 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700971 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800972 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700973 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800974 dex_cache.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -0700975 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800976 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
977 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800978 dex_caches_[index].VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -0700979 }
Elliott Hughesf8349362012-06-18 15:00:06 -0700980 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800981 if ((flags & kVisitRootFlagClearRootLog) != 0) {
982 new_dex_cache_roots_.clear();
983 }
984 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
985 log_new_dex_caches_roots_ = true;
986 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
987 log_new_dex_caches_roots_ = false;
988 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700989 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700990 VisitClassRoots(callback, arg, flags);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800991 array_iftable_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700992 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -0800993 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800994 find_array_class_cache_[i].VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -0800995 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700996}
997
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700998void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
999 if (dex_cache_image_class_lookup_required_) {
1000 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001001 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001002 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001003 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001004 for (GcRoot<mirror::Class>& root : class_table_) {
1005 if (!visitor(root.Read(), arg)) {
1006 return;
1007 }
1008 }
1009 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1010 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001011 return;
1012 }
1013 }
1014}
1015
Ian Rogersdbf3be02014-08-29 15:40:08 -07001016static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001017 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001018 classes->insert(c);
1019 return true;
1020}
1021
Ian Rogersdbf3be02014-08-29 15:40:08 -07001022struct GetClassesVisitorArrayArg {
1023 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1024 int32_t index;
1025 bool success;
1026};
1027
1028static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1029 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1030 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1031 if (arg->index < (*arg->classes)->GetLength()) {
1032 (*arg->classes)->Set(arg->index, c);
1033 arg->index++;
1034 return true;
1035 } else {
1036 arg->success = false;
1037 return false;
1038 }
1039}
1040
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001041void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001042 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1043 // is avoiding duplicates.
1044 if (!kMovingClasses) {
1045 std::set<mirror::Class*> classes;
1046 VisitClasses(GetClassesVisitorSet, &classes);
1047 for (mirror::Class* klass : classes) {
1048 if (!visitor(klass, arg)) {
1049 return;
1050 }
1051 }
1052 } else {
1053 Thread* self = Thread::Current();
1054 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001055 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001056 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1057 GetClassesVisitorArrayArg local_arg;
1058 local_arg.classes = &classes;
1059 local_arg.success = false;
1060 // We size the array assuming classes won't be added to the class table during the visit.
1061 // If this assumption fails we iterate again.
1062 while (!local_arg.success) {
1063 size_t class_table_size;
1064 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001065 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001066 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001067 }
1068 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1069 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1070 classes.Assign(
1071 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1072 CHECK(classes.Get() != nullptr); // OOME.
1073 local_arg.index = 0;
1074 local_arg.success = true;
1075 VisitClasses(GetClassesVisitorArray, &local_arg);
1076 }
1077 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1078 // If the class table shrank during creation of the clases array we expect null elements. If
1079 // the class table grew then the loop repeats. If classes are created after the loop has
1080 // finished then we don't visit.
1081 mirror::Class* klass = classes->Get(i);
1082 if (klass != nullptr && !visitor(klass, arg)) {
1083 return;
1084 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001085 }
1086 }
1087}
1088
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001089ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001090 mirror::Class::ResetClass();
1091 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001092 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001093 mirror::ArtField::ResetClass();
1094 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001095 mirror::BooleanArray::ResetArrayClass();
1096 mirror::ByteArray::ResetArrayClass();
1097 mirror::CharArray::ResetArrayClass();
1098 mirror::DoubleArray::ResetArrayClass();
1099 mirror::FloatArray::ResetArrayClass();
1100 mirror::IntArray::ResetArrayClass();
1101 mirror::LongArray::ResetArrayClass();
1102 mirror::ShortArray::ResetArrayClass();
1103 mirror::Throwable::ResetClass();
1104 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001105 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001106}
1107
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001108mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001109 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001110 StackHandleScope<16> hs(self);
1111 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1112 Handle<mirror::DexCache> dex_cache(
1113 hs.NewHandle(down_cast<mirror::DexCache*>(
1114 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1115 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001116 if (dex_cache.Get() == nullptr) {
1117 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001118 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001119 Handle<mirror::String>
1120 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001121 if (location.Get() == nullptr) {
1122 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001123 }
Ian Rogers700a4022014-05-19 16:49:03 -07001124 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001125 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001126 if (strings.Get() == nullptr) {
1127 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001128 }
Ian Rogers700a4022014-05-19 16:49:03 -07001129 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001130 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001131 if (types.Get() == nullptr) {
1132 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001133 }
Ian Rogers700a4022014-05-19 16:49:03 -07001134 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001135 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001136 if (methods.Get() == nullptr) {
1137 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001138 }
Ian Rogers700a4022014-05-19 16:49:03 -07001139 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001140 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001141 if (fields.Get() == nullptr) {
1142 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001143 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001144 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1145 fields.Get());
1146 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001147}
1148
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001149mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001150 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001151 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001152 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001153 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001154 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001155 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1156 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001157 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001158 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001159 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001160 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001161 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001162}
1163
Ian Rogers6fac4472014-02-25 17:01:10 -08001164mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001165 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001166}
1167
Brian Carlstromea46f952013-07-30 01:26:50 -07001168mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001169 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001170 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001171}
1172
Brian Carlstromea46f952013-07-30 01:26:50 -07001173mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001174 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001175 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001176}
1177
Mathieu Chartier590fee92013-09-13 13:46:47 -07001178mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1179 Thread* self, size_t length) {
1180 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1181 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001182}
1183
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001184mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1185 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001186 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001187
1188 // For temporary classes we must wait for them to be retired.
1189 if (init_done_ && klass->IsTemp()) {
1190 CHECK(!klass->IsResolved());
1191 if (klass->IsErroneous()) {
1192 ThrowEarlierClassFailure(klass);
1193 return nullptr;
1194 }
1195 StackHandleScope<1> hs(self);
1196 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1197 ObjectLock<mirror::Class> lock(self, h_class);
1198 // Loop and wait for the resolving thread to retire this class.
1199 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1200 lock.WaitIgnoringInterrupts();
1201 }
1202 if (h_class->IsErroneous()) {
1203 ThrowEarlierClassFailure(h_class.Get());
1204 return nullptr;
1205 }
1206 CHECK(h_class->IsRetired());
1207 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001208 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
1209 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001210 }
1211
Brian Carlstromaded5f72011-10-07 17:15:04 -07001212 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001213 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001214 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001215 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1216 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001217 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001218 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1219 ThrowClassCircularityError(h_class.Get());
1220 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001221 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001222 }
1223 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001224 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001225 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001226 }
1227 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001228
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001229 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001230 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001231 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001232 }
1233 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001234 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001235 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001236 return klass;
1237}
1238
Ian Rogers68b56852014-08-29 20:19:11 -07001239typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
1240
1241// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001242ClassPathEntry FindInClassPath(const char* descriptor,
1243 size_t hash, const std::vector<const DexFile*>& class_path) {
1244 for (const DexFile* dex_file : class_path) {
1245 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001246 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07001247 return ClassPathEntry(dex_file, dex_class_def);
1248 }
1249 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001250 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07001251}
1252
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001253mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1254 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001255 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001256 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08001257 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001258 if (class_loader->GetClass() !=
1259 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
1260 class_loader->GetParent()->GetClass() !=
1261 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
1262 return nullptr;
1263 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001264 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001265 // Check if this would be found in the parent boot class loader.
1266 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001267 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001268 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08001269 // May return null if resolution on another thread fails.
1270 klass = EnsureResolved(self, descriptor, klass);
1271 } else {
1272 // May OOME.
1273 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
1274 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001275 }
Ian Rogers32427292014-11-19 14:05:21 -08001276 if (klass == nullptr) {
1277 CHECK(self->IsExceptionPending()) << descriptor;
1278 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001279 }
Ian Rogers32427292014-11-19 14:05:21 -08001280 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001281 } else {
Ian Rogers32427292014-11-19 14:05:21 -08001282 // Handle as if this is the child PathClassLoader.
1283 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001284 StackHandleScope<3> hs(self);
1285 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
1286 // We need to get the DexPathList and loop through it.
1287 Handle<mirror::ArtField> cookie_field =
1288 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
1289 Handle<mirror::ArtField> dex_file_field =
1290 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07001291 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001292 mirror::Object* dex_path_list =
1293 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
1294 GetObject(class_loader.Get());
1295 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
1296 cookie_field.Get() != nullptr) {
1297 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1298 mirror::Object* dex_elements_obj =
1299 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1300 GetObject(dex_path_list);
1301 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1302 // at the mCookie which is a DexFile vector.
1303 if (dex_elements_obj != nullptr) {
1304 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
1305 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
1306 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
1307 mirror::Object* element = dex_elements->GetWithoutChecks(i);
1308 if (element == nullptr) {
1309 // Should never happen, fall back to java code to throw a NPE.
1310 break;
1311 }
1312 mirror::Object* dex_file = dex_file_field->GetObject(element);
1313 if (dex_file != nullptr) {
Andreas Gampe324b9bb2015-02-23 16:33:22 -08001314 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
1315 if (long_array == nullptr) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001316 // This should never happen so log a warning.
1317 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
1318 break;
1319 }
Andreas Gampe324b9bb2015-02-23 16:33:22 -08001320 int32_t long_array_size = long_array->GetLength();
1321 for (int32_t j = 0; j < long_array_size; ++j) {
1322 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
1323 long_array->GetWithoutChecks(j)));
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001324 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001325 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001326 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001327 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
1328 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001329 if (klass == nullptr) {
1330 CHECK(self->IsExceptionPending()) << descriptor;
1331 self->ClearException();
1332 return nullptr;
1333 }
1334 return klass;
1335 }
1336 }
1337 }
1338 }
1339 }
1340 }
Ian Rogers32427292014-11-19 14:05:21 -08001341 self->AssertNoPendingException();
1342 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001343 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001344}
1345
Ian Rogers98379392014-02-24 16:53:16 -08001346mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001347 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001348 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001349 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001350 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001351 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001352 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1353 // for primitive classes that aren't backed by dex files.
1354 return FindPrimitiveClass(descriptor[0]);
1355 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001356 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001357 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001358 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07001359 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001360 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001361 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001362 // Class is not yet loaded.
1363 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001364 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001365 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001366 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001367 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07001368 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001369 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07001370 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07001371 } else {
1372 // The boot class loader is searched ahead of the application class loader, failures are
1373 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
1374 // trigger the chaining with a proper stack trace.
1375 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001376 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07001377 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05001378 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001379 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07001380 // First try with the bootstrap class loader.
1381 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001382 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07001383 if (klass != nullptr) {
1384 return EnsureResolved(self, descriptor, klass);
1385 }
1386 }
Ian Rogers63557452014-06-04 16:57:15 -07001387 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
1388 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001389 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07001390 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001391 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07001392 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05001393 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07001394 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001395 const std::vector<const DexFile*>* class_path;
1396 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07001397 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001398 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001399 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001400 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
1401 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001402 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07001403 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001404 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07001405 } else {
1406 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
1407 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001408 self->SetException(pre_allocated);
Ian Rogers7b078e82014-09-10 14:44:24 -07001409 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001410 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001411 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001412 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001413 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
1414 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001415 if (cp_klass != nullptr) {
1416 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07001417 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001418 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001419 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001420 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07001421 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07001422 {
1423 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001424 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1425 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07001426 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001427 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07001428 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07001429 }
Ian Rogers68b56852014-08-29 20:19:11 -07001430 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001431 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1432 WellKnownClasses::java_lang_ClassLoader_loadClass,
1433 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001434 }
Ian Rogers98379392014-02-24 16:53:16 -08001435 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001436 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07001437 return nullptr;
1438 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08001439 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07001440 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07001441 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07001442 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08001443 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001444 // success, return mirror::Class*
1445 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001446 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001447 }
Ian Rogers07140832014-09-30 15:43:59 -07001448 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001449}
1450
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001451mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001452 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001453 const DexFile& dex_file,
1454 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001455 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001456 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001457
Brian Carlstromaded5f72011-10-07 17:15:04 -07001458 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001459 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001460 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001461 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001462 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001463 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001464 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001465 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001466 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001467 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1468 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001469 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001470 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001471 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001472 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001473 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001474 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001475 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001476 }
1477
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001478 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001479 // Allocate a class with the status of not ready.
1480 // Interface object should get the right size here. Regular class will
1481 // figure out the right size later and be replaced with one of the right
1482 // size when the class becomes resolved.
1483 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001484 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001485 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001486 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07001487 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001488 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001489 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07001490 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001491 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001492 if (self->IsExceptionPending()) {
1493 // An exception occured during load, set status to erroneous while holding klass' lock in case
1494 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001495 if (!klass->IsErroneous()) {
1496 klass->SetStatus(mirror::Class::kStatusError, self);
1497 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001498 return nullptr;
1499 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001500 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001501
Mathieu Chartier590fee92013-09-13 13:46:47 -07001502 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001503 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001504 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001505 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1506 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001507 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001508 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001509
Brian Carlstromaded5f72011-10-07 17:15:04 -07001510 // Finish loading (if necessary) by finding parents
1511 CHECK(!klass->IsLoaded());
1512 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1513 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001514 if (!klass->IsErroneous()) {
1515 klass->SetStatus(mirror::Class::kStatusError, self);
1516 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001517 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001518 }
1519 CHECK(klass->IsLoaded());
1520 // Link the class (if necessary)
1521 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001522 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001523 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001524
1525 mirror::Class* new_class = nullptr;
1526 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001527 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001528 if (!klass->IsErroneous()) {
1529 klass->SetStatus(mirror::Class::kStatusError, self);
1530 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001531 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001532 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07001533 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001534 CHECK(new_class != nullptr) << descriptor;
1535 CHECK(new_class->IsResolved()) << descriptor;
1536
1537 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001538
Sebastien Hertza8a697f2015-01-15 12:28:47 +01001539 // Instrumentation may have updated entrypoints for all methods of all
1540 // classes. However it could not update methods of this class while we
1541 // were loading it. Now the class is resolved, we can update entrypoints
1542 // as required by instrumentation.
1543 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
1544 // We must be in the kRunnable state to prevent instrumentation from
1545 // suspending all threads to update entrypoints while we are doing it
1546 // for this class.
1547 DCHECK_EQ(self->GetState(), kRunnable);
1548 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(new_class_h.Get());
1549 }
1550
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001551 /*
1552 * We send CLASS_PREPARE events to the debugger from here. The
1553 * definition of "preparation" is creating the static fields for a
1554 * class and initializing them to the standard default values, but not
1555 * executing any code (that comes later, during "initialization").
1556 *
1557 * We did the static preparation in LinkClass.
1558 *
1559 * The class has been prepared and resolved but possibly not yet verified
1560 * at this point.
1561 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001562 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001563
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001564 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001565}
1566
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001567uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
1568 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07001569 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001570 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07001571 size_t num_8 = 0;
1572 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001573 size_t num_32 = 0;
1574 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001575 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001576 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1577 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001578 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001579 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07001580 switch (c) {
1581 case 'L':
1582 case '[':
1583 num_ref++;
1584 break;
1585 case 'J':
1586 case 'D':
1587 num_64++;
1588 break;
1589 case 'I':
1590 case 'F':
1591 num_32++;
1592 break;
1593 case 'S':
1594 case 'C':
1595 num_16++;
1596 break;
1597 case 'B':
1598 case 'Z':
1599 num_8++;
1600 break;
1601 default:
1602 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08001603 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001604 }
1605 }
1606 }
Fred Shih37f05ef2014-07-16 18:38:08 -07001607 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001608}
1609
Ian Rogers97b52f82014-08-14 11:34:07 -07001610OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
1611 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001612 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001613 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
1614 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001615 *found = false;
1616 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001617 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001618 *found = true;
1619 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08001620}
1621
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001622static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
1623 uint32_t method_idx) {
1624 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07001625 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001626 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001627 ClassDataItemIterator it(dex_file, class_data);
1628 // Skip fields
1629 while (it.HasNextStaticField()) {
1630 it.Next();
1631 }
1632 while (it.HasNextInstanceField()) {
1633 it.Next();
1634 }
1635 // Process methods
1636 size_t class_def_method_index = 0;
1637 while (it.HasNextDirectMethod()) {
1638 if (it.GetMemberIndex() == method_idx) {
1639 return class_def_method_index;
1640 }
1641 class_def_method_index++;
1642 it.Next();
1643 }
1644 while (it.HasNextVirtualMethod()) {
1645 if (it.GetMemberIndex() == method_idx) {
1646 return class_def_method_index;
1647 }
1648 class_def_method_index++;
1649 it.Next();
1650 }
1651 DCHECK(!it.HasNext());
1652 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08001653 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001654}
1655
Ian Rogers97b52f82014-08-14 11:34:07 -07001656const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08001657 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001658 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001659 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08001660 size_t oat_method_index;
1661 if (method->IsStatic() || method->IsDirect()) {
1662 // Simple case where the oat method index was stashed at load time.
1663 oat_method_index = method->GetMethodIndex();
1664 } else {
1665 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1666 // by search for its position in the declared virtual methods.
1667 oat_method_index = declaring_class->NumDirectMethods();
1668 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001669 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001670 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07001671 // Check method index instead of identity in case of duplicate method definitions.
1672 if (method->GetDexMethodIndex() ==
1673 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001674 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001675 break;
1676 }
Ian Rogersf320b632012-03-13 18:47:47 -07001677 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001678 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001679 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
1680 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001681 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001682 DCHECK_EQ(oat_method_index,
1683 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001684 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001685 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07001686 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
1687 declaring_class->GetDexClassDefIndex(),
1688 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001689 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001690 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001691 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001692 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07001693}
1694
1695// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001696const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001697 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07001698 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001699 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07001700 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001701 bool found;
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001702 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1703 if (found) {
1704 auto* code = oat_method.GetQuickCode();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001705 if (code != nullptr) {
1706 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08001707 }
1708 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001709 jit::Jit* const jit = Runtime::Current()->GetJit();
1710 if (jit != nullptr) {
1711 auto* code = jit->GetCodeCache()->GetCodeFor(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001712 if (code != nullptr) {
1713 return code;
1714 }
1715 }
1716 if (method->IsNative()) {
1717 // No code and native? Use generic trampoline.
1718 return GetQuickGenericJniStub();
1719 }
1720 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07001721}
1722
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001723const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
1724 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
1725 return nullptr;
1726 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001727 bool found;
1728 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1729 if (found) {
1730 return oat_method.GetQuickCode();
1731 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001732 jit::Jit* jit = Runtime::Current()->GetJit();
1733 if (jit != nullptr) {
1734 auto* code = jit->GetCodeCache()->GetCodeFor(method);
1735 if (code != nullptr) {
1736 return code;
1737 }
1738 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001739 return nullptr;
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001740}
1741
Ian Rogersef7d42f2014-01-06 12:55:46 -08001742const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
1743 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001744 bool found;
1745 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
1746 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001747 return nullptr;
1748 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001749 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001750 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001751}
1752
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001753// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001754static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07001755 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08001756 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001757 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08001758 // May return true for native code, in the case of generic JNI
1759 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001760 return true;
1761 }
1762 // If interpreter mode is enabled, every method (except native and proxy) must
1763 // be run with interpreter.
1764 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
1765 !method->IsNative() && !method->IsProxyMethod();
1766}
1767
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001768void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08001769 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07001770 if (klass->NumDirectMethods() == 0) {
1771 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08001772 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001773 Runtime* runtime = Runtime::Current();
1774 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001775 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001776 return; // OAT file unavailable.
1777 }
Ian Rogers19846512012-02-24 11:42:47 -08001778 }
Alex Light64ad14d2014-08-19 14:23:13 -07001779
Mathieu Chartierf8322842014-05-16 10:59:25 -07001780 const DexFile& dex_file = klass->GetDexFile();
1781 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07001782 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07001783 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07001784 // There should always be class data if there were direct methods.
1785 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08001786 ClassDataItemIterator it(dex_file, class_data);
1787 // Skip fields
1788 while (it.HasNextStaticField()) {
1789 it.Next();
1790 }
1791 while (it.HasNextInstanceField()) {
1792 it.Next();
1793 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001794 bool has_oat_class;
1795 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1796 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07001797 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001798 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001799 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001800 if (!method->IsStatic()) {
1801 // Only update static methods.
1802 continue;
Ian Rogers19846512012-02-24 11:42:47 -08001803 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001804 const void* quick_code = nullptr;
1805 if (has_oat_class) {
1806 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001807 quick_code = oat_method.GetQuickCode();
1808 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001809 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001810 if (enter_interpreter) {
1811 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07001812 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001813 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001814 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08001815 } else {
1816 quick_code = GetQuickToInterpreterBridge();
1817 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001818 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001819 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08001820 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001821 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08001822}
1823
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001824void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07001825 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001826 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001827 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001828 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001829 // The following code only applies to a non-compiler runtime.
1830 return;
1831 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001832 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001833 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001834 if (oat_class != nullptr) {
1835 // Every kind of method should at least get an invoke stub from the oat_method.
1836 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001837 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001838 oat_method.LinkMethod(method.Get());
1839 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001840
Jeff Hao16743632013-05-08 10:59:04 -07001841 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001842 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08001843 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001844 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001845 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001846 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07001847 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001848 }
1849
Brian Carlstrom92827a52011-10-10 15:50:01 -07001850 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001851 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001852 return;
1853 }
Ian Rogers19846512012-02-24 11:42:47 -08001854
1855 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001856 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001857 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
1858 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001859 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001860 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001861 if (!method->IsNative()) {
1862 // Set entry point from compiled code if there's no code or in interpreter only mode.
1863 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001864 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001865 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001866 }
Ian Rogers0d6de042012-02-29 08:50:26 -08001867 }
jeffhao26c0a1a2012-01-17 16:28:33 -08001868
Ian Rogers62d6c772013-02-27 08:32:07 -08001869 if (method->IsNative()) {
1870 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001871 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07001872
1873 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001874 // We have a native method here without code. Then it should have either the generic JNI
1875 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
1876 // TODO: this doesn't handle all the cases where trampolines may be installed.
1877 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1878 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07001879 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001880 }
1881}
1882
Fred Shih37f05ef2014-07-16 18:38:08 -07001883
Fred Shih37f05ef2014-07-16 18:38:08 -07001884
Ian Rogers7b078e82014-09-10 14:44:24 -07001885void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07001886 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001887 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001888 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001889 CHECK(klass.Get() != nullptr);
1890 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001891 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001892 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001893 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001894
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001895 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07001896 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07001897 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001898 klass->SetAccessFlags(access_flags);
1899 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001900 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001901 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001902
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001903 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001904 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08001905 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001906
Ian Rogers13735952014-10-08 12:43:28 -07001907 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001908 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001909 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001910 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001911
Ian Rogers97b52f82014-08-14 11:34:07 -07001912
1913 bool has_oat_class = false;
1914 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
1915 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1916 &has_oat_class);
1917 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001918 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07001919 }
1920 }
1921 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001922 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001923 }
1924}
1925
Ian Rogers7b078e82014-09-10 14:44:24 -07001926void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07001927 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001928 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001929 const OatFile::OatClass* oat_class) {
1930 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07001931 ClassDataItemIterator it(dex_file, class_data);
1932 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001933 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001934 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001935 CHECK(self->IsExceptionPending()); // OOME.
1936 return;
1937 }
1938 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07001939 }
1940 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001941 mirror::ObjectArray<mirror::ArtField>* fields =
1942 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001943 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001944 CHECK(self->IsExceptionPending()); // OOME.
1945 return;
1946 }
1947 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07001948 }
1949 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001950 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001951 StackHandleScope<1> hs(self);
1952 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001953 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001954 CHECK(self->IsExceptionPending()); // OOME.
1955 return;
1956 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001957 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07001958 LoadField(dex_file, it, klass, sfield);
1959 }
1960 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001961 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001962 StackHandleScope<1> hs(self);
1963 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001964 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001965 CHECK(self->IsExceptionPending()); // OOME.
1966 return;
1967 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001968 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07001969 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001970 }
1971
Ian Rogers0571d352011-11-03 19:51:38 -07001972 // Load methods.
1973 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001974 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07001975 mirror::ObjectArray<mirror::ArtMethod>* directs =
1976 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001977 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001978 CHECK(self->IsExceptionPending()); // OOME.
1979 return;
1980 }
1981 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001982 }
Ian Rogers0571d352011-11-03 19:51:38 -07001983 if (it.NumVirtualMethods() != 0) {
1984 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07001985 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
1986 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001987 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001988 CHECK(self->IsExceptionPending()); // OOME.
1989 return;
1990 }
1991 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001992 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001993 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07001994 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
1995 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001996 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001997 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001998 StackHandleScope<1> hs(self);
1999 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002000 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002001 CHECK(self->IsExceptionPending()); // OOME.
2002 return;
2003 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002004 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002005 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002006 uint32_t it_method_index = it.GetMemberIndex();
2007 if (last_dex_method_index == it_method_index) {
2008 // duplicate case
2009 method->SetMethodIndex(last_class_def_method_index);
2010 } else {
2011 method->SetMethodIndex(class_def_method_index);
2012 last_dex_method_index = it_method_index;
2013 last_class_def_method_index = class_def_method_index;
2014 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002015 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002016 }
2017 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002018 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002019 StackHandleScope<1> hs(self);
2020 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002021 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002022 CHECK(self->IsExceptionPending()); // OOME.
2023 return;
2024 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002025 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002026 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002027 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002028 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002029 }
2030 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002031}
2032
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002033void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002034 Handle<mirror::Class> klass,
2035 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002036 uint32_t field_idx = it.GetMemberIndex();
2037 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002038 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002039 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002040}
2041
Brian Carlstromea46f952013-07-30 01:26:50 -07002042mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002043 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002044 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002045 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002046 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002047 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002048
Brian Carlstromea46f952013-07-30 01:26:50 -07002049 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002050 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002051 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002052 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002053 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002054 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002055
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002056 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002057 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002058 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002059 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002060
Ian Rogers19846512012-02-24 11:42:47 -08002061 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002062 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002063
Andreas Gampe51829322014-08-25 15:05:04 -07002064 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002065
Ian Rogersdfb325e2013-10-30 01:00:44 -07002066 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002067 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002068 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2069 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002070 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002071 klass->SetFinalizable();
2072 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002073 std::string temp;
2074 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002075 // The Enum class declares a "final" finalize() method to prevent subclasses from
2076 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2077 // subclasses, so we exclude it here.
2078 // We also want to avoid setting the flag on Object, where we know that finalize() is
2079 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002080 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2081 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002082 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002083 }
2084 }
2085 }
2086 } else if (method_name[0] == '<') {
2087 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002088 bool is_init = (strcmp("<init>", method_name) == 0);
2089 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002090 if (UNLIKELY(!is_init && !is_clinit)) {
2091 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2092 } else {
2093 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2094 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002095 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002096 access_flags |= kAccConstructor;
2097 }
2098 }
2099 }
2100 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002101
Mathieu Chartier66f19252012-09-18 08:57:04 -07002102 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002103}
2104
Ian Rogers7b078e82014-09-10 14:44:24 -07002105void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002106 StackHandleScope<1> hs(self);
2107 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002108 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2109 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002110 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002111}
2112
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002113void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002114 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002115 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002116 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002117 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002118}
2119
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002120bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002121 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002122 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002123 mirror::DexCache* dex_cache = GetDexCache(i);
2124 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002125 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002126 }
2127 }
2128 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002129}
2130
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002131bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002132 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002133 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002134}
2135
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002136void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002137 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002138 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002139 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002140 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2141 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002142 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002143 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002144 if (log_new_dex_caches_roots_) {
2145 // TODO: This is not safe if we can remove dex caches.
2146 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2147 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002148}
2149
Brian Carlstromaded5f72011-10-07 17:15:04 -07002150void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002151 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002152 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002153 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002154 if (IsDexFileRegisteredLocked(dex_file)) {
2155 return;
2156 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002157 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002158 // Don't alloc while holding the lock, since allocation may need to
2159 // suspend all threads and another thread may need the dex_lock_ to
2160 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002161 StackHandleScope<1> hs(self);
2162 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002163 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2164 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002165 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002166 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002167 if (IsDexFileRegisteredLocked(dex_file)) {
2168 return;
2169 }
2170 RegisterDexFileLocked(dex_file, dex_cache);
2171 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002172}
2173
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002174void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002175 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002176 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002177 RegisterDexFileLocked(dex_file, dex_cache);
2178}
2179
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002180mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002181 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002182 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002183 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002184 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002185 if (dex_cache->GetDexFile() == &dex_file) {
2186 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002187 }
2188 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002189 // Search matching by location name.
2190 std::string location(dex_file.GetLocation());
2191 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002192 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002193 if (dex_cache->GetDexFile()->GetLocation() == location) {
2194 return dex_cache;
2195 }
2196 }
2197 // Failure, dump diagnostic and abort.
2198 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002199 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002200 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2201 }
2202 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002203 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002204}
2205
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002206void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002207 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08002208 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002209 mirror::DexCache* dex_cache = GetDexCache(i);
2210 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08002211 }
2212}
2213
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002214mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002215 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002216 if (UNLIKELY(klass == nullptr)) {
2217 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002218 }
2219 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002220}
2221
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002222mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2223 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002224 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07002225 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002226 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002227 StackHandleScope<1> hs(self);
2228 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002229 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002230 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002231 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002232 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
2233 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002234 mirror::Class* existing = InsertClass(descriptor, primitive_class,
2235 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002236 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002237 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07002238}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002239
Brian Carlstrombe977852011-07-19 14:54:54 -07002240// Create an array class (i.e. the class object for the array, not the
2241// array itself). "descriptor" looks like "[C" or "[[[[B" or
2242// "[Ljava/lang/String;".
2243//
2244// If "descriptor" refers to an array of primitives, look up the
2245// primitive type's internally-generated class object.
2246//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002247// "class_loader" is the class loader of the class that's referring to
2248// us. It's used to ensure that we're looking for the element type in
2249// the right context. It does NOT become the class loader for the
2250// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002251//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002252// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002253mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002254 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002255 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002256 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002257 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002258 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
2259 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002260 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002261 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002262 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002263 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
2264 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002265 if (component_type.Get() == nullptr) {
2266 DCHECK(self->IsExceptionPending());
2267 return nullptr;
2268 } else {
2269 self->ClearException();
2270 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002271 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002272 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2273 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2274 return nullptr;
2275 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002276 // See if the component type is already loaded. Array classes are
2277 // always associated with the class loader of their underlying
2278 // element type -- an array of Strings goes with the loader for
2279 // java/lang/String -- so we need to look for it there. (The
2280 // caller should have checked for the existence of the class
2281 // before calling here, but they did so with *their* class loader,
2282 // not the component type's loader.)
2283 //
2284 // If we find it, the caller adds "loader" to the class' initiating
2285 // loader list, which should prevent us from going through this again.
2286 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002287 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002288 // are the same, because our caller (FindClass) just did the
2289 // lookup. (Even if we get this wrong we still have correct behavior,
2290 // because we effectively do this lookup again when we add the new
2291 // class to the hash table --- necessary because of possible races with
2292 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002293 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002294 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002295 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002296 return new_class;
2297 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002298 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002299
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002300 // Fill out the fields in the Class.
2301 //
2302 // It is possible to execute some methods against arrays, because
2303 // all arrays are subclasses of java_lang_Object_, so we need to set
2304 // up a vtable. We can just point at the one in java_lang_Object_.
2305 //
2306 // Array classes are simple enough that we don't need to do a full
2307 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002308 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002309 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002310 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002311 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002312 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002313 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002314 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002315 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002316 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002317 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002318 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002319 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002320 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002321 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002322 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002323 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002324 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002325 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002326 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002327 }
2328 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002329 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002330 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002331 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002332 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002333 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002334 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002335 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002336 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002337 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002338 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002339 new_class->SetSuperClass(java_lang_Object);
2340 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002341 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002342 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002343 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002344 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002345 StackHandleScope<mirror::Class::kImtSize> hs2(self,
2346 Runtime::Current()->GetImtUnimplementedMethod());
2347 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002348 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002349 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002350 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002351 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002352
2353
2354 // All arrays have java/lang/Cloneable and java/io/Serializable as
2355 // interfaces. We need to set that up here, so that stuff like
2356 // "instanceof" works right.
2357 //
2358 // Note: The GC could run during the call to FindSystemClass,
2359 // so we need to make sure the class object is GC-valid while we're in
2360 // there. Do this by clearing the interface list so the GC will just
2361 // think that the entries are null.
2362
2363
2364 // Use the single, global copies of "interfaces" and "iftable"
2365 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002366 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002367 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002368 CHECK(array_iftable != nullptr);
2369 new_class->SetIfTable(array_iftable);
2370 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002371
Elliott Hughes00626c22013-06-14 15:04:14 -07002372 // Inherit access flags from the component type.
2373 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2374 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2375 access_flags &= kAccJavaFlagsMask;
2376 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002377 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002378 access_flags |= kAccAbstract | kAccFinal;
2379 access_flags &= ~kAccInterface;
2380
2381 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002382
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002383 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002384 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002385 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002386 }
2387 // Another thread must have loaded the class after we
2388 // started but before we finished. Abandon what we've
2389 // done.
2390 //
2391 // (Yes, this happens.)
2392
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002393 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002394}
2395
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002396mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002397 switch (type) {
2398 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002399 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002400 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002401 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002402 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002403 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002404 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002405 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002406 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002407 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002408 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002409 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002410 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002411 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002412 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002413 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002414 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002415 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002416 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002417 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002418 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002419 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002420 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002421 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002422}
2423
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002424mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2425 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002426 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002427 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002428 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002429 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08002430 source += " from ";
2431 source += dex_cache->GetLocation()->ToModifiedUtf8();
2432 }
2433 LOG(INFO) << "Loaded class " << descriptor << source;
2434 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002435 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002436 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002437 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002438 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002439 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002440 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002441 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002442 // Check a class loaded with the system class loader matches one in the image if the class
2443 // is in the image.
2444 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002445 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002446 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002447 }
2448 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002449 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002450 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002451 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002452 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002453 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002454 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002455}
2456
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002457mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
2458 size_t hash) {
2459 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002460 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
2461 hash);
2462 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002463 CHECK(klass->IsProxyClass());
2464 return nullptr;
2465 }
2466
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002467 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002468 CHECK_NE(existing, klass) << descriptor;
2469 CHECK(!existing->IsResolved()) << descriptor;
2470 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
2471
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002472 CHECK(!klass->IsTemp()) << descriptor;
2473 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
2474 dex_cache_image_class_lookup_required_) {
2475 // Check a class loaded with the system class loader matches one in the image if the class
2476 // is in the image.
2477 existing = LookupClassFromImage(descriptor);
2478 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002479 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002480 }
2481 }
2482 VerifyObject(klass);
2483
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002484 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002485 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002486 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002487 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002488 }
2489
2490 return existing;
2491}
2492
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002493bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002494 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002495 auto pair = std::make_pair(descriptor, class_loader);
2496 auto it = class_table_.Find(pair);
2497 if (it != class_table_.end()) {
2498 class_table_.Erase(it);
2499 return true;
2500 }
2501 it = pre_zygote_class_table_.Find(pair);
2502 if (it != pre_zygote_class_table_.end()) {
2503 pre_zygote_class_table_.Erase(it);
2504 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08002505 }
2506 return false;
2507}
2508
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002509mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002510 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002511 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002512 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002513 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002514 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002515 return result;
2516 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07002517 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002518 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
2519 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002520 } else {
2521 // Lookup failed but need to search dex_caches_.
2522 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002523 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002524 InsertClass(descriptor, result, hash);
2525 } else {
2526 // Searching the image dex files/caches failed, we don't want to get into this situation
2527 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2528 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07002529 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002530 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2531 MoveImageClassesToClassTable();
2532 }
2533 }
2534 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002535 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002536}
2537
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002538mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002539 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002540 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002541 auto descriptor_pair = std::make_pair(descriptor, class_loader);
2542 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
2543 if (it == pre_zygote_class_table_.end()) {
2544 it = class_table_.FindWithHash(descriptor_pair, hash);
2545 if (it == class_table_.end()) {
2546 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07002547 }
2548 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002549 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002550}
2551
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002552static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
2553 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2554 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002555 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002556 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2557 return root->AsObjectArray<mirror::DexCache>();
2558}
2559
2560void ClassLinker::MoveImageClassesToClassTable() {
2561 Thread* self = Thread::Current();
2562 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2563 if (!dex_cache_image_class_lookup_required_) {
2564 return; // All dex cache classes are already in the class table.
2565 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002566 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002567 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002568 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002569 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2570 mirror::DexCache* dex_cache = dex_caches->Get(i);
2571 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
2572 for (int32_t j = 0; j < types->GetLength(); j++) {
2573 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002574 if (klass != nullptr) {
2575 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002576 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002577 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002578 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
2579 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002580 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002581 << PrettyClassAndClassLoader(klass);
2582 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002583 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002584 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002585 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002586 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002587 }
2588 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002589 }
2590 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002591 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002592}
2593
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002594void ClassLinker::MoveClassTableToPreZygote() {
2595 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2596 DCHECK(pre_zygote_class_table_.Empty());
2597 pre_zygote_class_table_ = std::move(class_table_);
2598 class_table_.Clear();
2599}
2600
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002601mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002602 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002603 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2604 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
2605 mirror::DexCache* dex_cache = dex_caches->Get(i);
2606 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00002607 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002608 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002609 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002610 const DexFile::TypeId* type_id =
2611 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002612 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002613 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
2614 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002615 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002616 return klass;
2617 }
2618 }
2619 }
2620 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002621 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002622}
2623
2624void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
2625 result.clear();
2626 if (dex_cache_image_class_lookup_required_) {
2627 MoveImageClassesToClassTable();
2628 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002629 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2630 while (true) {
2631 auto it = class_table_.Find(descriptor);
2632 if (it == class_table_.end()) {
2633 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002634 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002635 result.push_back(it->Read());
2636 class_table_.Erase(it);
2637 }
2638 for (mirror::Class* k : result) {
2639 class_table_.Insert(GcRoot<mirror::Class>(k));
2640 }
2641 size_t pre_zygote_start = result.size();
2642 // Now handle the pre zygote table.
2643 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
2644 // called from the debugger.
2645 while (true) {
2646 auto it = pre_zygote_class_table_.Find(descriptor);
2647 if (it == pre_zygote_class_table_.end()) {
2648 break;
2649 }
2650 result.push_back(it->Read());
2651 pre_zygote_class_table_.Erase(it);
2652 }
2653 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
2654 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002655 }
2656}
2657
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002658void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002659 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002660 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08002661
Ian Rogers9ffb0392012-09-10 11:56:50 -07002662 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002663 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07002664 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07002665 return;
2666 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002667 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002668 return;
2669 }
jeffhao98eacac2011-09-14 16:11:53 -07002670
Ian Rogers9ffb0392012-09-10 11:56:50 -07002671 // The class might already be erroneous, for example at compile time if we attempted to verify
2672 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002673 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002674 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002675 return;
2676 }
2677
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002678 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002679 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002680 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002681 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002682 << PrettyClass(klass.Get());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002683 CHECK(!Runtime::Current()->IsAotCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002684 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002685 }
jeffhao98eacac2011-09-14 16:11:53 -07002686
Jeff Hao4a200f52014-04-01 14:58:49 -07002687 // Skip verification if disabled.
2688 if (!Runtime::Current()->IsVerificationEnabled()) {
2689 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07002690 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07002691 return;
2692 }
2693
Ian Rogers9ffb0392012-09-10 11:56:50 -07002694 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002695 StackHandleScope<2> hs(self);
2696 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002697 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07002698 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002699 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002700
2701 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002702 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002703 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002704 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07002705 std::string error_msg(
2706 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
2707 PrettyDescriptor(klass.Get()).c_str(),
2708 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08002709 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002710 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002711 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002712 self->ClearException();
2713 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002714 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
2715 if (cause.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002716 self->GetException()->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002717 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08002718 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002719 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00002720 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
2721 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002722 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002723 return;
2724 }
2725 }
2726
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002727 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07002728 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002729 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002730 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002731 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002732 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002733 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002734 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002735 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
2736 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002737 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07002738 return;
2739 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002740 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08002741 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07002742 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002743 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002744 Runtime::Current()->IsAotCompiler(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002745 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002746 }
2747 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07002748 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002749 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07002750 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2751 << " because: " << error_msg;
2752 }
Ian Rogers1f539342012-10-03 21:09:42 -07002753 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002754 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002755 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002756 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002757 // Even though there were no verifier failures we need to respect whether the super-class
2758 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002759 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002760 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002761 } else {
2762 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002763 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002764 // Pretend a soft failure occured so that we don't consider the class verified below.
2765 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002766 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002767 } else {
2768 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
2769 // Soft failures at compile time should be retried at runtime. Soft
2770 // failures at runtime will be handled by slow paths in the generated
2771 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002772 if (Runtime::Current()->IsAotCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002773 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002774 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002775 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002776 // As this is a fake verified status, make sure the methods are _not_ marked preverified
2777 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07002778 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002779 }
2780 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07002781 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002782 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08002783 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2784 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002785 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002786 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002787 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002788 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002789 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002790 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002791 // Let the interpreter know it by setting the kAccPreverified flag onto each
2792 // method.
2793 // Note: we're going here during compilation and at runtime. When we set the
2794 // kAccPreverified flag when compiling image classes, the flag is recorded
2795 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07002796 EnsurePreverifiedMethods(klass);
2797 }
2798}
2799
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002800void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002801 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002802 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07002803 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002804 }
jeffhao98eacac2011-09-14 16:11:53 -07002805}
2806
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002807bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
2808 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002809 // If we're compiling, we can only verify the class using the oat file if
2810 // we are not compiling the image or if the class we're verifying is not part of
2811 // the app. In other words, we will only check for preverification of bootclasspath
2812 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002813 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002814 // Are we compiling the bootclasspath?
2815 if (!Runtime::Current()->UseCompileTimeClassPath()) {
2816 return false;
2817 }
2818 // We are compiling an app (not the image).
2819
2820 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002821 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002822 return false;
2823 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002824 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002825
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002826 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002827 // In case we run without an image there won't be a backing oat file.
2828 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07002829 return false;
2830 }
2831
Andreas Gampe76bd8802014-12-10 16:43:58 -08002832 // We may be running with a preopted oat file but without image. In this case,
2833 // we don't skip verification of preverified classes to ensure we initialize
2834 // dex caches with all types resolved during verification.
2835 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
2836 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
2837 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
2838 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002839 if (!Runtime::Current()->IsAotCompiler() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08002840 !Runtime::Current()->GetHeap()->HasImageSpace() &&
2841 klass->GetClassLoader() != nullptr) {
2842 return false;
2843 }
2844
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002845 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002846 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002847 if (oat_file_class_status == mirror::Class::kStatusVerified ||
2848 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002849 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002850 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002851 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07002852 // Compile time verification failed with a soft error. Compile time verification can fail
2853 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08002854 // class ... {
2855 // Foo x;
2856 // .... () {
2857 // if (...) {
2858 // v1 gets assigned a type of resolved class Foo
2859 // } else {
2860 // v1 gets assigned a type of unresolved class Bar
2861 // }
2862 // iput x = v1
2863 // } }
2864 // when we merge v1 following the if-the-else it results in Conflict
2865 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2866 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2867 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2868 // at compile time).
2869 return false;
2870 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002871 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07002872 // Compile time verification failed with a hard error. This is caused by invalid instructions
2873 // in the class. These errors are unrecoverable.
2874 return false;
2875 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002876 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002877 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2878 // not loading the class.
2879 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2880 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002881 return false;
2882 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002883 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002884 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002885 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07002886 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08002887 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002888}
2889
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002890void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002891 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002892 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2893 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2894 }
2895 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2896 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2897 }
2898}
2899
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002900void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07002901 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002902 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2903 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002904 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002905 return; // native or abstract method
2906 }
2907 if (code_item->tries_size_ == 0) {
2908 return; // nothing to process
2909 }
Ian Rogers13735952014-10-08 12:43:28 -07002910 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002911 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2912 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2913 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2914 CatchHandlerIterator iterator(handlers_ptr);
2915 for (; iterator.HasNext(); iterator.Next()) {
2916 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2917 // unresolved exception types will be ignored by exception delivery
2918 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002919 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002920 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002921 DCHECK(Thread::Current()->IsExceptionPending());
2922 Thread::Current()->ClearException();
2923 }
2924 }
2925 }
2926 handlers_ptr = iterator.EndDataPointer();
2927 }
2928}
2929
Brian Carlstromea46f952013-07-30 01:26:50 -07002930static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002931static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
2932 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08002933
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07002934mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07002935 jobjectArray interfaces, jobject loader,
2936 jobjectArray methods, jobjectArray throws) {
2937 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002938 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002939 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002940 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002941 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002942 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002943 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002944 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002945 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002946 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07002947 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
2948 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002949 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08002950 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002951 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002952 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002953 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002954 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08002955
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002956 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07002957 {
2958 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002959 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002960 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002961 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002962 }
2963 klass->SetSFields(sfields);
2964 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002965 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
2966 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002967 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
2968 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002969 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002970 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002971 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002972 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002973 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002974 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002975 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
2976 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002977 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
2978 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002979 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002980 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002981 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002982 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002983 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002984 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002985 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002986
Ian Rogers466bb252011-10-14 03:29:56 -07002987 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07002988 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002989 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002990 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002991 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002992 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002993 }
2994 klass->SetDirectMethods(directs);
2995 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002996 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002997 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002998 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002999 }
3000 klass->SetDirectMethod(0, constructor);
3001 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003002
Mathieu Chartier590fee92013-09-13 13:46:47 -07003003 // Create virtual method using specified prototypes.
3004 size_t num_virtual_methods =
3005 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003006 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003007 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3008 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003009 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003010 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003011 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003012 }
3013 klass->SetVirtualMethods(virtuals);
3014 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003015 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003016 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003017 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3018 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003019 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003020 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003021 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003022 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003023 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003024 }
3025 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003026 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003027
3028 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003029 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003030 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003031
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003032 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3033 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003034 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003035 // Must hold lock on object when resolved.
3036 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003037 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003038 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003039 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003040 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003041 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003042 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003043 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003044 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003045
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003046 CHECK(klass->IsRetired());
3047 CHECK_NE(klass.Get(), new_class);
3048 klass.Assign(new_class);
3049
3050 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003051 interfaces_sfield->SetObject<false>(klass.Get(),
3052 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003053 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003054 throws_sfield->SetObject<false>(klass.Get(),
3055 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003056
3057 {
3058 // Lock on klass is released. Lock new class object.
3059 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003060 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003061 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003062
3063 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003064 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003065 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003066 CheckProxyConstructor(klass->GetDirectMethod(0));
3067 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003068 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003069 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3070 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003071 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3072 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003073 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003074 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003075
Mathieu Chartier590fee92013-09-13 13:46:47 -07003076 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003077 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003078 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003079 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3080
3081 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003082 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003083 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003084
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003085 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003086 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003087 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003088 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003089 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003090 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3091 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003092 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003093 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003094}
3095
Ian Rogersef7d42f2014-01-06 12:55:46 -08003096std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003097 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003098 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003099 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003100 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3101}
3102
Ian Rogersef7d42f2014-01-06 12:55:46 -08003103mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3104 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003105 DCHECK(proxy_class->IsProxyClass());
3106 DCHECK(proxy_method->IsProxyMethod());
3107 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003108 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003109 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003110 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003111 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003112 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003113 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003114 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003115 break;
3116 }
3117 }
3118 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003119 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003120 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003121 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003122 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003123 return resolved_method;
3124}
3125
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003126
Brian Carlstromea46f952013-07-30 01:26:50 -07003127mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003128 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003129 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003130 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003131 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003132 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003133 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3134 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003135 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3136 // constructor method.
3137 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3138 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003139 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3140 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003141 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3142 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003143 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003144 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003145 }
Ian Rogers466bb252011-10-14 03:29:56 -07003146 // Make this constructor public and fix the class to be our Proxy version
3147 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003148 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003149 return constructor;
3150}
3151
Brian Carlstromea46f952013-07-30 01:26:50 -07003152static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003153 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003154 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003155 CHECK_STREQ(constructor->GetName(), "<init>");
3156 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3157 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003158 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003159}
3160
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003161mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003162 Handle<mirror::Class> klass,
3163 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003164 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3165 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003166 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003167 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003168 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003169 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003170 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003171 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003172 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003173 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003174 }
Ian Rogers466bb252011-10-14 03:29:56 -07003175
3176 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3177 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003178 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003179 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003180
Ian Rogers466bb252011-10-14 03:29:56 -07003181 // At runtime the method looks like a reference and argument saving method, clone the code
3182 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003183 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003184 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003185
Ian Rogersc2b44472011-12-14 21:17:17 -08003186 return method;
3187}
Jesse Wilson95caa792011-10-12 18:14:17 -04003188
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003189static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3190 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003191 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003192 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003193 CHECK(!prototype->IsFinal());
3194 CHECK(method->IsFinal());
3195 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003196
3197 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3198 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07003199 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
3200 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08003201 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3202
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003203 CHECK_STREQ(method->GetName(), prototype->GetName());
3204 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003205 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07003206 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04003207}
3208
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003209static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3210 bool can_init_parents)
3211 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003212 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003213 return true;
3214 }
3215 if (!can_init_statics) {
3216 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07003217 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003218 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003219 return false;
3220 }
3221 // Check if there are encoded static values needing initialization.
3222 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003223 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003224 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003225 if (dex_class_def->static_values_off_ != 0) {
3226 return false;
3227 }
3228 }
3229 }
3230 if (!klass->IsInterface() && klass->HasSuperClass()) {
3231 mirror::Class* super_class = klass->GetSuperClass();
3232 if (!can_init_parents && !super_class->IsInitialized()) {
3233 return false;
3234 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003235 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003236 return false;
3237 }
3238 }
3239 }
3240 return true;
3241}
3242
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003243bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07003244 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003245 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3246
3247 // Are we already initialized and therefore done?
3248 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3249 // an initialized class will never change its state.
3250 if (klass->IsInitialized()) {
3251 return true;
3252 }
3253
3254 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003255 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003256 return false;
3257 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003258
Ian Rogers7b078e82014-09-10 14:44:24 -07003259 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003260 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003261 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003262 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003263
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003264 // Re-check under the lock in case another thread initialized ahead of us.
3265 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003266 return true;
3267 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003268
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003269 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003270 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003271 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003272 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003273 return false;
3274 }
3275
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003276 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003277
3278 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003279 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003280 if (!klass->IsVerified()) {
3281 // We failed to verify, expect either the klass to be erroneous or verification failed at
3282 // compile time.
3283 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003284 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003285 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003286 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003287 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003288 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003289 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003290 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07003291 } else {
3292 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003293 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003294 }
3295
Brian Carlstromd1422f82011-09-28 11:37:09 -07003296 // If the class is kStatusInitializing, either this thread is
3297 // initializing higher up the stack or another thread has beat us
3298 // to initializing and we need to wait. Either way, this
3299 // invocation of InitializeClass will not be responsible for
3300 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003301 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07003302 // Could have got an exception during verification.
3303 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003304 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003305 return false;
3306 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003307 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003308 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003309 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003310 return true;
3311 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003312 // No. That's fine. Wait for another thread to finish initializing.
3313 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003314 }
3315
3316 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003317 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003318 return false;
3319 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003320 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003321
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003322 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003323
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003324 // From here out other threads may observe that we're initializing and so changes of state
3325 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003326 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003327 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003328
3329 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003330 }
3331
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003332 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003333 if (!klass->IsInterface() && klass->HasSuperClass()) {
3334 mirror::Class* super_class = klass->GetSuperClass();
3335 if (!super_class->IsInitialized()) {
3336 CHECK(!super_class->IsInterface());
3337 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003338 StackHandleScope<1> hs(self);
3339 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07003340 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003341 if (!super_initialized) {
3342 // The super class was verified ahead of entering initializing, we should only be here if
3343 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003344 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003345 << "Super class initialization failed for "
3346 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003347 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003348 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003349 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003350 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003351 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003352 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003353 return false;
3354 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003355 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003356 }
3357
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003358 const size_t num_static_fields = klass->NumStaticFields();
3359 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003360 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003361 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003362 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07003363 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003364 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003365 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003366
3367 // Eagerly fill in static fields so that the we don't have to do as many expensive
3368 // Class::FindStaticField in ResolveField.
3369 for (size_t i = 0; i < num_static_fields; ++i) {
3370 mirror::ArtField* field = klass->GetStaticField(i);
3371 const uint32_t field_idx = field->GetDexFieldIndex();
3372 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
3373 if (resolved_field == nullptr) {
3374 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07003375 } else {
3376 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003377 }
3378 }
3379
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003380 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
3381 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07003382 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003383 ClassDataItemIterator field_it(dex_file, class_data);
3384 if (value_it.HasNext()) {
3385 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003386 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003387 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003388 StackHandleScope<1> hs2(self);
3389 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003390 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003391 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003392 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003393 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003394 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003395 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003396 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003397 }
3398 }
3399 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003400
Ian Rogersd91d6d62013-09-25 20:26:14 -07003401 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003402 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003403 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003404 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003405 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003406 }
3407
Ian Rogers7b078e82014-09-10 14:44:24 -07003408 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003409 uint64_t t1 = NanoTime();
3410
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003411 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003412 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003413 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003414
3415 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003416 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003417 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003418 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003419 } else if (Runtime::Current()->IsTransactionAborted()) {
3420 // The exception thrown when the transaction aborted has been caught and cleared
3421 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01003422 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
3423 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003424 Runtime::Current()->ThrowInternalErrorForAbortedTransaction(self);
3425 klass->SetStatus(mirror::Class::kStatusError, self);
3426 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003427 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003428 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3429 RuntimeStats* thread_stats = self->GetStats();
3430 ++global_stats->class_init_count;
3431 ++thread_stats->class_init_count;
3432 global_stats->class_init_time_ns += (t1 - t0);
3433 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003434 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003435 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003436 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003437 std::string temp;
3438 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003439 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003440 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003441 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003442 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003443 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003444 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003445 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003446}
3447
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003448bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003449 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003450 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003451 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003452 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003453 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08003454 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003455
3456 // When we wake up, repeat the test for init-in-progress. If
3457 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07003458 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003459 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003460 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003461 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003462 return false;
3463 }
3464 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003465 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003466 continue;
3467 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003468 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
3469 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003470 // Compile time initialization failed.
3471 return false;
3472 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003473 if (klass->IsErroneous()) {
3474 // The caller wants an exception, but it was thrown in a
3475 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003476 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003477 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003478 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003479 return false;
3480 }
3481 if (klass->IsInitialized()) {
3482 return true;
3483 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003484 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003485 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003486 }
Ian Rogers07140832014-09-30 15:43:59 -07003487 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003488}
3489
Ian Rogersb5fb2072014-12-02 17:22:02 -08003490static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
3491 Handle<mirror::ArtMethod> method1,
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003492 Handle<mirror::ArtMethod> method2,
3493 std::string* error_msg)
Ian Rogersb5fb2072014-12-02 17:22:02 -08003494 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3495 {
3496 StackHandleScope<1> hs(self);
3497 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
Vladimir Marko862f43c2015-02-10 18:22:57 +00003498 mirror::Class* other_return_type = method2->GetReturnType();
3499 // NOTE: return_type.Get() must be sequenced after method2->GetReturnType().
3500 if (UNLIKELY(other_return_type != return_type.Get())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003501 *error_msg = StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
3502 PrettyClassAndClassLoader(return_type.Get()).c_str(),
3503 return_type.Get(),
3504 PrettyClassAndClassLoader(other_return_type).c_str(),
3505 other_return_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003506 return false;
3507 }
3508 }
3509 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
3510 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
3511 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003512 if (types2 != nullptr && types2->Size() != 0) {
3513 *error_msg = StringPrintf("Type list mismatch with %s",
3514 PrettyMethod(method2.Get(), true).c_str());
3515 return false;
3516 }
3517 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003518 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003519 if (types1->Size() != 0) {
3520 *error_msg = StringPrintf("Type list mismatch with %s",
3521 PrettyMethod(method2.Get(), true).c_str());
3522 return false;
3523 }
3524 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003525 }
3526 uint32_t num_types = types1->Size();
3527 if (UNLIKELY(num_types != types2->Size())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003528 *error_msg = StringPrintf("Type list mismatch with %s",
3529 PrettyMethod(method2.Get(), true).c_str());
Ian Rogersb5fb2072014-12-02 17:22:02 -08003530 return false;
3531 }
3532 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00003533 StackHandleScope<1> hs(self);
3534 Handle<mirror::Class> param_type(hs.NewHandle(
3535 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true)));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003536 mirror::Class* other_param_type =
3537 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
Vladimir Marko862f43c2015-02-10 18:22:57 +00003538 // NOTE: param_type.Get() must be sequenced after method2->GetClassFromTypeIndex(...).
3539 if (UNLIKELY(param_type.Get() != other_param_type)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003540 *error_msg = StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
3541 i,
3542 PrettyClassAndClassLoader(param_type.Get()).c_str(),
3543 param_type.Get(),
3544 PrettyClassAndClassLoader(other_param_type).c_str(),
3545 other_param_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003546 return false;
3547 }
3548 }
3549 return true;
3550}
3551
3552
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003553bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003554 if (klass->IsInterface()) {
3555 return true;
3556 }
Ian Rogers151f2212014-05-06 11:27:27 -07003557 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07003558 Thread* self = Thread::Current();
3559 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003560 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
3561 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003562 if (klass->HasSuperClass() &&
3563 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003564 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003565 h_m.Assign(klass->GetVTableEntry(i));
3566 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003567 if (h_m.Get() != super_h_m.Get()) {
3568 std::string error_msg;
3569 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3570 ThrowLinkageError(klass.Get(),
3571 "Class %s method %s resolves differently in superclass %s: %s",
3572 PrettyDescriptor(klass.Get()).c_str(),
3573 PrettyMethod(h_m.Get()).c_str(),
3574 PrettyDescriptor(klass->GetSuperClass()).c_str(),
3575 error_msg.c_str());
3576 return false;
3577 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003578 }
3579 }
3580 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003581 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07003582 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
3583 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
3584 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003585 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
3586 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003587 if (h_m.Get() != super_h_m.Get()) {
3588 std::string error_msg;
3589 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3590 ThrowLinkageError(klass.Get(),
3591 "Class %s method %s resolves differently in interface %s: %s",
3592 PrettyDescriptor(klass.Get()).c_str(),
3593 PrettyMethod(h_m.Get()).c_str(),
3594 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str(),
3595 error_msg.c_str());
3596 return false;
3597 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003598 }
3599 }
3600 }
3601 }
3602 return true;
3603}
3604
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003605bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
3606 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003607 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003608 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003609 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003610 return true;
3611 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003612 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003613 if (!success) {
3614 if (can_init_fields && can_init_parents) {
3615 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
3616 }
3617 } else {
3618 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08003619 }
3620 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003621}
3622
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003623void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
3624 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
3625 if (fields != nullptr) {
3626 for (int index = 0; index < fields->GetLength(); index ++) {
3627 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
3628 fields->Get(index)->SetDeclaringClass(new_class);
3629 }
3630 }
3631 }
3632
3633 fields = new_class->GetSFields();
3634 if (fields != nullptr) {
3635 for (int index = 0; index < fields->GetLength(); index ++) {
3636 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
3637 fields->Get(index)->SetDeclaringClass(new_class);
3638 }
3639 }
3640 }
3641
3642 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
3643 if (methods != nullptr) {
3644 for (int index = 0; index < methods->GetLength(); index ++) {
3645 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3646 methods->Get(index)->SetDeclaringClass(new_class);
3647 }
3648 }
3649 }
3650
3651 methods = new_class->GetVirtualMethods();
3652 if (methods != nullptr) {
3653 for (int index = 0; index < methods->GetLength(); index ++) {
3654 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3655 methods->Get(index)->SetDeclaringClass(new_class);
3656 }
3657 }
3658 }
3659}
3660
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003661bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
3662 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003663 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003664 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003665
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003666 if (!LinkSuperClass(klass)) {
3667 return false;
3668 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003669 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
3670 self, Runtime::Current()->GetImtUnimplementedMethod());
3671 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003672 return false;
3673 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003674 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003675 return false;
3676 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003677 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07003678 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003679 return false;
3680 }
3681 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003682 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003683
3684 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
3685 // We don't need to retire this class as it has no embedded tables or it was created the
3686 // correct size during class linker initialization.
3687 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
3688
3689 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003690 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003691 }
3692
3693 // This will notify waiters on klass that saw the not yet resolved
3694 // class in the class_table_ during EnsureResolved.
3695 klass->SetStatus(mirror::Class::kStatusResolved, self);
3696 *new_class = klass.Get();
3697 } else {
3698 CHECK(!klass->IsResolved());
3699 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003700 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003701 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003702 CHECK(self->IsExceptionPending()); // Expect an OOME.
3703 klass->SetStatus(mirror::Class::kStatusError, self);
3704 return false;
3705 }
3706
3707 CHECK_EQ((*new_class)->GetClassSize(), class_size);
3708 StackHandleScope<1> hs(self);
3709 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
3710 ObjectLock<mirror::Class> lock(self, new_class_h);
3711
3712 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
3713
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003714 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
3715 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003716 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003717
3718 // This will notify waiters on temp class that saw the not yet resolved class in the
3719 // class_table_ during EnsureResolved.
3720 klass->SetStatus(mirror::Class::kStatusRetired, self);
3721
3722 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
3723 // This will notify waiters on new_class that saw the not yet resolved
3724 // class in the class_table_ during EnsureResolved.
3725 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003726 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003727 return true;
3728}
3729
Andreas Gampefd9eb392014-11-06 16:52:58 -08003730static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
3731 size_t* virtual_methods,
3732 size_t* direct_methods,
3733 size_t* static_fields,
3734 size_t* instance_fields) {
3735 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
3736
3737 while (dex_data.HasNextStaticField()) {
3738 dex_data.Next();
3739 (*static_fields)++;
3740 }
3741 while (dex_data.HasNextInstanceField()) {
3742 dex_data.Next();
3743 (*instance_fields)++;
3744 }
3745 while (dex_data.HasNextDirectMethod()) {
3746 (*direct_methods)++;
3747 dex_data.Next();
3748 }
3749 while (dex_data.HasNextVirtualMethod()) {
3750 (*virtual_methods)++;
3751 dex_data.Next();
3752 }
3753 DCHECK(!dex_data.HasNext());
3754}
3755
3756static void DumpClass(std::ostream& os,
3757 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
3758 const char* suffix) {
3759 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
3760 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
3761 os << " Static fields:\n";
3762 while (dex_data.HasNextStaticField()) {
3763 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3764 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3765 dex_data.Next();
3766 }
3767 os << " Instance fields:\n";
3768 while (dex_data.HasNextInstanceField()) {
3769 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3770 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3771 dex_data.Next();
3772 }
3773 os << " Direct methods:\n";
3774 while (dex_data.HasNextDirectMethod()) {
3775 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3776 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3777 dex_data.Next();
3778 }
3779 os << " Virtual methods:\n";
3780 while (dex_data.HasNextVirtualMethod()) {
3781 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3782 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3783 dex_data.Next();
3784 }
3785}
3786
3787static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3788 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
3789 std::ostringstream os;
3790 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
3791 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
3792 return os.str();
3793}
3794
3795
3796// Very simple structural check on whether the classes match. Only compares the number of
3797// methods and fields.
3798static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3799 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
3800 std::string* error_msg) {
3801 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
3802 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
3803
3804 // Counters for current dex file.
3805 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
3806 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
3807 &dex_instance_fields1);
3808 // Counters for compile-time dex file.
3809 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
3810 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
3811 &dex_instance_fields2);
3812
3813 if (dex_virtual_methods1 != dex_virtual_methods2) {
3814 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3815 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
3816 dex_virtual_methods2, class_dump.c_str());
3817 return false;
3818 }
3819 if (dex_direct_methods1 != dex_direct_methods2) {
3820 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3821 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
3822 dex_direct_methods2, class_dump.c_str());
3823 return false;
3824 }
3825 if (dex_static_fields1 != dex_static_fields2) {
3826 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3827 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
3828 dex_static_fields2, class_dump.c_str());
3829 return false;
3830 }
3831 if (dex_instance_fields1 != dex_instance_fields2) {
3832 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3833 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
3834 dex_instance_fields2, class_dump.c_str());
3835 return false;
3836 }
3837
3838 return true;
3839}
3840
3841// Checks whether a the super-class changed from what we had at compile-time. This would
3842// invalidate quickening.
3843static bool CheckSuperClassChange(Handle<mirror::Class> klass,
3844 const DexFile& dex_file,
3845 const DexFile::ClassDef& class_def,
3846 mirror::Class* super_class)
3847 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3848 // Check for unexpected changes in the superclass.
3849 // Quick check 1) is the super_class class-loader the boot class loader? This always has
3850 // precedence.
3851 if (super_class->GetClassLoader() != nullptr &&
3852 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
3853 // which is implied by different dex cache.
3854 klass->GetDexCache() != super_class->GetDexCache()) {
3855 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
3856 // definition for the super-class, and (b) the files are in separate oat files. The oat files
3857 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
3858 const OatFile* class_oat_file = dex_file.GetOatFile();
3859 if (class_oat_file != nullptr) {
3860 const OatFile* loaded_super_oat_file = super_class->GetDexFile().GetOatFile();
3861 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
3862 // Now check (a).
3863 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
3864 if (super_class_def != nullptr) {
3865 // Uh-oh, we found something. Do our check.
3866 std::string error_msg;
3867 if (!SimpleStructuralCheck(dex_file, *super_class_def,
3868 super_class->GetDexFile(), *super_class->GetClassDef(),
3869 &error_msg)) {
3870 // Print a warning to the log. This exception might be caught, e.g., as common in test
3871 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
3872 // only save the type of the exception.
3873 LOG(WARNING) << "Incompatible structural change detected: " <<
3874 StringPrintf(
3875 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3876 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3877 class_oat_file->GetLocation().c_str(),
3878 loaded_super_oat_file->GetLocation().c_str(),
3879 error_msg.c_str());
3880 ThrowIncompatibleClassChangeError(klass.Get(),
3881 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3882 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3883 class_oat_file->GetLocation().c_str(),
3884 loaded_super_oat_file->GetLocation().c_str(),
3885 error_msg.c_str());
3886 return false;
3887 }
3888 }
3889 }
3890 }
3891 }
3892 return true;
3893}
3894
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003895bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003896 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003897 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3898 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003899 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003900 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003901 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003902 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003903 return false;
3904 }
Ian Rogersbe125a92012-01-11 15:19:49 -08003905 // Verify
3906 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003907 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003908 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003909 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08003910 return false;
3911 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003912 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003913 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08003914
3915 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
3916 DCHECK(Thread::Current()->IsExceptionPending());
3917 return false;
3918 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003919 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003920 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003921 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003922 for (size_t i = 0; i < interfaces->Size(); i++) {
3923 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003924 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003925 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003926 DCHECK(Thread::Current()->IsExceptionPending());
3927 return false;
3928 }
3929 // Verify
3930 if (!klass->CanAccess(interface)) {
3931 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003932 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003933 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003934 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003935 return false;
3936 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003937 }
3938 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003939 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003940 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003941 return true;
3942}
3943
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003944bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003945 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003946 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003947 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003948 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003949 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003950 return false;
3951 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003952 return true;
3953 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003954 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003955 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
3956 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003957 return false;
3958 }
3959 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003960 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003961 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003962 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003963 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003964 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003965 return false;
3966 }
3967 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003968 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003969 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003970 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003971 return false;
3972 }
Elliott Hughes20cde902011-10-04 17:37:27 -07003973
Brian Carlstromf3632832014-05-20 15:36:53 -07003974 // Inherit kAccClassIsFinalizable from the superclass in case this
3975 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07003976 if (super->IsFinalizable()) {
3977 klass->SetFinalizable();
3978 }
3979
Elliott Hughes2da50362011-10-10 16:57:08 -07003980 // Inherit reference flags (if any) from the superclass.
3981 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
3982 if (reference_flags != 0) {
3983 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
3984 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07003985 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07003986 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003987 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003988 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003989 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07003990 return false;
3991 }
Elliott Hughes2da50362011-10-10 16:57:08 -07003992
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003993 if (kIsDebugBuild) {
3994 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003995 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003996 CHECK(super->IsResolved());
3997 super = super->GetSuperClass();
3998 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003999 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004000 return true;
4001}
4002
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004003// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004004bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004005 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4006 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004007 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004008 if (klass->IsInterface()) {
4009 // No vtable.
4010 size_t count = klass->NumVirtualMethods();
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004011 if (!IsUint<16>(count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004012 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004013 return false;
4014 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004015 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004016 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004017 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004018 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4019 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004020 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004021 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004022}
4023
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004024// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4025// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4026// caches in the implementation below.
4027class MethodNameAndSignatureComparator FINAL : public ValueObject {
4028 public:
4029 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4030 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4031 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4032 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004033 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4034 }
4035
4036 const char* GetName() {
4037 if (name_ == nullptr) {
4038 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4039 }
4040 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004041 }
4042
4043 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4044 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4045 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4046 const DexFile* other_dex_file = other->GetDexFile();
4047 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4048 if (dex_file_ == other_dex_file) {
4049 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4050 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004051 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004052 uint32_t other_name_len;
4053 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4054 &other_name_len);
4055 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4056 return false;
4057 }
4058 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4059 }
4060
4061 private:
4062 // Dex file for the method to compare against.
4063 const DexFile* const dex_file_;
4064 // MethodId for the method to compare against.
4065 const DexFile::MethodId* const mid_;
4066 // Lazily computed name from the dex file's strings.
4067 const char* name_;
4068 // Lazily computed name length.
4069 uint32_t name_len_;
4070};
4071
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004072class LinkVirtualHashTable {
4073 public:
4074 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4075 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4076 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4077 }
4078 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4079 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4080 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004081 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004082 uint32_t index = hash % hash_size_;
4083 // Linear probe until we have an empty slot.
4084 while (hash_table_[index] != invalid_index_) {
4085 if (++index == hash_size_) {
4086 index = 0;
4087 }
4088 }
4089 hash_table_[index] = virtual_method_index;
4090 }
4091 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4092 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4093 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004094 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004095 size_t index = hash % hash_size_;
4096 while (true) {
4097 const uint32_t value = hash_table_[index];
4098 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4099 // the block and can safely assume not found.
4100 if (value == invalid_index_) {
4101 break;
4102 }
4103 if (value != removed_index_) { // This signifies not already overriden.
4104 mirror::ArtMethod* virtual_method =
4105 klass_->GetVirtualMethodDuringLinking(value);
4106 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4107 hash_table_[index] = removed_index_;
4108 return value;
4109 }
4110 }
4111 if (++index == hash_size_) {
4112 index = 0;
4113 }
4114 }
4115 return GetNotFoundIndex();
4116 }
4117 static uint32_t GetNotFoundIndex() {
4118 return invalid_index_;
4119 }
4120
4121 private:
4122 static const uint32_t invalid_index_;
4123 static const uint32_t removed_index_;
4124
4125 Handle<mirror::Class> klass_;
4126 const size_t hash_size_;
4127 uint32_t* const hash_table_;
4128};
4129
4130const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4131const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4132
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004133bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004134 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004135 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004136 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4137 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004138 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004139 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004140 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004141 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4142 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4143 if (UNLIKELY(vtable.Get() == nullptr)) {
4144 CHECK(self->IsExceptionPending()); // OOME.
4145 return false;
4146 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004147 for (size_t i = 0; i < super_vtable_length; i++) {
4148 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004149 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004150 if (num_virtual_methods == 0) {
4151 klass->SetVTable(vtable.Get());
4152 return true;
4153 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004154 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004155 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4156 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4157 if (num_virtual_methods == 0) {
4158 klass->SetVTable(super_vtable);
4159 return true;
4160 }
4161 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004162 if (UNLIKELY(vtable.Get() == nullptr)) {
4163 CHECK(self->IsExceptionPending()); // OOME.
4164 return false;
4165 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004166 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004167 // How the algorithm works:
4168 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4169 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4170 // method which has not been matched to a vtable method, and j if the virtual method at the
4171 // index overrode the super virtual method at index j.
4172 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4173 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4174 // the need for the initial vtable which we later shrink back down).
4175 // 3. Add non overridden methods to the end of the vtable.
4176 static constexpr size_t kMaxStackHash = 250;
4177 const size_t hash_table_size = num_virtual_methods * 3;
4178 uint32_t* hash_table_ptr;
4179 std::unique_ptr<uint32_t[]> hash_heap_storage;
4180 if (hash_table_size <= kMaxStackHash) {
4181 hash_table_ptr = reinterpret_cast<uint32_t*>(
4182 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4183 } else {
4184 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4185 hash_table_ptr = hash_heap_storage.get();
4186 }
4187 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4188 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004189 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004190 hash_table.Add(i);
4191 }
4192 // Loop through each super vtable method and see if they are overriden by a method we added to
4193 // the hash table.
4194 for (size_t j = 0; j < super_vtable_length; ++j) {
4195 // Search the hash table to see if we are overidden by any method.
4196 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4197 MethodNameAndSignatureComparator super_method_name_comparator(
4198 super_method->GetInterfaceMethodIfProxy());
4199 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4200 if (hash_index != hash_table.GetNotFoundIndex()) {
4201 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4202 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4203 super_method->GetAccessFlags())) {
4204 if (super_method->IsFinal()) {
4205 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4206 PrettyMethod(virtual_method).c_str(),
4207 super_method->GetDeclaringClassDescriptor());
4208 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004209 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004210 vtable->SetWithoutChecks<false>(j, virtual_method);
4211 virtual_method->SetMethodIndex(j);
4212 } else {
4213 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004214 << " would have incorrectly overridden the package-private method in "
4215 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004216 }
4217 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004218 }
4219 // Add the non overridden methods at the end.
4220 size_t actual_count = super_vtable_length;
4221 for (size_t i = 0; i < num_virtual_methods; ++i) {
4222 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4223 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4224 if (method_idx < super_vtable_length &&
4225 local_method == vtable->GetWithoutChecks(method_idx)) {
4226 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004227 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004228 vtable->SetWithoutChecks<false>(actual_count, local_method);
4229 local_method->SetMethodIndex(actual_count);
4230 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004231 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004232 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004233 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004234 return false;
4235 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004236 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004237 CHECK_LE(actual_count, max_count);
4238 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004239 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004240 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004241 CHECK(self->IsExceptionPending()); // OOME.
4242 return false;
4243 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004244 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004245 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004246 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004247 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004248 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004249 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4250 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004251 return false;
4252 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004253 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4254 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004255 CHECK(self->IsExceptionPending()); // OOME.
4256 return false;
4257 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004258 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004259 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004260 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004261 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004262 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004263 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004264 }
4265 return true;
4266}
4267
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004268bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4269 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4270 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004271 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004272 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004273 const bool has_superclass = klass->HasSuperClass();
4274 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4275 const bool have_interfaces = interfaces.Get() != nullptr;
4276 const size_t num_interfaces =
4277 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4278 if (num_interfaces == 0) {
4279 if (super_ifcount == 0) {
4280 // Class implements no interfaces.
4281 DCHECK_EQ(klass->GetIfTableCount(), 0);
4282 DCHECK(klass->GetIfTable() == nullptr);
4283 return true;
4284 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004285 // Class implements same interfaces as parent, are any of these not marker interfaces?
4286 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004287 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004288 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004289 if (super_iftable->GetMethodArrayCount(i) > 0) {
4290 has_non_marker_interface = true;
4291 break;
4292 }
4293 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004294 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004295 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004296 klass->SetIfTable(super_iftable);
4297 return true;
4298 }
4299 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004300 size_t ifcount = super_ifcount + num_interfaces;
4301 for (size_t i = 0; i < num_interfaces; i++) {
4302 mirror::Class* interface = have_interfaces ?
4303 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4304 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004305 if (UNLIKELY(!interface->IsInterface())) {
4306 std::string temp;
4307 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4308 PrettyDescriptor(klass.Get()).c_str(),
4309 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4310 return false;
4311 }
4312 ifcount += interface->GetIfTableCount();
4313 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004314 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004315 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004316 CHECK(self->IsExceptionPending()); // OOME.
4317 return false;
4318 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004319 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004320 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004321 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004322 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004323 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004324 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004325 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004326 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004327 // Flatten the interface inheritance hierarchy.
4328 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004329 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004330 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4331 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004332 // Check if interface is already in iftable
4333 bool duplicate = false;
4334 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004335 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004336 if (existing_interface == interface) {
4337 duplicate = true;
4338 break;
4339 }
4340 }
4341 if (!duplicate) {
4342 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004343 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004344 // Add this interface's non-duplicate super-interfaces.
4345 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004346 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004347 bool super_duplicate = false;
4348 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004349 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004350 if (existing_interface == super_interface) {
4351 super_duplicate = true;
4352 break;
4353 }
4354 }
4355 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004356 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004357 }
4358 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004359 }
4360 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004361 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004362 // Shrink iftable in case duplicates were found
4363 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004364 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004365 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004366 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004367 CHECK(self->IsExceptionPending()); // OOME.
4368 return false;
4369 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004370 ifcount = idx;
4371 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004372 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004373 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004374 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004375 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004376 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004377 return true;
4378 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004379 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004380 size_t max_miranda_methods = 0; // The max size of miranda_list.
4381 for (size_t i = 0; i < ifcount; ++i) {
4382 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4383 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004384 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004385 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004386 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4387 hs.NewHandle(klass->GetVTableDuringLinking()));
4388 // Copy the IMT from the super class if possible.
4389 bool extend_super_iftable = false;
4390 if (has_superclass) {
4391 mirror::Class* super_class = klass->GetSuperClass();
4392 extend_super_iftable = true;
4393 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4394 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4395 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
4396 }
4397 } else {
4398 // No imt in the super class, need to reconstruct from the iftable.
4399 mirror::IfTable* if_table = super_class->GetIfTable();
4400 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4401 const size_t length = super_class->GetIfTableCount();
4402 for (size_t i = 0; i < length; ++i) {
4403 mirror::Class* interface = iftable->GetInterface(i);
4404 const size_t num_virtuals = interface->NumVirtualMethods();
4405 const size_t method_array_count = if_table->GetMethodArrayCount(i);
4406 DCHECK_EQ(num_virtuals, method_array_count);
4407 if (method_array_count == 0) {
4408 continue;
4409 }
4410 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
4411 for (size_t j = 0; j < num_virtuals; ++j) {
4412 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
4413 if (method->IsMiranda()) {
4414 continue;
4415 }
4416 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
4417 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4418 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4419 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4420 out_imt->SetReference(imt_index, method);
4421 } else if (imt_ref != conflict_method) {
4422 out_imt->SetReference(imt_index, conflict_method);
4423 }
4424 }
4425 }
4426 }
4427 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004428 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004429 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004430 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004431 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004432 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004433 const bool is_super = i < super_ifcount;
4434 const bool super_interface = is_super && extend_super_iftable;
4435 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
4436 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
4437 if (super_interface) {
4438 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
4439 DCHECK(if_table != nullptr);
4440 DCHECK(if_table->GetMethodArray(i) != nullptr);
4441 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004442 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004443 AsObjectArray<mirror::ArtMethod>());
4444 // We are overwriting a super class interface, try to only virtual methods instead of the
4445 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004446 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004447 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004448 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004449 // A new interface, we need the whole vtable incase a new interface method is implemented
4450 // in the whole superclass.
4451 input_array = vtable;
4452 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004453 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004454 CHECK(self->IsExceptionPending()); // OOME.
4455 return false;
4456 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004457 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004458 if (input_array.Get() == nullptr) {
4459 // If the added virtual methods is empty, do nothing.
4460 DCHECK(super_interface);
4461 continue;
4462 }
Ian Rogers62d6c772013-02-27 08:32:07 -08004463 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004464 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004465 MethodNameAndSignatureComparator interface_name_comparator(
4466 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07004467 int32_t k;
4468 // For each method listed in the interface's method list, find the
4469 // matching method in our class's method list. We want to favor the
4470 // subclass over the superclass, which just requires walking
4471 // back from the end of the vtable. (This only matters if the
4472 // superclass defines a private method and this class redefines
4473 // it -- otherwise it would use the same vtable slot. In .dex files
4474 // those don't end up in the virtual method table, so it shouldn't
4475 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004476 for (k = input_array->GetLength() - 1; k >= 0; --k) {
4477 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004478 mirror::ArtMethod* vtable_method_for_name_comparison =
4479 vtable_method->GetInterfaceMethodIfProxy();
4480 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004481 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004482 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004483 ThrowIllegalAccessError(
4484 klass.Get(),
4485 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004486 PrettyMethod(vtable_method).c_str(),
4487 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004488 return false;
4489 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004490 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004491 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004492 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4493 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4494 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4495 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4496 out_imt->SetReference(imt_index, vtable_method);
4497 } else if (imt_ref != conflict_method) {
4498 // If we are not a conflict and we have the same signature and name as the imt entry,
4499 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004500 MethodNameAndSignatureComparator imt_ref_name_comparator(
4501 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004502 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004503 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004504 out_imt->SetReference(imt_index, vtable_method);
4505 } else {
4506 out_imt->SetReference(imt_index, conflict_method);
4507 }
Jeff Hao88474b42013-10-23 16:24:40 -07004508 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004509 break;
4510 }
4511 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004512 if (k < 0 && !super_interface) {
4513 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004514 for (size_t l = 0; l < miranda_list_size; ++l) {
4515 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004516 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004517 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07004518 break;
4519 }
4520 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004521 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004522 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004523 miranda_method = interface_method->Clone(self)->AsArtMethod();
4524 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004525 CHECK(self->IsExceptionPending()); // OOME.
4526 return false;
4527 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004528 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004529 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004530 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004531 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004532 }
4533 }
4534 }
4535 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004536 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004537 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004538 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004539 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4540 if (old_method_count == 0) {
4541 virtuals = AllocArtMethodArray(self, new_method_count);
4542 } else {
4543 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4544 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004545 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004546 CHECK(self->IsExceptionPending()); // OOME.
4547 return false;
4548 }
4549 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004550
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004551 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004552 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004553 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004554 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004555 CHECK(self->IsExceptionPending()); // OOME.
4556 return false;
4557 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004558 for (size_t i = 0; i < miranda_list_size; ++i) {
4559 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004560 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004561 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4562 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4563 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004564 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004565 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004566 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004567 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004568 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004569
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004570 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004571 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
4572 for (int i = 0; i < check_vtable->GetLength(); ++i) {
4573 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004574 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004575 }
4576
Ian Rogers7b078e82014-09-10 14:44:24 -07004577 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004578 return true;
4579}
4580
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004581bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004582 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004583 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004584}
4585
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004586bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004587 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004588 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004589}
4590
Brian Carlstromdbc05252011-09-09 01:59:59 -07004591struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004592 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4593 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004594 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004595 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004596 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07004597 // 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 -07004598 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4599 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004600 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00004601 if (type1 == Primitive::kPrimNot) {
4602 // Reference always goes first.
4603 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08004604 }
Vladimir Markod5777482014-11-12 17:02:02 +00004605 if (type2 == Primitive::kPrimNot) {
4606 // Reference always goes first.
4607 return false;
4608 }
4609 size_t size1 = Primitive::ComponentSize(type1);
4610 size_t size2 = Primitive::ComponentSize(type2);
4611 if (size1 != size2) {
4612 // Larger primitive types go first.
4613 return size1 > size2;
4614 }
4615 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
4616 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004617 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004618 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
4619 // by name and for equal names by type id index.
4620 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
4621 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07004622 }
4623};
4624
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004625bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07004626 size_t* class_size) {
4627 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004628 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004629 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004630
Brian Carlstromea46f952013-07-30 01:26:50 -07004631 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004632 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004633
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004634 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07004635 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004636 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00004637 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004638 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004639 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004640 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004641 CHECK(super_class->IsResolved())
4642 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004643 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004644 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004645 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004646
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004647 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004648
Brian Carlstromdbc05252011-09-09 01:59:59 -07004649 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07004650 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07004651 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07004652 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07004653 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07004654 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004655 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004656 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004657 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004658 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004659 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4660 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004661
Fred Shih381e4ca2014-08-25 17:24:27 -07004662 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07004663 size_t current_field = 0;
4664 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07004665 FieldGaps gaps;
4666
Brian Carlstromdbc05252011-09-09 01:59:59 -07004667 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004668 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004669 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004670 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004671 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004672 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004673 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004674 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
4675 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07004676 MemberOffset old_offset = field_offset;
4677 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
4678 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
4679 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004680 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07004681 grouped_and_sorted_fields.pop_front();
4682 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004683 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00004684 field_offset = MemberOffset(field_offset.Uint32Value() +
4685 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004686 }
Fred Shih381e4ca2014-08-25 17:24:27 -07004687 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
4688 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00004689 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4690 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4691 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4692 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07004693 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
4694 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07004695 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004696
Elliott Hughesadb460d2011-10-05 17:02:34 -07004697 // 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 -07004698 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07004699 // We know there are no non-reference fields in the Reference classes, and we know
4700 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07004701 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004702 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07004703 --num_reference_fields;
4704 }
4705
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004706 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004707 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004708 if (is_static) {
4709 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004710 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004711 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004712 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004713 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08004714 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
Jeff Haoc7d11882015-02-03 15:08:39 -08004715 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
4716 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartier2d721012014-11-10 11:08:06 -08004717 } else {
4718 std::string temp;
4719 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
4720 size_t previous_size = klass->GetObjectSize();
4721 if (previous_size != 0) {
4722 // Make sure that we didn't originally have an incorrect size.
4723 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
4724 }
4725 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004726 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004727 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004728 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004729
4730 if (kIsDebugBuild) {
4731 // Make sure that the fields array is ordered by name but all reference
4732 // offsets are at the beginning as far as alignment allows.
4733 MemberOffset start_ref_offset = is_static
4734 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
4735 : klass->GetFirstReferenceInstanceFieldOffset();
4736 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
4737 num_reference_fields *
4738 sizeof(mirror::HeapReference<mirror::Object>));
4739 MemberOffset current_ref_offset = start_ref_offset;
4740 for (size_t i = 0; i < num_fields; i++) {
4741 mirror::ArtField* field = fields->Get(i);
4742 if ((false)) { // enable to debug field layout
4743 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
4744 << " class=" << PrettyClass(klass.Get())
4745 << " field=" << PrettyField(field)
4746 << " offset="
4747 << field->GetField32(mirror::ArtField::OffsetOffset());
4748 }
4749 if (i != 0) {
4750 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004751 // NOTE: The field names can be the same. This is not possible in the Java language
4752 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
4753 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00004754 }
4755 Primitive::Type type = field->GetTypeAsPrimitiveType();
4756 bool is_primitive = type != Primitive::kPrimNot;
4757 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
4758 strcmp("referent", field->GetName()) == 0) {
4759 is_primitive = true; // We lied above, so we have to expect a lie here.
4760 }
4761 MemberOffset offset = field->GetOffsetDuringLinking();
4762 if (is_primitive) {
4763 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
4764 // Shuffled before references.
4765 size_t type_size = Primitive::ComponentSize(type);
4766 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
4767 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
4768 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
4769 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
4770 }
4771 } else {
4772 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
4773 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
4774 sizeof(mirror::HeapReference<mirror::Object>));
4775 }
4776 }
4777 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
4778 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004779 return true;
4780}
4781
Vladimir Marko76649e82014-11-10 18:32:59 +00004782// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004783void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004784 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004785 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004786 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004787 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004788 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004789 // Compute reference offsets unless our superclass overflowed.
4790 if (reference_offsets != mirror::Class::kClassWalkSuper) {
4791 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00004792 if (num_reference_fields != 0u) {
4793 // All of the fields that contain object references are guaranteed be grouped in memory
4794 // starting at an appropriately aligned address after super class object data.
4795 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
4796 sizeof(mirror::HeapReference<mirror::Object>));
4797 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004798 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00004799 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004800 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004801 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00004802 reference_offsets |= (0xffffffffu << start_bit) &
4803 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004804 }
4805 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07004806 }
4807 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07004808 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004809}
4810
Mathieu Chartier590fee92013-09-13 13:46:47 -07004811mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004812 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004813 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004814 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004815 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004816 return resolved;
4817 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07004818 uint32_t utf16_length;
4819 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004820 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004821 dex_cache->SetResolvedString(string_idx, string);
4822 return string;
4823}
4824
Mathieu Chartier590fee92013-09-13 13:46:47 -07004825mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08004826 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004827 StackHandleScope<2> hs(Thread::Current());
4828 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
4829 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07004830 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
4831}
4832
4833mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004834 Handle<mirror::DexCache> dex_cache,
4835 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004836 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004837 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004838 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08004839 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07004840 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08004841 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004842 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05004843 // TODO: we used to throw here if resolved's class loader was not the
4844 // boot class loader. This was to permit different classes with the
4845 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004846 dex_cache->SetResolvedType(type_idx, resolved);
4847 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004848 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08004849 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08004850 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004851 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004852 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004853 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004854 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08004855 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08004856 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004857 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08004858 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004859 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004860 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004861 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07004862 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004863 return resolved;
4864}
4865
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004866mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004867 Handle<mirror::DexCache> dex_cache,
4868 Handle<mirror::ClassLoader> class_loader,
4869 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07004870 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004871 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07004872 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07004873 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004874 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004875 return resolved;
4876 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004877 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004878 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004879 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004880 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07004881 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004882 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004883 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004884 // Scan using method_idx, this saves string compares but will only hit for matching dex
4885 // caches/files.
4886 switch (type) {
4887 case kDirect: // Fall-through.
4888 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004889 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004890 break;
4891 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004892 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004893 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004894 break;
4895 case kSuper: // Fall-through.
4896 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004897 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004898 break;
4899 default:
4900 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07004901 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004902 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004903 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004904 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004905 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07004906 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07004907 switch (type) {
4908 case kDirect: // Fall-through.
4909 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08004910 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004911 break;
4912 case kInterface:
4913 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004914 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004915 break;
4916 case kSuper: // Fall-through.
4917 case kVirtual:
4918 resolved = klass->FindVirtualMethod(name, signature);
4919 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004920 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004921 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004922 // If we found a method, check for incompatible class changes.
4923 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004924 // Be a good citizen and update the dex cache to speed subsequent calls.
4925 dex_cache->SetResolvedMethod(method_idx, resolved);
4926 return resolved;
4927 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004928 // If we had a method, it's an incompatible-class-change error.
4929 if (resolved != nullptr) {
4930 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
4931 } else {
4932 // We failed to find the method which means either an access error, an incompatible class
4933 // change, or no such method. First try to find the method among direct and virtual methods.
4934 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
4935 const Signature signature = dex_file.GetMethodSignature(method_id);
4936 switch (type) {
4937 case kDirect:
4938 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07004939 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004940 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
4941 // have had a resolved method before, which triggers the "true" branch above.
4942 break;
4943 case kInterface:
4944 case kVirtual:
4945 case kSuper:
4946 resolved = klass->FindDirectMethod(name, signature);
4947 break;
4948 }
4949
4950 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08004951 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004952 if (resolved != nullptr && referrer.Get() != nullptr) {
4953 mirror::Class* methods_class = resolved->GetDeclaringClass();
4954 mirror::Class* referring_class = referrer->GetDeclaringClass();
4955 if (!referring_class->CanAccess(methods_class)) {
4956 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
4957 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004958 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004959 } else if (!referring_class->CanAccessMember(methods_class,
4960 resolved->GetAccessFlags())) {
4961 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004962 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004963 }
4964 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004965 if (!exception_generated) {
4966 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
4967 // interface methods and throw if we find the method there. If we find nothing, throw a
4968 // NoSuchMethodError.
4969 switch (type) {
4970 case kDirect:
4971 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004972 if (resolved != nullptr) {
4973 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4974 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004975 resolved = klass->FindInterfaceMethod(name, signature);
4976 if (resolved != nullptr) {
4977 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4978 } else {
4979 ThrowNoSuchMethodError(type, klass, name, signature);
4980 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004981 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004982 break;
4983 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004984 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004985 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
4986 } else {
4987 resolved = klass->FindVirtualMethod(name, signature);
4988 if (resolved != nullptr) {
4989 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4990 } else {
4991 ThrowNoSuchMethodError(type, klass, name, signature);
4992 }
4993 }
4994 break;
4995 case kSuper:
4996 if (resolved != nullptr) {
4997 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004998 } else {
4999 ThrowNoSuchMethodError(type, klass, name, signature);
5000 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005001 break;
5002 case kVirtual:
5003 if (resolved != nullptr) {
5004 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5005 } else {
5006 resolved = klass->FindInterfaceMethod(name, signature);
5007 if (resolved != nullptr) {
5008 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5009 } else {
5010 ThrowNoSuchMethodError(type, klass, name, signature);
5011 }
5012 }
5013 break;
5014 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005015 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005016 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005017 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005018 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005019 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005020}
5021
Mathieu Chartier590fee92013-09-13 13:46:47 -07005022mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005023 Handle<mirror::DexCache> dex_cache,
5024 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005025 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005026 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005027 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005028 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005029 return resolved;
5030 }
5031 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005032 Thread* const self = Thread::Current();
5033 StackHandleScope<1> hs(self);
5034 Handle<mirror::Class> klass(
5035 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005036 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005037 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005038 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005039 }
5040
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005041 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005042 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005043 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005044 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005045 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005046
Andreas Gampe58a5af82014-07-31 16:23:49 -07005047 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005048 const char* name = dex_file.GetFieldName(field_id);
5049 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5050 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005051 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005052 } else {
5053 resolved = klass->FindInstanceField(name, type);
5054 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005055 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005056 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005057 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005058 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005059 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005060 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005061 return resolved;
5062}
5063
Brian Carlstromea46f952013-07-30 01:26:50 -07005064mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005065 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005066 Handle<mirror::DexCache> dex_cache,
5067 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005068 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005069 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005070 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005071 return resolved;
5072 }
5073 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005074 Thread* self = Thread::Current();
5075 StackHandleScope<1> hs(self);
5076 Handle<mirror::Class> klass(
5077 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005078 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005079 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005080 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005081 }
5082
Ian Rogersdfb325e2013-10-30 01:00:44 -07005083 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5084 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005085 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005086 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005087 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005088 dex_cache->SetResolvedField(field_idx, resolved);
5089 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005090 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005091 }
5092 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005093}
5094
Brian Carlstromea46f952013-07-30 01:26:50 -07005095const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005096 uint32_t* length) {
5097 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5098 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005099 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005100 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005101 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005102}
5103
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005104void ClassLinker::DumpAllClasses(int flags) {
5105 if (dex_cache_image_class_lookup_required_) {
5106 MoveImageClassesToClassTable();
5107 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005108 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5109 // lock held, because it might need to resolve a field's type, which would try to take the lock.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005110 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005111 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005112 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005113 for (GcRoot<mirror::Class>& it : class_table_) {
5114 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005115 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005116 }
5117
5118 for (size_t i = 0; i < all_classes.size(); ++i) {
5119 all_classes[i]->DumpClass(std::cerr, flags);
5120 }
5121}
5122
Elliott Hughes956af0f2014-12-11 14:34:28 -08005123static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005124 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005125 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5126 base -= sizeof(void*); // Move backward so that code_offset != 0.
5127 const uint32_t code_offset = sizeof(void*);
5128 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005129}
5130
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005131bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5132 return (entry_point == GetQuickResolutionStub()) ||
5133 (quick_resolution_trampoline_ == entry_point);
5134}
5135
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005136bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5137 return (entry_point == GetQuickToInterpreterBridge()) ||
5138 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5139}
5140
5141bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5142 return (entry_point == GetQuickGenericJniStub()) ||
5143 (quick_generic_jni_trampoline_ == entry_point);
5144}
5145
5146const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5147 return GetQuickGenericJniStub();
5148}
5149
Elliott Hughes956af0f2014-12-11 14:34:28 -08005150void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5151 const void* method_code) const {
5152 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005153 oat_method.LinkMethod(method);
5154 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005155}
5156
5157void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5158 if (!method->IsNative()) {
5159 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005160 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5161 } else {
5162 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005163 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005164 oat_method.LinkMethod(method);
5165 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005166 }
5167}
5168
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005169void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005170 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005171 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005172 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005173 MoveImageClassesToClassTable();
5174 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005175 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005176 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5177 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005178}
5179
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005180size_t ClassLinker::NumLoadedClasses() {
5181 if (dex_cache_image_class_lookup_required_) {
5182 MoveImageClassesToClassTable();
5183 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005184 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005185 // Only return non zygote classes since these are the ones which apps which care about.
5186 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005187}
5188
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005189pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005190 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005191}
5192
5193pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005194 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005195}
5196
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005197void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005198 DCHECK(!init_done_);
5199
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005200 DCHECK(klass != nullptr);
5201 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005202
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005203 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005204 DCHECK(class_roots != nullptr);
5205 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005206 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005207}
5208
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005209const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5210 static const char* class_roots_descriptors[] = {
5211 "Ljava/lang/Class;",
5212 "Ljava/lang/Object;",
5213 "[Ljava/lang/Class;",
5214 "[Ljava/lang/Object;",
5215 "Ljava/lang/String;",
5216 "Ljava/lang/DexCache;",
5217 "Ljava/lang/ref/Reference;",
5218 "Ljava/lang/reflect/ArtField;",
5219 "Ljava/lang/reflect/ArtMethod;",
5220 "Ljava/lang/reflect/Proxy;",
5221 "[Ljava/lang/String;",
5222 "[Ljava/lang/reflect/ArtField;",
5223 "[Ljava/lang/reflect/ArtMethod;",
5224 "Ljava/lang/ClassLoader;",
5225 "Ljava/lang/Throwable;",
5226 "Ljava/lang/ClassNotFoundException;",
5227 "Ljava/lang/StackTraceElement;",
5228 "Z",
5229 "B",
5230 "C",
5231 "D",
5232 "F",
5233 "I",
5234 "J",
5235 "S",
5236 "V",
5237 "[Z",
5238 "[B",
5239 "[C",
5240 "[D",
5241 "[F",
5242 "[I",
5243 "[J",
5244 "[S",
5245 "[Ljava/lang/StackTraceElement;",
5246 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005247 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5248 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005249
5250 const char* descriptor = class_roots_descriptors[class_root];
5251 CHECK(descriptor != nullptr);
5252 return descriptor;
5253}
5254
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005255std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5256 const {
5257 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005258 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005259}
5260
5261bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5262 const GcRoot<mirror::Class>& b) {
5263 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5264 return false;
5265 }
5266 std::string temp;
5267 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5268}
5269
5270std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5271 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005272 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005273}
5274
5275bool ClassLinker::ClassDescriptorHashEquals::operator()(
5276 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
5277 if (a.Read()->GetClassLoader() != b.second) {
5278 return false;
5279 }
5280 return a.Read()->DescriptorEquals(b.first);
5281}
5282
5283bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5284 const char* descriptor) {
5285 return a.Read()->DescriptorEquals(descriptor);
5286}
5287
5288std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005289 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005290}
5291
Sebastien Hertz6963e442014-11-26 22:11:27 +01005292bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
5293 // Non-image methods don't use direct code pointer.
5294 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
5295 return false;
5296 }
5297 if (m->IsPrivate()) {
5298 // The method can only be called inside its own oat file. Therefore it won't be called using
5299 // its direct code if the oat file has been compiled in PIC mode.
5300 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
5301 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
5302 const OatFile::OatDexFile* oat_dex_file = class_linker->FindOpenedOatDexFileForDexFile(dex_file);
5303 if (oat_dex_file == nullptr) {
5304 // No oat file: the method has not been compiled.
5305 return false;
5306 }
5307 const OatFile* oat_file = oat_dex_file->GetOatFile();
5308 return oat_file != nullptr && !oat_file->IsPic();
5309 } else {
5310 // The method can be called outside its own oat file. Therefore it won't be called using its
5311 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
5312 ReaderMutexLock mu(Thread::Current(), dex_lock_);
5313 for (const OatFile* oat_file : oat_files_) {
5314 if (!oat_file->IsPic()) {
5315 return true;
5316 }
5317 }
5318 return false;
5319 }
5320}
5321
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005322} // namespace art