blob: c344eb4b4118678f29995698c66f64ec94815c37 [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
Mathieu Chartierc7853442015-03-27 14:35:38 -070028#include "art_field-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080030#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010031#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080032#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080033#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080034#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000035#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080036#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070037#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070038#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070039#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070040#include "gc/accounting/card_table-inl.h"
41#include "gc/accounting/heap_bitmap.h"
42#include "gc/heap.h"
43#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070044#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070045#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070046#include "interpreter/interpreter.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080047#include "jit/jit.h"
48#include "jit/jit_code_cache.h"
Ian Rogers0571d352011-11-03 19:51:38 -070049#include "leb128.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070050#include "linear_alloc.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080051#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070052#include "oat_file.h"
Richard Uhler66d874d2015-01-15 09:37:19 -080053#include "oat_file_assistant.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070054#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070055#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/class.h"
57#include "mirror/class-inl.h"
58#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070059#include "mirror/dex_cache-inl.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070060#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070062#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080063#include "mirror/object-inl.h"
64#include "mirror/object_array-inl.h"
65#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070066#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080067#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070068#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080069#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070070#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070071#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070072#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070073#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070074#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070075#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070076#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080077#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070078#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070079
80namespace art {
81
Mathieu Chartierc7853442015-03-27 14:35:38 -070082static constexpr bool kSanityCheckObjects = kIsDebugBuild;
83
Ian Rogers00f7d0e2012-07-19 15:28:27 -070084static void ThrowNoClassDefFoundError(const char* fmt, ...)
85 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070086 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070087static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070088 va_list args;
89 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080090 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +000091 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080092 va_end(args);
93}
94
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080095static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070096 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070097 // The class failed to initialize on a previous attempt, so we want to throw
98 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
99 // failed in verification, in which case v2 5.4.1 says we need to re-throw
100 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800101 Runtime* const runtime = Runtime::Current();
102 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -0700103 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
104 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700105
Elliott Hughes5c599942012-06-13 16:45:05 -0700106 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800107 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800108 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700109 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
110 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000111 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700112 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700113 if (c->GetVerifyErrorClass() != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700114 // TODO: change the verifier to store an _instance_, with a useful detail message?
115 std::string temp;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000116 self->ThrowNewException(c->GetVerifyErrorClass()->GetDescriptor(&temp),
Ian Rogers7b078e82014-09-10 14:44:24 -0700117 PrettyDescriptor(c).c_str());
118 } else {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000119 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
Ian Rogers7b078e82014-09-10 14:44:24 -0700120 PrettyDescriptor(c).c_str());
121 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700122 }
123}
124
Brian Carlstromb23eab12014-10-08 17:55:21 -0700125static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
126 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
127 if (VLOG_IS_ON(class_linker)) {
128 std::string temp;
129 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000130 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700131 }
132}
133
134static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
135 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700136 Thread* self = Thread::Current();
137 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700138
139 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700140 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700141
142 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700143 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
144 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700145
Elliott Hughesa4f94742012-05-29 16:28:38 -0700146 // We only wrap non-Error exceptions; an Error can just be used as-is.
147 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000148 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700149 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700150 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700151}
152
Fred Shih381e4ca2014-08-25 17:24:27 -0700153// Gap between two fields in object layout.
154struct FieldGap {
155 uint32_t start_offset; // The offset from the start of the object.
156 uint32_t size; // The gap size of 1, 2, or 4 bytes.
157};
158struct FieldGapsComparator {
159 explicit FieldGapsComparator() {
160 }
161 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
162 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800163 // Sort by gap size, largest first. Secondary sort by starting offset.
164 return lhs.size > rhs.size || (lhs.size == rhs.size && lhs.start_offset < rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700165 }
166};
167typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
168
169// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800170static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700171 DCHECK(gaps != nullptr);
172
173 uint32_t current_offset = gap_start;
174 while (current_offset != gap_end) {
175 size_t remaining = gap_end - current_offset;
176 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
177 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
178 current_offset += sizeof(uint32_t);
179 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
180 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
181 current_offset += sizeof(uint16_t);
182 } else {
183 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
184 current_offset += sizeof(uint8_t);
185 }
186 DCHECK_LE(current_offset, gap_end) << "Overran gap";
187 }
188}
189// Shuffle fields forward, making use of gaps whenever possible.
190template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000191static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700192 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700193 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700194 FieldGaps* gaps)
195 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
196 DCHECK(current_field_idx != nullptr);
197 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700198 DCHECK(gaps != nullptr);
199 DCHECK(field_offset != nullptr);
200
201 DCHECK(IsPowerOfTwo(n));
202 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700203 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700204 Primitive::Type type = field->GetTypeAsPrimitiveType();
205 if (Primitive::ComponentSize(type) < n) {
206 break;
207 }
208 if (!IsAligned<n>(field_offset->Uint32Value())) {
209 MemberOffset old_offset = *field_offset;
210 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
211 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
212 }
213 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
214 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700215 if (!gaps->empty() && gaps->top().size >= n) {
216 FieldGap gap = gaps->top();
217 gaps->pop();
218 DCHECK(IsAligned<n>(gap.start_offset));
219 field->SetOffset(MemberOffset(gap.start_offset));
220 if (gap.size > n) {
221 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
222 }
223 } else {
224 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
225 field->SetOffset(*field_offset);
226 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
227 }
228 ++(*current_field_idx);
229 }
230}
231
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800232ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700233 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700234 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700235 dex_cache_image_class_lookup_required_(false),
236 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800237 class_roots_(nullptr),
238 array_iftable_(nullptr),
239 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700240 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800241 log_new_dex_caches_roots_(false),
242 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700243 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800244 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800245 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100246 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800247 quick_to_interpreter_bridge_trampoline_(nullptr),
248 image_pointer_size_(sizeof(void*)) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700249 CHECK(intern_table_ != nullptr);
250 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
251 find_array_class_cache_[i] = GcRoot<mirror::Class>(nullptr);
252 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700253}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700254
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800255void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800256 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700257 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700258
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700259 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700260
Elliott Hughes30646832011-10-13 16:59:46 -0700261 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700262 Thread* const self = Thread::Current();
263 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700264 // 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 -0800265 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700266 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
267 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700268 heap->AllocNonMovableObject<true>(self, nullptr,
269 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700270 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700271 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700272 mirror::Class::SetClassClass(java_lang_Class.Get());
273 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700274 if (kUseBakerOrBrooksReadBarrier) {
275 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800276 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700277 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700278 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800279 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800280 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700281
Elliott Hughes418d20f2011-09-22 14:00:39 -0700282 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700283 Handle<mirror::Class> class_array_class(hs.NewHandle(
284 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700285 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700286
Ian Rogers23435d02012-09-24 11:23:12 -0700287 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700288 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
289 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700290 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700291 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700292 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700293 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700294
Ian Rogers23435d02012-09-24 11:23:12 -0700295 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700296 Handle<mirror::Class> object_array_class(hs.NewHandle(
297 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700298 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700299
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700300 // Setup the char (primitive) class to be used for char[].
301 Handle<mirror::Class> char_class(hs.NewHandle(
302 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700303 // The primitive char class won't be initialized by
304 // InitializePrimitiveClass until line 459, but strings (and
305 // internal char arrays) will be allocated before that and the
306 // component size, which is computed from the primitive type, needs
307 // to be set here.
308 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700309
Ian Rogers23435d02012-09-24 11:23:12 -0700310 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700311 Handle<mirror::Class> char_array_class(hs.NewHandle(
312 AllocClass(self, java_lang_Class.Get(),
313 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700314 char_array_class->SetComponentType(char_class.Get());
315 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700316
Ian Rogers23435d02012-09-24 11:23:12 -0700317 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700318 Handle<mirror::Class> java_lang_String(hs.NewHandle(
319 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700320 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700321 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700322 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400323
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700324 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700325 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
326 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
327 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
328 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700329 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700330
Ian Rogers23435d02012-09-24 11:23:12 -0700331 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700332 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700333 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
334 kClassRootsMax));
335 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700336 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
337 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
338 SetClassRoot(kClassArrayClass, class_array_class.Get());
339 SetClassRoot(kObjectArrayClass, object_array_class.Get());
340 SetClassRoot(kCharArrayClass, char_array_class.Get());
341 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700342 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700343
344 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700345 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
346 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
347 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
348 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
349 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
350 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
351 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
352 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700353
Ian Rogers23435d02012-09-24 11:23:12 -0700354 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700355 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700356
Ian Rogers23435d02012-09-24 11:23:12 -0700357 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700358 Handle<mirror::Class> int_array_class(hs.NewHandle(
359 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700360 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700361 mirror::IntArray::SetArrayClass(int_array_class.Get());
362 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700363
Mathieu Chartierc7853442015-03-27 14:35:38 -0700364 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
365 Handle<mirror::Class> long_array_class(hs.NewHandle(
366 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
367 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
368 mirror::LongArray::SetArrayClass(long_array_class.Get());
369 SetClassRoot(kLongArrayClass, long_array_class.Get());
370
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700371 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700372
Ian Rogers52813c92012-10-11 11:50:38 -0700373 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700374 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
375 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700376 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700377 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700378 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700379
Mathieu Chartierc7853442015-03-27 14:35:38 -0700380 // Constructor, Method, and AbstractMethod are necessary so
Brian Carlstromf3632832014-05-20 15:36:53 -0700381 // that FindClass can link members.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700382
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700383 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
384 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700385 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800386 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
387 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700388 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700389 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700390 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700391
392 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700393 Handle<mirror::Class> object_array_string(hs.NewHandle(
394 AllocClass(self, java_lang_Class.Get(),
395 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700396 object_array_string->SetComponentType(java_lang_String.Get());
397 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700398
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700399 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
400 AllocClass(self, java_lang_Class.Get(),
401 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700402 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
403 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700404
Ian Rogers23435d02012-09-24 11:23:12 -0700405 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
406 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
407 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700408 CHECK_NE(0U, boot_class_path.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800409 for (auto& dex_file : boot_class_path) {
410 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700411 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800412 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700413 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700414
415 // now we can use FindSystemClass
416
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700417 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700418 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
419 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700420
Jeff Hao88474b42013-10-23 16:24:40 -0700421 // Create runtime resolution and imt conflict methods. Also setup the default imt.
422 Runtime* runtime = Runtime::Current();
423 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
424 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700425 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700426 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
427
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700428 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
429 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700430 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800431 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700432 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700433 quick_resolution_trampoline_ = GetQuickResolutionStub();
434 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
435 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700436 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700437
Mathieu Chartier66f19252012-09-18 08:57:04 -0700438 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700439 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700440 CHECK_EQ(java_lang_Object.Get(), FindSystemClass(self, "Ljava/lang/Object;"));
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700441 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700442 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800443 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700444 if (java_lang_String.Get() != String_class) {
445 std::ostringstream os1, os2;
446 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
447 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
448 LOG(FATAL) << os1.str() << "\n\n" << os2.str();
449 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700450 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700451 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700452 CHECK_EQ(java_lang_DexCache.Get(), FindSystemClass(self, "Ljava/lang/DexCache;"));
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700453 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454
Ian Rogers23435d02012-09-24 11:23:12 -0700455 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800456 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800457 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700458
Ian Rogers98379392014-02-24 16:53:16 -0800459 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800460 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700461
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700462 CHECK_EQ(char_array_class.Get(), FindSystemClass(self, "[C"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700463
Ian Rogers98379392014-02-24 16:53:16 -0800464 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800465 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700466
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700467 CHECK_EQ(int_array_class.Get(), FindSystemClass(self, "[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700468
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700469 CHECK_EQ(long_array_class.Get(), FindSystemClass(self, "[J"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470
Ian Rogers98379392014-02-24 16:53:16 -0800471 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800472 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700473
Ian Rogers98379392014-02-24 16:53:16 -0800474 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800475 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700476
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700477 CHECK_EQ(class_array_class.Get(), FindSystemClass(self, "[Ljava/lang/Class;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700478
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700479 CHECK_EQ(object_array_class.Get(), FindSystemClass(self, "[Ljava/lang/Object;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700480
Ian Rogers23435d02012-09-24 11:23:12 -0700481 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700482 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
483 CHECK(java_lang_Cloneable.Get() != nullptr);
484 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
485 CHECK(java_io_Serializable.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700486 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
487 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700488 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
489 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700490
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700491 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
492 // suspension.
493 CHECK_EQ(java_lang_Cloneable.Get(),
494 mirror::Class::GetDirectInterface(self, class_array_class, 0));
495 CHECK_EQ(java_io_Serializable.Get(),
496 mirror::Class::GetDirectInterface(self, class_array_class, 1));
497 CHECK_EQ(java_lang_Cloneable.Get(),
498 mirror::Class::GetDirectInterface(self, object_array_class, 0));
499 CHECK_EQ(java_io_Serializable.Get(),
500 mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700501 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700502 // dex_cache_ fields and register them in class_table_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700503 CHECK_EQ(java_lang_Class.Get(), FindSystemClass(self, "Ljava/lang/Class;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700504
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700505 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700506 CHECK_EQ(java_lang_reflect_ArtMethod.Get(),
507 FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;"));
508 CHECK_EQ(object_array_string.Get(),
509 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
510 CHECK_EQ(object_array_art_method.Get(),
511 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700512
Ian Rogers23435d02012-09-24 11:23:12 -0700513 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700514
Ian Rogers23435d02012-09-24 11:23:12 -0700515 // Create java.lang.reflect.Proxy root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700516 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700517
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700518 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700519 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
520 CHECK(class_root != nullptr);
521 SetClassRoot(kJavaLangReflectField, class_root);
522 mirror::Field::SetClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700523
524 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700525 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
526 CHECK(class_root != nullptr);
527 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
528 mirror::Field::SetArrayClass(class_root);
529
530 // Create java.lang.reflect.Constructor.class root and array root.
531 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
532 CHECK(class_root != nullptr);
533 SetClassRoot(kJavaLangReflectConstructor, class_root);
534 mirror::Constructor::SetClass(class_root);
535 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
536 CHECK(class_root != nullptr);
537 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
538 mirror::Constructor::SetArrayClass(class_root);
539
540 // Create java.lang.reflect.Method.class root and array root.
541 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
542 CHECK(class_root != nullptr);
543 SetClassRoot(kJavaLangReflectMethod, class_root);
544 mirror::Method::SetClass(class_root);
545 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
546 CHECK(class_root != nullptr);
547 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
548 mirror::Method::SetArrayClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700549
Brian Carlstrom1f870082011-08-23 16:02:11 -0700550 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700551 // finish initializing Reference class
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700552 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700553 CHECK_EQ(java_lang_ref_Reference.Get(), FindSystemClass(self, "Ljava/lang/ref/Reference;"));
Fred Shih4ee7a662014-07-11 09:59:27 -0700554 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
555 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700556 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
557 class_root->SetAccessFlags(class_root->GetAccessFlags() |
558 kAccClassIsReference | kAccClassIsFinalizerReference);
559 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
560 class_root->SetAccessFlags(class_root->GetAccessFlags() | kAccClassIsReference |
561 kAccClassIsPhantomReference);
562 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
563 class_root->SetAccessFlags(class_root->GetAccessFlags() | kAccClassIsReference);
564 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
565 class_root->SetAccessFlags(class_root->GetAccessFlags() | kAccClassIsReference |
566 kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700567
Ian Rogers23435d02012-09-24 11:23:12 -0700568 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700569 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
570 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
571 SetClassRoot(kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700572
jeffhao8cd6dda2012-02-22 10:15:34 -0800573 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700574 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800575 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800576 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700577 SetClassRoot(kJavaLangClassNotFoundException,
578 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800579 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700580 SetClassRoot(kJavaLangStackTraceElementArrayClass,
581 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800582 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700583
Andreas Gampe76bd8802014-12-10 16:43:58 -0800584 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
585 // initialized.
586 {
587 const DexFile& dex_file = java_lang_Object->GetDexFile();
588 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
589 CHECK(void_string_id != nullptr);
590 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
591 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
592 CHECK(void_type_id != nullptr);
593 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
594 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
595 // as referrer so the used dex cache is core's one.
596 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
597 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
598 self->AssertNoPendingException();
599 }
600
Ian Rogers98379392014-02-24 16:53:16 -0800601 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700602
Brian Carlstroma004aa92012-02-08 18:05:09 -0800603 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700604}
605
Ian Rogers98379392014-02-24 16:53:16 -0800606void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800607 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700608
609 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700610 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700611 // as the types of the field can't be resolved prior to the runtime being
612 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800613 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700614 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800615 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800616
Mathieu Chartierc7853442015-03-27 14:35:38 -0700617 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700618 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
619 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700620
Mathieu Chartierc7853442015-03-27 14:35:38 -0700621 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700622 CHECK_STREQ(queue->GetName(), "queue");
623 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700624
Mathieu Chartierc7853442015-03-27 14:35:38 -0700625 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700626 CHECK_STREQ(queueNext->GetName(), "queueNext");
627 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700628
Mathieu Chartierc7853442015-03-27 14:35:38 -0700629 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700630 CHECK_STREQ(referent->GetName(), "referent");
631 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700632
Mathieu Chartierc7853442015-03-27 14:35:38 -0700633 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700634 CHECK_STREQ(zombie->GetName(), "zombie");
635 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700636
Brian Carlstroma663ea52011-08-19 23:33:41 -0700637 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700638 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700639 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800640 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700641 CHECK(klass != nullptr);
642 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700643 // note SetClassRoot does additional validation.
644 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700645 }
646
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700647 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700648
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700649 // disable the slow paths in FindClass and CreatePrimitiveClass now
650 // that Object, Class, and Object[] are setup
651 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700652
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800653 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700654}
655
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700656void ClassLinker::RunRootClinits() {
657 Thread* self = Thread::Current();
658 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800659 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700660 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700661 StackHandleScope<1> hs(self);
662 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700663 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700665 }
666 }
667}
668
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700669const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700670 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800671 if (kIsDebugBuild) {
672 for (size_t i = 0; i < oat_files_.size(); ++i) {
673 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700674 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800675 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700676 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
677 oat_files_.push_back(oat_file);
678 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800679}
680
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700681OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
682 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700683 OatFile* oat_file = space->ReleaseOatFile();
684 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700685 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700686 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700687}
688
Richard Uhler66d874d2015-01-15 09:37:19 -0800689std::vector<std::unique_ptr<const DexFile>> ClassLinker::OpenDexFilesFromOat(
690 const char* dex_location, const char* oat_location,
691 std::vector<std::string>* error_msgs) {
692 CHECK(error_msgs != nullptr);
Calin Juravle621962a2014-09-02 15:53:55 +0100693
Richard Uhler66d874d2015-01-15 09:37:19 -0800694 // Verify we aren't holding the mutator lock, which could starve GC if we
695 // have to generate or relocate an oat file.
696 Locks::mutator_lock_->AssertNotHeld(Thread::Current());
697
698 OatFileAssistant oat_file_assistant(dex_location, oat_location, kRuntimeISA,
699 !Runtime::Current()->IsAotCompiler());
700
701 // Lock the target oat location to avoid races generating and loading the
702 // oat file.
703 std::string error_msg;
704 if (!oat_file_assistant.Lock(&error_msg)) {
705 // Don't worry too much if this fails. If it does fail, it's unlikely we
706 // can generate an oat file anyway.
707 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700708 }
709
Richard Uhler66d874d2015-01-15 09:37:19 -0800710 // Check if we already have an up-to-date oat file open.
711 const OatFile* source_oat_file = nullptr;
712 {
713 ReaderMutexLock mu(Thread::Current(), dex_lock_);
714 for (const OatFile* oat_file : oat_files_) {
715 CHECK(oat_file != nullptr);
716 if (oat_file_assistant.GivenOatFileIsUpToDate(*oat_file)) {
717 source_oat_file = oat_file;
718 break;
Andreas Gampe833a4852014-05-21 18:46:59 -0700719 }
720 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700721 }
722
Richard Uhler66d874d2015-01-15 09:37:19 -0800723 // If we didn't have an up-to-date oat file open, try to load one from disk.
724 if (source_oat_file == nullptr) {
725 // Update the oat file on disk if we can. This may fail, but that's okay.
726 // Best effort is all that matters here.
727 if (!oat_file_assistant.MakeUpToDate(&error_msg)) {
728 LOG(WARNING) << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700729 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700730
Richard Uhler66d874d2015-01-15 09:37:19 -0800731 // Get the oat file on disk.
732 std::unique_ptr<OatFile> oat_file = oat_file_assistant.GetBestOatFile();
733 if (oat_file.get() != nullptr) {
734 source_oat_file = oat_file.release();
735 RegisterOatFile(source_oat_file);
Andreas Gampe833a4852014-05-21 18:46:59 -0700736 }
737 }
738
Richard Uhler66d874d2015-01-15 09:37:19 -0800739 std::vector<std::unique_ptr<const DexFile>> dex_files;
Andreas Gampe833a4852014-05-21 18:46:59 -0700740
Richard Uhler66d874d2015-01-15 09:37:19 -0800741 // Load the dex files from the oat file.
742 if (source_oat_file != nullptr) {
743 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
744 if (dex_files.empty()) {
745 error_msgs->push_back("Failed to open dex files from "
746 + source_oat_file->GetLocation());
Andreas Gampe833a4852014-05-21 18:46:59 -0700747 }
748 }
749
Richard Uhler66d874d2015-01-15 09:37:19 -0800750 // Fall back to running out of the original dex file if we couldn't load any
751 // dex_files from the oat file.
752 if (dex_files.empty()) {
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700753 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800754 if (!DexFile::Open(dex_location, dex_location, &error_msg, &dex_files)) {
755 LOG(WARNING) << error_msg;
756 error_msgs->push_back("Failed to open dex files from "
757 + std::string(dex_location));
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700758 }
759 } else {
760 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
761 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700762 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800763 return dex_files;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700764}
765
Brian Carlstromae826982011-11-09 01:33:42 -0800766const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700767 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700768 for (size_t i = 0; i < oat_files_.size(); i++) {
769 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700770 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -0800771 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700772 return oat_file;
773 }
774 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700775 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -0700776}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700777
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800778void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700779 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700780 DCHECK(obj != nullptr);
781 DCHECK(class_linker != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700782 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700783 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -0700784 if (!method->IsNative()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800785 const size_t pointer_size = class_linker->image_pointer_size_;
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800786 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800787 if (!method->IsRuntimeMethod() && method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800788 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
789 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -0700790 }
791 }
792 }
793}
794
Mathieu Chartierc7853442015-03-27 14:35:38 -0700795void SanityCheckObjectsCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED)
796 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
797 DCHECK(obj != nullptr);
798 CHECK(obj->GetClass() != nullptr) << "Null class " << obj;
799 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
800 if (obj->IsClass()) {
801 auto klass = obj->AsClass();
802 ArtField* fields[2] = { klass->GetSFields(), klass->GetIFields() };
803 size_t num_fields[2] = { klass->NumStaticFields(), klass->NumInstanceFields() };
804 for (size_t i = 0; i < 2; ++i) {
805 for (size_t j = 0; j < num_fields[i]; ++j) {
806 CHECK_EQ(fields[i][j].GetDeclaringClass(), klass);
807 }
808 }
809 }
810}
811
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700812void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800813 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700814 CHECK(!init_done_);
815
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700816 Runtime* const runtime = Runtime::Current();
817 Thread* const self = Thread::Current();
818 gc::Heap* const heap = runtime->GetHeap();
819 gc::space::ImageSpace* const space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700820 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700821 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700822 OatFile& oat_file = GetImageOatFile(space);
823 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
824 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700825 const char* image_file_location = oat_file.GetOatHeader().
826 GetStoreValueByKey(OatHeader::kImageLocationKey);
827 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700828 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -0700829 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -0800830 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +0100831 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800832 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
833 mirror::ObjectArray<mirror::DexCache>* dex_caches =
834 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700835
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700836 StackHandleScope<1> hs(self);
837 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
838 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
839 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700840 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700841
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700842 // Special case of setting up the String class early so that we can test arbitrary objects
843 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700844 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800845
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700846 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700847 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700848 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800849 StackHandleScope<1> hs2(self);
850 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700851 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700852 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
853 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700854 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700855 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800856 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
857 if (dex_file.get() == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700858 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700859 << " from within oat file " << oat_file.GetLocation()
860 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -0800861 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700862 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700863
864 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
865
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800866 AppendToBootClassPath(*dex_file.get(), dex_cache);
867 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700868 }
869
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700870 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
871 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -0700872 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -0800873 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700874 if (!runtime->IsAotCompiler()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800875 // Aot compiler supports having an image with a different pointer size than the runtime. This
Mathieu Chartier2d721012014-11-10 11:08:06 -0800876 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
877 // also use 32 bit dex2oat on a system with 64 bit apps.
878 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
879 << sizeof(void*);
880 }
881 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
882 image_pointer_size_ = 4;
883 } else {
884 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
885 image_pointer_size_ = 8;
886 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700887
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700888 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800889 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700890 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700891 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700892 if (kSanityCheckObjects) {
893 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
894 auto* dex_cache = dex_caches->Get(i);
895 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
896 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
897 if (field != nullptr) {
898 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
899 }
900 }
901 }
902 heap->VisitObjects(SanityCheckObjectsCallback, nullptr);
903 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700904
905 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800906 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700907 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700908
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800909 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700910 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800911 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800912 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700913 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
914 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700915 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
916 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
917 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
918 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
Fred Shih4ee7a662014-07-11 09:59:27 -0700919 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800920 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
921 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
922 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
923 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
924 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
925 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
926 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
927 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
928 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
929 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700930
Ian Rogers98379392014-02-24 16:53:16 -0800931 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700932
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800933 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700934}
935
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700936void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700937 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700938 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
939 visitor, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700940 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800941 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700942 buffered_visitor.VisitRoot(root);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700943 root.Read()->VisitFieldRoots(buffered_visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800944 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700945 // PreZygote classes can't move so we won't need to update fields' declaring classes.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800946 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700947 buffered_visitor.VisitRoot(root);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700948 root.Read()->VisitFieldRoots(buffered_visitor);
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700949 }
950 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800951 for (auto& root : new_class_roots_) {
952 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700953 old_ref->VisitFieldRoots(buffered_visitor);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700954 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800955 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700956 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700957 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
958 // corresponding object. This is slow, but luckily for us, this may only happen with a
959 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800960 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800961 DCHECK(it != class_table_.end());
962 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700963 }
964 }
965 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700966 buffered_visitor.Flush(); // Flush before clearing new_class_roots_.
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700967 if ((flags & kVisitRootFlagClearRootLog) != 0) {
968 new_class_roots_.clear();
969 }
970 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
971 log_new_class_table_roots_ = true;
972 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
973 log_new_class_table_roots_ = false;
974 }
975 // We deliberately ignore the class roots in the image since we
976 // handle image roots by using the MS/CMS rescanning of dirty cards.
977}
978
Brian Carlstroma663ea52011-08-19 23:33:41 -0700979// Keep in sync with InitCallback. Anything we visit, we need to
980// reinit references to when reinitializing a ClassLinker from a
981// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700982void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
983 class_roots_.VisitRoot(visitor, RootInfo(kRootVMInternal));
984 Thread* const self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -0700985 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700986 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800987 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700988 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700989 dex_cache.VisitRoot(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -0700990 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800991 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
992 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700993 dex_caches_[index].VisitRoot(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -0700994 }
Elliott Hughesf8349362012-06-18 15:00:06 -0700995 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800996 if ((flags & kVisitRootFlagClearRootLog) != 0) {
997 new_dex_cache_roots_.clear();
998 }
999 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1000 log_new_dex_caches_roots_ = true;
1001 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1002 log_new_dex_caches_roots_ = false;
1003 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001004 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001005 VisitClassRoots(visitor, flags);
1006 array_iftable_.VisitRoot(visitor, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001007 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001008 find_array_class_cache_[i].VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001009 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001010}
1011
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001012void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1013 if (dex_cache_image_class_lookup_required_) {
1014 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001015 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001016 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001017 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001018 for (GcRoot<mirror::Class>& root : class_table_) {
1019 if (!visitor(root.Read(), arg)) {
1020 return;
1021 }
1022 }
1023 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1024 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001025 return;
1026 }
1027 }
1028}
1029
Ian Rogersdbf3be02014-08-29 15:40:08 -07001030static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001031 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001032 classes->insert(c);
1033 return true;
1034}
1035
Ian Rogersdbf3be02014-08-29 15:40:08 -07001036struct GetClassesVisitorArrayArg {
1037 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1038 int32_t index;
1039 bool success;
1040};
1041
1042static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1043 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1044 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1045 if (arg->index < (*arg->classes)->GetLength()) {
1046 (*arg->classes)->Set(arg->index, c);
1047 arg->index++;
1048 return true;
1049 } else {
1050 arg->success = false;
1051 return false;
1052 }
1053}
1054
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001055void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001056 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1057 // is avoiding duplicates.
1058 if (!kMovingClasses) {
1059 std::set<mirror::Class*> classes;
1060 VisitClasses(GetClassesVisitorSet, &classes);
1061 for (mirror::Class* klass : classes) {
1062 if (!visitor(klass, arg)) {
1063 return;
1064 }
1065 }
1066 } else {
1067 Thread* self = Thread::Current();
1068 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001069 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001070 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1071 GetClassesVisitorArrayArg local_arg;
1072 local_arg.classes = &classes;
1073 local_arg.success = false;
1074 // We size the array assuming classes won't be added to the class table during the visit.
1075 // If this assumption fails we iterate again.
1076 while (!local_arg.success) {
1077 size_t class_table_size;
1078 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001079 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001080 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001081 }
1082 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1083 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1084 classes.Assign(
1085 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1086 CHECK(classes.Get() != nullptr); // OOME.
1087 local_arg.index = 0;
1088 local_arg.success = true;
1089 VisitClasses(GetClassesVisitorArray, &local_arg);
1090 }
1091 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1092 // If the class table shrank during creation of the clases array we expect null elements. If
1093 // the class table grew then the loop repeats. If classes are created after the loop has
1094 // finished then we don't visit.
1095 mirror::Class* klass = classes->Get(i);
1096 if (klass != nullptr && !visitor(klass, arg)) {
1097 return;
1098 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001099 }
1100 }
1101}
1102
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001103ClassLinker::~ClassLinker() {
Brian Carlstromea46f952013-07-30 01:26:50 -07001104 mirror::ArtMethod::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001105 mirror::Class::ResetClass();
1106 mirror::Constructor::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001107 mirror::Field::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001108 mirror::Method::ResetClass();
1109 mirror::Reference::ResetClass();
1110 mirror::StackTraceElement::ResetClass();
1111 mirror::String::ResetClass();
1112 mirror::Throwable::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001113 mirror::BooleanArray::ResetArrayClass();
1114 mirror::ByteArray::ResetArrayClass();
1115 mirror::CharArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001116 mirror::Constructor::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001117 mirror::DoubleArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001118 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001119 mirror::FloatArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001120 mirror::Method::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001121 mirror::IntArray::ResetArrayClass();
1122 mirror::LongArray::ResetArrayClass();
1123 mirror::ShortArray::ResetArrayClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001124 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001125}
1126
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001127mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001128 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001129 StackHandleScope<16> hs(self);
1130 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1131 Handle<mirror::DexCache> dex_cache(
1132 hs.NewHandle(down_cast<mirror::DexCache*>(
1133 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1134 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001135 if (dex_cache.Get() == nullptr) {
1136 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001137 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001138 Handle<mirror::String>
1139 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001140 if (location.Get() == nullptr) {
1141 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001142 }
Ian Rogers700a4022014-05-19 16:49:03 -07001143 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001144 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001145 if (strings.Get() == nullptr) {
1146 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001147 }
Ian Rogers700a4022014-05-19 16:49:03 -07001148 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001149 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001150 if (types.Get() == nullptr) {
1151 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001152 }
Ian Rogers700a4022014-05-19 16:49:03 -07001153 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001154 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001155 if (methods.Get() == nullptr) {
1156 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001157 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001158 Handle<mirror::Array> fields;
1159 if (image_pointer_size_ == 8) {
1160 fields = hs.NewHandle<mirror::Array>(mirror::LongArray::Alloc(self, dex_file.NumFieldIds()));
1161 } else {
1162 fields = hs.NewHandle<mirror::Array>(mirror::IntArray::Alloc(self, dex_file.NumFieldIds()));
1163 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001164 if (fields.Get() == nullptr) {
1165 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001166 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001167 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1168 fields.Get());
1169 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001170}
1171
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001172mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001173 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001174 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001175 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001176 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001177 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001178 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1179 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001180 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001181 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001182 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001183 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001184 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001185}
1186
Ian Rogers6fac4472014-02-25 17:01:10 -08001187mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001188 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001189}
1190
Brian Carlstromea46f952013-07-30 01:26:50 -07001191mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001192 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001193 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001194}
1195
Mathieu Chartier590fee92013-09-13 13:46:47 -07001196mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1197 Thread* self, size_t length) {
1198 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1199 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001200}
1201
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001202mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1203 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001204 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001205
1206 // For temporary classes we must wait for them to be retired.
1207 if (init_done_ && klass->IsTemp()) {
1208 CHECK(!klass->IsResolved());
1209 if (klass->IsErroneous()) {
1210 ThrowEarlierClassFailure(klass);
1211 return nullptr;
1212 }
1213 StackHandleScope<1> hs(self);
1214 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1215 ObjectLock<mirror::Class> lock(self, h_class);
1216 // Loop and wait for the resolving thread to retire this class.
1217 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1218 lock.WaitIgnoringInterrupts();
1219 }
1220 if (h_class->IsErroneous()) {
1221 ThrowEarlierClassFailure(h_class.Get());
1222 return nullptr;
1223 }
1224 CHECK(h_class->IsRetired());
1225 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001226 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
1227 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001228 }
1229
Brian Carlstromaded5f72011-10-07 17:15:04 -07001230 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001231 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001232 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001233 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1234 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001235 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001236 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1237 ThrowClassCircularityError(h_class.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001238 mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001239 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001240 }
1241 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001242 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001243 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001244 }
1245 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001246
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001247 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001248 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001249 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001250 }
1251 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001252 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001253 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001254 return klass;
1255}
1256
Ian Rogers68b56852014-08-29 20:19:11 -07001257typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
1258
1259// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001260ClassPathEntry FindInClassPath(const char* descriptor,
1261 size_t hash, const std::vector<const DexFile*>& class_path) {
1262 for (const DexFile* dex_file : class_path) {
1263 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001264 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07001265 return ClassPathEntry(dex_file, dex_class_def);
1266 }
1267 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001268 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07001269}
1270
Andreas Gampef865ea92015-04-13 22:14:19 -07001271static bool IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1272 mirror::ClassLoader* class_loader)
1273 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1274 return class_loader == nullptr ||
1275 class_loader->GetClass() ==
1276 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader);
1277}
1278
1279bool ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1280 Thread* self, const char* descriptor,
1281 size_t hash,
1282 Handle<mirror::ClassLoader> class_loader,
1283 mirror::Class** result) {
1284 // Termination case: boot class-loader.
1285 if (IsBootClassLoader(soa, class_loader.Get())) {
1286 // The boot class loader, search the boot class path.
1287 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
1288 if (pair.second != nullptr) {
1289 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
1290 if (klass != nullptr) {
1291 *result = EnsureResolved(self, descriptor, klass);
1292 } else {
1293 *result = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(),
1294 *pair.first, *pair.second);
1295 }
1296 if (*result == nullptr) {
1297 CHECK(self->IsExceptionPending()) << descriptor;
1298 self->ClearException();
1299 }
Ian Rogers32427292014-11-19 14:05:21 -08001300 } else {
Andreas Gampef865ea92015-04-13 22:14:19 -07001301 *result = nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001302 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001303 return true;
1304 }
1305
1306 // Unsupported class-loader?
1307 if (class_loader->GetClass() !=
1308 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)) {
1309 *result = nullptr;
1310 return false;
1311 }
1312
1313 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
1314 StackHandleScope<4> hs(self);
1315 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
1316 bool recursive_result = FindClassInPathClassLoader(soa, self, descriptor, hash, h_parent, result);
1317
1318 if (!recursive_result) {
1319 // Something wrong up the chain.
1320 return false;
1321 }
1322
1323 if (*result != nullptr) {
1324 // Found the class up the chain.
1325 return true;
1326 }
1327
1328 // Handle this step.
1329 // Handle as if this is the child PathClassLoader.
1330 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
1331 // We need to get the DexPathList and loop through it.
1332 ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
1333 ArtField* const dex_file_field =
1334 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
1335 mirror::Object* dex_path_list =
1336 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
1337 GetObject(class_loader.Get());
1338 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
1339 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1340 mirror::Object* dex_elements_obj =
1341 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1342 GetObject(dex_path_list);
1343 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1344 // at the mCookie which is a DexFile vector.
1345 if (dex_elements_obj != nullptr) {
1346 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
1347 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
1348 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
1349 mirror::Object* element = dex_elements->GetWithoutChecks(i);
1350 if (element == nullptr) {
1351 // Should never happen, fall back to java code to throw a NPE.
1352 break;
1353 }
1354 mirror::Object* dex_file = dex_file_field->GetObject(element);
1355 if (dex_file != nullptr) {
1356 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
1357 if (long_array == nullptr) {
1358 // This should never happen so log a warning.
1359 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001360 break;
1361 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001362 int32_t long_array_size = long_array->GetLength();
1363 for (int32_t j = 0; j < long_array_size; ++j) {
1364 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
1365 long_array->GetWithoutChecks(j)));
1366 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
1367 if (dex_class_def != nullptr) {
1368 RegisterDexFile(*cp_dex_file);
1369 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
1370 *cp_dex_file, *dex_class_def);
1371 if (klass == nullptr) {
1372 CHECK(self->IsExceptionPending()) << descriptor;
1373 self->ClearException();
1374 // TODO: Is it really right to break here, and not check the other dex files?
1375 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001376 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001377 *result = klass;
1378 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001379 }
1380 }
1381 }
1382 }
1383 }
Ian Rogers32427292014-11-19 14:05:21 -08001384 self->AssertNoPendingException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001385 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001386
1387 // Result is still null from the parent call, no need to set it again...
1388 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001389}
1390
Ian Rogers98379392014-02-24 16:53:16 -08001391mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001392 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001393 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001394 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001395 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001396 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001397 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1398 // for primitive classes that aren't backed by dex files.
1399 return FindPrimitiveClass(descriptor[0]);
1400 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001401 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001402 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001403 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07001404 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001405 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001406 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001407 // Class is not yet loaded.
1408 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001409 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001410 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001411 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001412 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07001413 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001414 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07001415 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07001416 } else {
1417 // The boot class loader is searched ahead of the application class loader, failures are
1418 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
1419 // trigger the chaining with a proper stack trace.
1420 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001421 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07001422 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05001423 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001424 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001425 ScopedObjectAccessUnchecked soa(self);
Andreas Gampef865ea92015-04-13 22:14:19 -07001426 mirror::Class* cp_klass;
1427 if (FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader, &cp_klass)) {
1428 // The chain was understood. So the value in cp_klass is either the class we were looking
1429 // for, or not found.
1430 if (cp_klass != nullptr) {
1431 return cp_klass;
1432 }
1433 // TODO: We handle the boot classpath loader in FindClassInPathClassLoader. Try to unify this
1434 // and the branch above. TODO: throw the right exception here.
1435
1436 // We'll let the Java-side rediscover all this and throw the exception with the right stack
1437 // trace.
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07001438 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001439
1440 if (Runtime::Current()->IsAotCompiler()) {
1441 // Oops, compile-time, can't run actual class-loader code.
1442 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
1443 self->SetException(pre_allocated);
1444 return nullptr;
1445 }
1446
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001447 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001448 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001449 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07001450 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07001451 {
1452 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001453 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1454 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07001455 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001456 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07001457 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07001458 }
Ian Rogers68b56852014-08-29 20:19:11 -07001459 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001460 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1461 WellKnownClasses::java_lang_ClassLoader_loadClass,
1462 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001463 }
Ian Rogers98379392014-02-24 16:53:16 -08001464 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001465 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07001466 return nullptr;
1467 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08001468 // broken loader - throw NPE to be compatible with Dalvik
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001469 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
1470 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07001471 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08001472 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001473 // success, return mirror::Class*
1474 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001475 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001476 }
Ian Rogers07140832014-09-30 15:43:59 -07001477 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001478}
1479
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001480mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001481 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001482 const DexFile& dex_file,
1483 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001484 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001485 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001486
Brian Carlstromaded5f72011-10-07 17:15:04 -07001487 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001488 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001489 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001490 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001491 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001492 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001493 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001494 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001495 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001496 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1497 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001498 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001499 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001500 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001501 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001502 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001503 }
1504
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001505 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001506 // Allocate a class with the status of not ready.
1507 // Interface object should get the right size here. Regular class will
1508 // figure out the right size later and be replaced with one of the right
1509 // size when the class becomes resolved.
1510 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001511 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001512 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001513 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07001514 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001515 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001516 klass->SetDexCache(FindDexCache(dex_file));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001517
1518 SetupClass(dex_file, dex_class_def, klass, class_loader.Get());
1519
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001520 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001521 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001522
Mathieu Chartier590fee92013-09-13 13:46:47 -07001523 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001524 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001525 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001526 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1527 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001528 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001529 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001530
Mathieu Chartierc7853442015-03-27 14:35:38 -07001531 // Load the fields and other things after we are inserted in the table. This is so that we don't
1532 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
1533 // other reason is that the field roots are only visited from the class table. So we need to be
1534 // inserted before we allocate / fill in these fields.
1535 LoadClass(self, dex_file, dex_class_def, klass);
1536 if (self->IsExceptionPending()) {
1537 // An exception occured during load, set status to erroneous while holding klass' lock in case
1538 // notification is necessary.
1539 if (!klass->IsErroneous()) {
1540 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
1541 }
1542 return nullptr;
1543 }
1544
Brian Carlstromaded5f72011-10-07 17:15:04 -07001545 // Finish loading (if necessary) by finding parents
1546 CHECK(!klass->IsLoaded());
1547 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1548 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001549 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001550 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001551 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001552 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001553 }
1554 CHECK(klass->IsLoaded());
1555 // Link the class (if necessary)
1556 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001557 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001558 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001559
1560 mirror::Class* new_class = nullptr;
1561 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001562 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001563 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001564 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001565 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001566 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001567 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07001568 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001569 CHECK(new_class != nullptr) << descriptor;
1570 CHECK(new_class->IsResolved()) << descriptor;
1571
1572 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001573
Sebastien Hertza8a697f2015-01-15 12:28:47 +01001574 // Instrumentation may have updated entrypoints for all methods of all
1575 // classes. However it could not update methods of this class while we
1576 // were loading it. Now the class is resolved, we can update entrypoints
1577 // as required by instrumentation.
1578 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
1579 // We must be in the kRunnable state to prevent instrumentation from
1580 // suspending all threads to update entrypoints while we are doing it
1581 // for this class.
1582 DCHECK_EQ(self->GetState(), kRunnable);
1583 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(new_class_h.Get());
1584 }
1585
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001586 /*
1587 * We send CLASS_PREPARE events to the debugger from here. The
1588 * definition of "preparation" is creating the static fields for a
1589 * class and initializing them to the standard default values, but not
1590 * executing any code (that comes later, during "initialization").
1591 *
1592 * We did the static preparation in LinkClass.
1593 *
1594 * The class has been prepared and resolved but possibly not yet verified
1595 * at this point.
1596 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001597 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001598
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001599 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001600}
1601
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001602uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
1603 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07001604 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001605 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07001606 size_t num_8 = 0;
1607 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001608 size_t num_32 = 0;
1609 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001610 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001611 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1612 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001613 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001614 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07001615 switch (c) {
1616 case 'L':
1617 case '[':
1618 num_ref++;
1619 break;
1620 case 'J':
1621 case 'D':
1622 num_64++;
1623 break;
1624 case 'I':
1625 case 'F':
1626 num_32++;
1627 break;
1628 case 'S':
1629 case 'C':
1630 num_16++;
1631 break;
1632 case 'B':
1633 case 'Z':
1634 num_8++;
1635 break;
1636 default:
1637 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08001638 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001639 }
1640 }
1641 }
Fred Shih37f05ef2014-07-16 18:38:08 -07001642 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001643}
1644
Ian Rogers97b52f82014-08-14 11:34:07 -07001645OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
1646 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001647 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Richard Uhler07b3c232015-03-31 15:57:54 -07001648 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001649 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001650 *found = false;
1651 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001652 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001653 *found = true;
1654 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08001655}
1656
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001657static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
1658 uint32_t method_idx) {
1659 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07001660 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001661 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001662 ClassDataItemIterator it(dex_file, class_data);
1663 // Skip fields
1664 while (it.HasNextStaticField()) {
1665 it.Next();
1666 }
1667 while (it.HasNextInstanceField()) {
1668 it.Next();
1669 }
1670 // Process methods
1671 size_t class_def_method_index = 0;
1672 while (it.HasNextDirectMethod()) {
1673 if (it.GetMemberIndex() == method_idx) {
1674 return class_def_method_index;
1675 }
1676 class_def_method_index++;
1677 it.Next();
1678 }
1679 while (it.HasNextVirtualMethod()) {
1680 if (it.GetMemberIndex() == method_idx) {
1681 return class_def_method_index;
1682 }
1683 class_def_method_index++;
1684 it.Next();
1685 }
1686 DCHECK(!it.HasNext());
1687 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08001688 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001689}
1690
Ian Rogers97b52f82014-08-14 11:34:07 -07001691const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08001692 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001693 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001694 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08001695 size_t oat_method_index;
1696 if (method->IsStatic() || method->IsDirect()) {
1697 // Simple case where the oat method index was stashed at load time.
1698 oat_method_index = method->GetMethodIndex();
1699 } else {
1700 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1701 // by search for its position in the declared virtual methods.
1702 oat_method_index = declaring_class->NumDirectMethods();
1703 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001704 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001705 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07001706 // Check method index instead of identity in case of duplicate method definitions.
1707 if (method->GetDexMethodIndex() ==
1708 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001709 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001710 break;
1711 }
Ian Rogersf320b632012-03-13 18:47:47 -07001712 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001713 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001714 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
1715 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001716 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001717 DCHECK_EQ(oat_method_index,
1718 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001719 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001720 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07001721 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
1722 declaring_class->GetDexClassDefIndex(),
1723 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001724 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001725 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001726 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001727 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07001728}
1729
1730// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001731const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001732 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07001733 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001734 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07001735 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001736 bool found;
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001737 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1738 if (found) {
1739 auto* code = oat_method.GetQuickCode();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001740 if (code != nullptr) {
1741 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08001742 }
1743 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001744 jit::Jit* const jit = Runtime::Current()->GetJit();
1745 if (jit != nullptr) {
1746 auto* code = jit->GetCodeCache()->GetCodeFor(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001747 if (code != nullptr) {
1748 return code;
1749 }
1750 }
1751 if (method->IsNative()) {
1752 // No code and native? Use generic trampoline.
1753 return GetQuickGenericJniStub();
1754 }
1755 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07001756}
1757
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001758const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
1759 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
1760 return nullptr;
1761 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001762 bool found;
1763 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1764 if (found) {
1765 return oat_method.GetQuickCode();
1766 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001767 jit::Jit* jit = Runtime::Current()->GetJit();
1768 if (jit != nullptr) {
1769 auto* code = jit->GetCodeCache()->GetCodeFor(method);
1770 if (code != nullptr) {
1771 return code;
1772 }
1773 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001774 return nullptr;
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001775}
1776
Ian Rogersef7d42f2014-01-06 12:55:46 -08001777const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
1778 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001779 bool found;
1780 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
1781 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001782 return nullptr;
1783 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001784 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001785 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001786}
1787
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001788// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001789static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07001790 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08001791 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001792 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08001793 // May return true for native code, in the case of generic JNI
1794 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001795 return true;
1796 }
1797 // If interpreter mode is enabled, every method (except native and proxy) must
1798 // be run with interpreter.
1799 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
1800 !method->IsNative() && !method->IsProxyMethod();
1801}
1802
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001803void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08001804 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07001805 if (klass->NumDirectMethods() == 0) {
1806 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08001807 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001808 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001809 if (!runtime->IsStarted()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001810 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001811 return; // OAT file unavailable.
1812 }
Ian Rogers19846512012-02-24 11:42:47 -08001813 }
Alex Light64ad14d2014-08-19 14:23:13 -07001814
Mathieu Chartierf8322842014-05-16 10:59:25 -07001815 const DexFile& dex_file = klass->GetDexFile();
1816 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07001817 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07001818 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07001819 // There should always be class data if there were direct methods.
1820 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08001821 ClassDataItemIterator it(dex_file, class_data);
1822 // Skip fields
1823 while (it.HasNextStaticField()) {
1824 it.Next();
1825 }
1826 while (it.HasNextInstanceField()) {
1827 it.Next();
1828 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001829 bool has_oat_class;
1830 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1831 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07001832 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001833 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001834 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001835 if (!method->IsStatic()) {
1836 // Only update static methods.
1837 continue;
Ian Rogers19846512012-02-24 11:42:47 -08001838 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001839 const void* quick_code = nullptr;
1840 if (has_oat_class) {
1841 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001842 quick_code = oat_method.GetQuickCode();
1843 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001844 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001845 if (enter_interpreter) {
1846 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07001847 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001848 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001849 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08001850 } else {
1851 quick_code = GetQuickToInterpreterBridge();
1852 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001853 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001854 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08001855 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001856 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08001857}
1858
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001859void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07001860 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001861 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001862 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001863 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001864 // The following code only applies to a non-compiler runtime.
1865 return;
1866 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001867 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001868 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001869 if (oat_class != nullptr) {
1870 // Every kind of method should at least get an invoke stub from the oat_method.
1871 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001872 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001873 oat_method.LinkMethod(method.Get());
1874 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001875
Jeff Hao16743632013-05-08 10:59:04 -07001876 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001877 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08001878 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001879 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001880 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001881 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07001882 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001883 }
1884
Brian Carlstrom92827a52011-10-10 15:50:01 -07001885 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001886 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001887 return;
1888 }
Ian Rogers19846512012-02-24 11:42:47 -08001889
1890 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001891 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001892 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
1893 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001894 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001895 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001896 if (!method->IsNative()) {
1897 // Set entry point from compiled code if there's no code or in interpreter only mode.
1898 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001899 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001900 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001901 }
Ian Rogers0d6de042012-02-29 08:50:26 -08001902 }
jeffhao26c0a1a2012-01-17 16:28:33 -08001903
Ian Rogers62d6c772013-02-27 08:32:07 -08001904 if (method->IsNative()) {
1905 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001906 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07001907
1908 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001909 // We have a native method here without code. Then it should have either the generic JNI
1910 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
1911 // TODO: this doesn't handle all the cases where trampolines may be installed.
1912 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1913 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07001914 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001915 }
1916}
1917
Mathieu Chartierc7853442015-03-27 14:35:38 -07001918void ClassLinker::SetupClass(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1919 Handle<mirror::Class> klass, mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001920 CHECK(klass.Get() != nullptr);
1921 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001922 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001923 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001924 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001925
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001926 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07001927 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07001928 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001929 klass->SetAccessFlags(access_flags);
1930 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001931 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001932 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001933
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001934 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001935 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08001936 CHECK(klass->GetDexCacheStrings() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001937}
Brian Carlstrom934486c2011-07-12 23:42:50 -07001938
Mathieu Chartierc7853442015-03-27 14:35:38 -07001939void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
1940 const DexFile::ClassDef& dex_class_def,
1941 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07001942 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001943 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001944 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001945 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001946 bool has_oat_class = false;
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001947 if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001948 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1949 &has_oat_class);
1950 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001951 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07001952 }
1953 }
1954 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001955 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001956 }
1957}
1958
Mathieu Chartierc7853442015-03-27 14:35:38 -07001959ArtField* ClassLinker::AllocArtFieldArray(Thread* self, size_t length) {
1960 auto* const la = Runtime::Current()->GetLinearAlloc();
1961 auto* ptr = reinterpret_cast<ArtField*>(la->AllocArray<ArtField>(self, length));
1962 CHECK(ptr!= nullptr);
1963 std::uninitialized_fill_n(ptr, length, ArtField());
1964 return ptr;
1965}
1966
Ian Rogers7b078e82014-09-10 14:44:24 -07001967void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07001968 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001969 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001970 const OatFile::OatClass* oat_class) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001971 // Load static fields.
Ian Rogers0571d352011-11-03 19:51:38 -07001972 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001973 const size_t num_sfields = it.NumStaticFields();
1974 ArtField* sfields = num_sfields != 0 ? AllocArtFieldArray(self, num_sfields) : nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001975 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001976 CHECK_LT(i, num_sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001977 LoadField(it, klass, &sfields[i]);
Ian Rogers0571d352011-11-03 19:51:38 -07001978 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001979 klass->SetSFields(sfields);
1980 klass->SetNumStaticFields(num_sfields);
1981 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
1982 // Load instance fields.
1983 const size_t num_ifields = it.NumInstanceFields();
1984 ArtField* ifields = num_ifields != 0 ? AllocArtFieldArray(self, num_ifields) : nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001985 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001986 CHECK_LT(i, num_ifields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001987 LoadField(it, klass, &ifields[i]);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001988 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001989 klass->SetIFields(ifields);
1990 klass->SetNumInstanceFields(num_ifields);
1991 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07001992 // Note: We cannot have thread suspension until the field arrays are setup or else
1993 // Class::VisitFieldRoots may miss some fields.
1994 self->AllowThreadSuspension();
Ian Rogers0571d352011-11-03 19:51:38 -07001995 // Load methods.
1996 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001997 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07001998 mirror::ObjectArray<mirror::ArtMethod>* directs =
1999 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002000 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002001 CHECK(self->IsExceptionPending()); // OOME.
2002 return;
2003 }
2004 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002005 }
Ian Rogers0571d352011-11-03 19:51:38 -07002006 if (it.NumVirtualMethods() != 0) {
2007 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002008 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2009 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002010 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002011 CHECK(self->IsExceptionPending()); // OOME.
2012 return;
2013 }
2014 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002015 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002016 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002017 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2018 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002019 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002020 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002021 StackHandleScope<1> hs(self);
2022 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002023 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002024 CHECK(self->IsExceptionPending()); // OOME.
2025 return;
2026 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002027 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002028 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002029 uint32_t it_method_index = it.GetMemberIndex();
2030 if (last_dex_method_index == it_method_index) {
2031 // duplicate case
2032 method->SetMethodIndex(last_class_def_method_index);
2033 } else {
2034 method->SetMethodIndex(class_def_method_index);
2035 last_dex_method_index = it_method_index;
2036 last_class_def_method_index = class_def_method_index;
2037 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002038 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002039 }
2040 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002041 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002042 StackHandleScope<1> hs(self);
2043 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002044 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002045 CHECK(self->IsExceptionPending()); // OOME.
2046 return;
2047 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002048 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002049 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002050 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002051 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002052 }
2053 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002054}
2055
Mathieu Chartierc7853442015-03-27 14:35:38 -07002056void ClassLinker::LoadField(const ClassDataItemIterator& it, Handle<mirror::Class> klass,
2057 ArtField* dst) {
2058 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002059 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002060 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002061 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002062}
2063
Brian Carlstromea46f952013-07-30 01:26:50 -07002064mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002065 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002066 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002067 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002068 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002069 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002070
Brian Carlstromea46f952013-07-30 01:26:50 -07002071 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002072 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002073 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002074 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002075 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002076 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002077
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002078 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002079 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002080 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002081 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002082
Ian Rogers19846512012-02-24 11:42:47 -08002083 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002084 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002085
Andreas Gampe51829322014-08-25 15:05:04 -07002086 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002087
Ian Rogersdfb325e2013-10-30 01:00:44 -07002088 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002089 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002090 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2091 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002092 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002093 klass->SetFinalizable();
2094 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002095 std::string temp;
2096 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002097 // The Enum class declares a "final" finalize() method to prevent subclasses from
2098 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2099 // subclasses, so we exclude it here.
2100 // We also want to avoid setting the flag on Object, where we know that finalize() is
2101 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002102 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2103 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002104 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002105 }
2106 }
2107 }
2108 } else if (method_name[0] == '<') {
2109 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002110 bool is_init = (strcmp("<init>", method_name) == 0);
2111 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002112 if (UNLIKELY(!is_init && !is_clinit)) {
2113 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2114 } else {
2115 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2116 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002117 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002118 access_flags |= kAccConstructor;
2119 }
2120 }
2121 }
2122 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002123
Mathieu Chartier66f19252012-09-18 08:57:04 -07002124 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002125}
2126
Ian Rogers7b078e82014-09-10 14:44:24 -07002127void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002128 StackHandleScope<1> hs(self);
2129 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002130 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2131 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002132 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002133}
2134
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002135void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002136 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002137 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002138 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002139 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002140}
2141
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002142bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002143 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002144 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002145 mirror::DexCache* dex_cache = GetDexCache(i);
2146 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002147 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002148 }
2149 }
2150 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002151}
2152
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002153bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002154 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002155 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002156}
2157
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002158void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002159 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002160 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002161 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002162 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2163 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002164 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002165 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002166 if (log_new_dex_caches_roots_) {
2167 // TODO: This is not safe if we can remove dex caches.
2168 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2169 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002170}
2171
Brian Carlstromaded5f72011-10-07 17:15:04 -07002172void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002173 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002174 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002175 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002176 if (IsDexFileRegisteredLocked(dex_file)) {
2177 return;
2178 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002179 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002180 // Don't alloc while holding the lock, since allocation may need to
2181 // suspend all threads and another thread may need the dex_lock_ to
2182 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002183 StackHandleScope<1> hs(self);
2184 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002185 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2186 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002187 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002188 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002189 if (IsDexFileRegisteredLocked(dex_file)) {
2190 return;
2191 }
2192 RegisterDexFileLocked(dex_file, dex_cache);
2193 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002194}
2195
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002196void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002197 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002198 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002199 RegisterDexFileLocked(dex_file, dex_cache);
2200}
2201
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002202mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002203 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002204 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002205 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002206 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002207 if (dex_cache->GetDexFile() == &dex_file) {
2208 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002209 }
2210 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002211 // Search matching by location name.
2212 std::string location(dex_file.GetLocation());
2213 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002214 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002215 if (dex_cache->GetDexFile()->GetLocation() == location) {
2216 return dex_cache;
2217 }
2218 }
2219 // Failure, dump diagnostic and abort.
2220 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002221 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002222 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2223 }
2224 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002225 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002226}
2227
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002228void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002229 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08002230 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002231 mirror::DexCache* dex_cache = GetDexCache(i);
2232 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08002233 }
2234}
2235
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002236mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002237 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002238 if (UNLIKELY(klass == nullptr)) {
2239 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002240 }
2241 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002242}
2243
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002244mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2245 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002246 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07002247 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002248 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002249 StackHandleScope<1> hs(self);
2250 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002251 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002252 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
2253 h_class->SetPrimitiveType(type);
2254 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002255 const char* descriptor = Primitive::Descriptor(type);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002256 mirror::Class* existing = InsertClass(descriptor, h_class.Get(),
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002257 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002258 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002259 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07002260}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002261
Brian Carlstrombe977852011-07-19 14:54:54 -07002262// Create an array class (i.e. the class object for the array, not the
2263// array itself). "descriptor" looks like "[C" or "[[[[B" or
2264// "[Ljava/lang/String;".
2265//
2266// If "descriptor" refers to an array of primitives, look up the
2267// primitive type's internally-generated class object.
2268//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002269// "class_loader" is the class loader of the class that's referring to
2270// us. It's used to ensure that we're looking for the element type in
2271// the right context. It does NOT become the class loader for the
2272// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002273//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002274// Returns null with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002275mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002276 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002277 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002278 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002279 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002280 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
2281 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002282 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002283 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002284 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002285 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
2286 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002287 if (component_type.Get() == nullptr) {
2288 DCHECK(self->IsExceptionPending());
2289 return nullptr;
2290 } else {
2291 self->ClearException();
2292 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002293 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002294 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2295 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2296 return nullptr;
2297 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002298 // See if the component type is already loaded. Array classes are
2299 // always associated with the class loader of their underlying
2300 // element type -- an array of Strings goes with the loader for
2301 // java/lang/String -- so we need to look for it there. (The
2302 // caller should have checked for the existence of the class
2303 // before calling here, but they did so with *their* class loader,
2304 // not the component type's loader.)
2305 //
2306 // If we find it, the caller adds "loader" to the class' initiating
2307 // loader list, which should prevent us from going through this again.
2308 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002309 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002310 // are the same, because our caller (FindClass) just did the
2311 // lookup. (Even if we get this wrong we still have correct behavior,
2312 // because we effectively do this lookup again when we add the new
2313 // class to the hash table --- necessary because of possible races with
2314 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002315 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002316 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002317 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002318 return new_class;
2319 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002320 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002321
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002322 // Fill out the fields in the Class.
2323 //
2324 // It is possible to execute some methods against arrays, because
2325 // all arrays are subclasses of java_lang_Object_, so we need to set
2326 // up a vtable. We can just point at the one in java_lang_Object_.
2327 //
2328 // Array classes are simple enough that we don't need to do a full
2329 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002330 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002331 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002332 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002333 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002334 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002335 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002336 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002337 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002338 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002339 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002340 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002341 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002342 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002343 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002344 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002345 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002346 } else if (strcmp(descriptor, "[J") == 0) {
2347 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002348 }
2349 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002350 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002351 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002352 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002353 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002354 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002355 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002356 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002357 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002358 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002359 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002360 new_class->SetSuperClass(java_lang_Object);
2361 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002362 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002363 new_class->SetClassLoader(component_type->GetClassLoader());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002364 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002365 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002366 StackHandleScope<mirror::Class::kImtSize> hs2(self,
2367 Runtime::Current()->GetImtUnimplementedMethod());
2368 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002369 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002370 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002371 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002372 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002373
2374
2375 // All arrays have java/lang/Cloneable and java/io/Serializable as
2376 // interfaces. We need to set that up here, so that stuff like
2377 // "instanceof" works right.
2378 //
2379 // Note: The GC could run during the call to FindSystemClass,
2380 // so we need to make sure the class object is GC-valid while we're in
2381 // there. Do this by clearing the interface list so the GC will just
2382 // think that the entries are null.
2383
2384
2385 // Use the single, global copies of "interfaces" and "iftable"
2386 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002387 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002388 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002389 CHECK(array_iftable != nullptr);
2390 new_class->SetIfTable(array_iftable);
2391 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002392
Elliott Hughes00626c22013-06-14 15:04:14 -07002393 // Inherit access flags from the component type.
2394 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2395 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2396 access_flags &= kAccJavaFlagsMask;
2397 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002398 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002399 access_flags |= kAccAbstract | kAccFinal;
2400 access_flags &= ~kAccInterface;
2401
2402 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002403
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002404 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002405 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002406 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002407 }
2408 // Another thread must have loaded the class after we
2409 // started but before we finished. Abandon what we've
2410 // done.
2411 //
2412 // (Yes, this happens.)
2413
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002414 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002415}
2416
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002417mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002418 switch (type) {
2419 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002420 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002421 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002422 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002423 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002424 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002425 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002426 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002427 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002428 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002429 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002430 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002431 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002432 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002433 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002434 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002435 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002436 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002437 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002438 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002439 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002440 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002441 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002442 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002443}
2444
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002445mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2446 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002447 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002448 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002449 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002450 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08002451 source += " from ";
2452 source += dex_cache->GetLocation()->ToModifiedUtf8();
2453 }
2454 LOG(INFO) << "Loaded class " << descriptor << source;
2455 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002456 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002457 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002458 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002459 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002460 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002461 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002462 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002463 // Check a class loaded with the system class loader matches one in the image if the class
2464 // is in the image.
2465 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002466 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002467 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002468 }
2469 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002470 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002471 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002472 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002473 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002474 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002475 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002476}
2477
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002478mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
2479 size_t hash) {
2480 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002481 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
2482 hash);
2483 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002484 CHECK(klass->IsProxyClass());
2485 return nullptr;
2486 }
2487
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002488 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002489 CHECK_NE(existing, klass) << descriptor;
2490 CHECK(!existing->IsResolved()) << descriptor;
2491 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
2492
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002493 CHECK(!klass->IsTemp()) << descriptor;
2494 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
2495 dex_cache_image_class_lookup_required_) {
2496 // Check a class loaded with the system class loader matches one in the image if the class
2497 // is in the image.
2498 existing = LookupClassFromImage(descriptor);
2499 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002500 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002501 }
2502 }
2503 VerifyObject(klass);
2504
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002505 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002506 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002507 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002508 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002509 }
2510
2511 return existing;
2512}
2513
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002514bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002515 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002516 auto pair = std::make_pair(descriptor, class_loader);
2517 auto it = class_table_.Find(pair);
2518 if (it != class_table_.end()) {
2519 class_table_.Erase(it);
2520 return true;
2521 }
2522 it = pre_zygote_class_table_.Find(pair);
2523 if (it != pre_zygote_class_table_.end()) {
2524 pre_zygote_class_table_.Erase(it);
2525 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08002526 }
2527 return false;
2528}
2529
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002530mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002531 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002532 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002533 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002534 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002535 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002536 return result;
2537 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07002538 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002539 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
2540 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002541 } else {
2542 // Lookup failed but need to search dex_caches_.
2543 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002544 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002545 InsertClass(descriptor, result, hash);
2546 } else {
2547 // Searching the image dex files/caches failed, we don't want to get into this situation
2548 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2549 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07002550 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002551 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2552 MoveImageClassesToClassTable();
2553 }
2554 }
2555 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002556 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002557}
2558
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002559mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002560 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002561 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002562 auto descriptor_pair = std::make_pair(descriptor, class_loader);
2563 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
2564 if (it == pre_zygote_class_table_.end()) {
2565 it = class_table_.FindWithHash(descriptor_pair, hash);
2566 if (it == class_table_.end()) {
2567 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07002568 }
2569 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002570 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002571}
2572
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002573static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
2574 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2575 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002576 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002577 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2578 return root->AsObjectArray<mirror::DexCache>();
2579}
2580
2581void ClassLinker::MoveImageClassesToClassTable() {
2582 Thread* self = Thread::Current();
2583 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2584 if (!dex_cache_image_class_lookup_required_) {
2585 return; // All dex cache classes are already in the class table.
2586 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002587 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002588 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002589 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002590 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2591 mirror::DexCache* dex_cache = dex_caches->Get(i);
2592 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
2593 for (int32_t j = 0; j < types->GetLength(); j++) {
2594 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002595 if (klass != nullptr) {
2596 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002597 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002598 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002599 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
2600 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002601 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002602 << PrettyClassAndClassLoader(klass);
2603 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002604 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002605 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002606 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002607 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002608 }
2609 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002610 }
2611 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002612 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002613}
2614
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002615void ClassLinker::MoveClassTableToPreZygote() {
2616 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2617 DCHECK(pre_zygote_class_table_.Empty());
2618 pre_zygote_class_table_ = std::move(class_table_);
2619 class_table_.Clear();
2620}
2621
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002622mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002623 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002624 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2625 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
2626 mirror::DexCache* dex_cache = dex_caches->Get(i);
2627 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00002628 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002629 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002630 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002631 const DexFile::TypeId* type_id =
2632 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002633 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002634 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
2635 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002636 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002637 return klass;
2638 }
2639 }
2640 }
2641 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002642 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002643}
2644
2645void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
2646 result.clear();
2647 if (dex_cache_image_class_lookup_required_) {
2648 MoveImageClassesToClassTable();
2649 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002650 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2651 while (true) {
2652 auto it = class_table_.Find(descriptor);
2653 if (it == class_table_.end()) {
2654 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002655 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002656 result.push_back(it->Read());
2657 class_table_.Erase(it);
2658 }
2659 for (mirror::Class* k : result) {
2660 class_table_.Insert(GcRoot<mirror::Class>(k));
2661 }
2662 size_t pre_zygote_start = result.size();
2663 // Now handle the pre zygote table.
2664 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
2665 // called from the debugger.
2666 while (true) {
2667 auto it = pre_zygote_class_table_.Find(descriptor);
2668 if (it == pre_zygote_class_table_.end()) {
2669 break;
2670 }
2671 result.push_back(it->Read());
2672 pre_zygote_class_table_.Erase(it);
2673 }
2674 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
2675 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002676 }
2677}
2678
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002679void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002680 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002681 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08002682
Ian Rogers9ffb0392012-09-10 11:56:50 -07002683 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002684 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07002685 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07002686 return;
2687 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002688 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002689 return;
2690 }
jeffhao98eacac2011-09-14 16:11:53 -07002691
Ian Rogers9ffb0392012-09-10 11:56:50 -07002692 // The class might already be erroneous, for example at compile time if we attempted to verify
2693 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002694 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002695 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002696 return;
2697 }
2698
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002699 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002700 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002701 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002702 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002703 << PrettyClass(klass.Get());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002704 CHECK(!Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002705 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002706 }
jeffhao98eacac2011-09-14 16:11:53 -07002707
Jeff Hao4a200f52014-04-01 14:58:49 -07002708 // Skip verification if disabled.
2709 if (!Runtime::Current()->IsVerificationEnabled()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002710 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07002711 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07002712 return;
2713 }
2714
Ian Rogers9ffb0392012-09-10 11:56:50 -07002715 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002716 StackHandleScope<2> hs(self);
2717 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002718 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07002719 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002720 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002721
2722 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002723 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002724 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002725 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07002726 std::string error_msg(
2727 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
2728 PrettyDescriptor(klass.Get()).c_str(),
2729 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08002730 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002731 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002732 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002733 self->ClearException();
2734 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002735 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
2736 if (cause.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002737 self->GetException()->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002738 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08002739 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002740 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00002741 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
2742 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002743 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002744 return;
2745 }
2746 }
2747
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002748 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07002749 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002750 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002751 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002752 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002753 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002754 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002755 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002756 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
2757 PrettyDescriptor(klass.Get()).c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002758 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07002759 return;
2760 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002761 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08002762 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07002763 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002764 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002765 Runtime::Current()->IsAotCompiler(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002766 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002767 }
2768 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07002769 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002770 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07002771 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2772 << " because: " << error_msg;
2773 }
Ian Rogers1f539342012-10-03 21:09:42 -07002774 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002775 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002776 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002777 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002778 // Even though there were no verifier failures we need to respect whether the super-class
2779 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002780 if (super.Get() == nullptr || super->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002781 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002782 } else {
2783 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002784 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002785 // Pretend a soft failure occured so that we don't consider the class verified below.
2786 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002787 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002788 } else {
2789 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
2790 // Soft failures at compile time should be retried at runtime. Soft
2791 // failures at runtime will be handled by slow paths in the generated
2792 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002793 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002794 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002795 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002796 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002797 // As this is a fake verified status, make sure the methods are _not_ marked preverified
2798 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07002799 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002800 }
2801 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07002802 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002803 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08002804 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2805 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002806 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002807 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002808 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002809 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002810 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002811 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002812 // Let the interpreter know it by setting the kAccPreverified flag onto each
2813 // method.
2814 // Note: we're going here during compilation and at runtime. When we set the
2815 // kAccPreverified flag when compiling image classes, the flag is recorded
2816 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07002817 EnsurePreverifiedMethods(klass);
2818 }
2819}
2820
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002821void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002822 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002823 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07002824 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002825 }
jeffhao98eacac2011-09-14 16:11:53 -07002826}
2827
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002828bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
2829 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002830 // If we're compiling, we can only verify the class using the oat file if
2831 // we are not compiling the image or if the class we're verifying is not part of
2832 // the app. In other words, we will only check for preverification of bootclasspath
2833 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002834 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002835 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002836 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002837 return false;
2838 }
2839 // We are compiling an app (not the image).
2840
2841 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002842 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002843 return false;
2844 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002845 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002846
Richard Uhler07b3c232015-03-31 15:57:54 -07002847 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002848 // In case we run without an image there won't be a backing oat file.
2849 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07002850 return false;
2851 }
2852
Andreas Gampe76bd8802014-12-10 16:43:58 -08002853 // We may be running with a preopted oat file but without image. In this case,
2854 // we don't skip verification of preverified classes to ensure we initialize
2855 // dex caches with all types resolved during verification.
2856 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
2857 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
2858 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
2859 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002860 if (!Runtime::Current()->IsAotCompiler() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08002861 !Runtime::Current()->GetHeap()->HasImageSpace() &&
2862 klass->GetClassLoader() != nullptr) {
2863 return false;
2864 }
2865
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002866 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002867 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002868 if (oat_file_class_status == mirror::Class::kStatusVerified ||
2869 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002870 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002871 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002872 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07002873 // Compile time verification failed with a soft error. Compile time verification can fail
2874 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08002875 // class ... {
2876 // Foo x;
2877 // .... () {
2878 // if (...) {
2879 // v1 gets assigned a type of resolved class Foo
2880 // } else {
2881 // v1 gets assigned a type of unresolved class Bar
2882 // }
2883 // iput x = v1
2884 // } }
2885 // when we merge v1 following the if-the-else it results in Conflict
2886 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2887 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2888 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2889 // at compile time).
2890 return false;
2891 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002892 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07002893 // Compile time verification failed with a hard error. This is caused by invalid instructions
2894 // in the class. These errors are unrecoverable.
2895 return false;
2896 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002897 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002898 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2899 // not loading the class.
2900 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2901 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002902 return false;
2903 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002904 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002905 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002906 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07002907 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08002908 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002909}
2910
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002911void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002912 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002913 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2914 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2915 }
2916 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2917 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2918 }
2919}
2920
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002921void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07002922 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002923 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2924 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002925 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002926 return; // native or abstract method
2927 }
2928 if (code_item->tries_size_ == 0) {
2929 return; // nothing to process
2930 }
Ian Rogers13735952014-10-08 12:43:28 -07002931 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002932 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2933 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2934 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2935 CatchHandlerIterator iterator(handlers_ptr);
2936 for (; iterator.HasNext(); iterator.Next()) {
2937 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2938 // unresolved exception types will be ignored by exception delivery
2939 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002940 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002941 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002942 DCHECK(Thread::Current()->IsExceptionPending());
2943 Thread::Current()->ClearException();
2944 }
2945 }
2946 }
2947 handlers_ptr = iterator.EndDataPointer();
2948 }
2949}
2950
Brian Carlstromea46f952013-07-30 01:26:50 -07002951static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002952static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
2953 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08002954
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07002955mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07002956 jobjectArray interfaces, jobject loader,
2957 jobjectArray methods, jobjectArray throws) {
2958 Thread* self = soa.Self();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002959 StackHandleScope<9> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002960 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002961 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002962 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002963 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002964 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002965 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002966 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002967 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07002968 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
2969 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002970 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08002971 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002972 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002973 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002974 klass->SetDexCache(proxy_class->GetDexCache());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002975 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08002976
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002977 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002978 const size_t num_fields = 2;
2979 ArtField* sfields = AllocArtFieldArray(self, num_fields);
2980 klass->SetSFields(sfields);
2981 klass->SetNumStaticFields(num_fields);
2982
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002983 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
2984 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartierc7853442015-03-27 14:35:38 -07002985 ArtField* interfaces_sfield = &sfields[0];
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002986 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002987 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002988 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002989
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002990 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartierc7853442015-03-27 14:35:38 -07002991 ArtField* throws_sfield = &sfields[1];
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002992 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002993 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002994 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002995
Ian Rogers466bb252011-10-14 03:29:56 -07002996 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07002997 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002998 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002999 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003000 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003001 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003002 }
3003 klass->SetDirectMethods(directs);
3004 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003005 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003006 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003007 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003008 }
3009 klass->SetDirectMethod(0, constructor);
3010 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003011
Mathieu Chartier590fee92013-09-13 13:46:47 -07003012 // Create virtual method using specified prototypes.
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003013 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>*>(methods));
3014 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
3015 << PrettyClass(h_methods->GetClass());
3016 const size_t num_virtual_methods = h_methods->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003017 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003018 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3019 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003020 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003021 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003022 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003023 }
3024 klass->SetVirtualMethods(virtuals);
3025 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003026 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003027 StackHandleScope<1> hs2(self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003028 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(h_methods->Get(i)->GetArtMethod()));
Ian Rogersa436fde2013-08-27 23:34:06 -07003029 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003030 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003031 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003032 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003033 }
3034 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003035 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003036
3037 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003038 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003039 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003040
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003041 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3042 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003043 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003044 // Must hold lock on object when resolved.
3045 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003046 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003047 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003048 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003049 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003050 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003051 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003052 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003053 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003054
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003055 CHECK(klass->IsRetired());
3056 CHECK_NE(klass.Get(), new_class);
3057 klass.Assign(new_class);
3058
3059 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003060 interfaces_sfield->SetObject<false>(klass.Get(),
3061 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003062 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003063 throws_sfield->SetObject<false>(klass.Get(),
3064 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003065
3066 {
3067 // Lock on klass is released. Lock new class object.
3068 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003069 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003070 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003071
3072 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003073 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003074 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003075 CheckProxyConstructor(klass->GetDirectMethod(0));
3076 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003077 StackHandleScope<2> hs2(self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003078 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(h_methods->Get(i)->GetArtMethod()));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003079 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003080 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003081 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003082
Mathieu Chartier590fee92013-09-13 13:46:47 -07003083 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003084 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003085 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003086 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3087
3088 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003089 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003090 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003091
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003092 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003093 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003094 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003095 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003096 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003097 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3098 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003099 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003100 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003101}
3102
Ian Rogersef7d42f2014-01-06 12:55:46 -08003103std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003104 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003105 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003106 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003107 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3108}
3109
Ian Rogersef7d42f2014-01-06 12:55:46 -08003110mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3111 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003112 DCHECK(proxy_class->IsProxyClass());
3113 DCHECK(proxy_method->IsProxyMethod());
Ian Rogers16f93672012-02-14 12:29:06 -08003114 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003115 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003116 // Locate the dex cache of the original interface/Object
3117 for (const GcRoot<mirror::DexCache>& root : dex_caches_) {
3118 auto* dex_cache = root.Read();
3119 if (proxy_method->HasSameDexCacheResolvedTypes(dex_cache->GetResolvedTypes())) {
3120 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(
3121 proxy_method->GetDexMethodIndex());
3122 CHECK(resolved_method != nullptr);
3123 return resolved_method;
Ian Rogers16f93672012-02-14 12:29:06 -08003124 }
3125 }
3126 }
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003127 LOG(FATAL) << "Didn't find dex cache for " << PrettyClass(proxy_class) << " "
3128 << PrettyMethod(proxy_method);
3129 UNREACHABLE();
Ian Rogers16f93672012-02-14 12:29:06 -08003130}
3131
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003132
Brian Carlstromea46f952013-07-30 01:26:50 -07003133mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003134 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003135 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003136 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003137 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003138 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003139 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3140 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003141 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3142 // constructor method.
3143 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3144 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003145 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3146 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003147 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3148 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003149 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003150 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003151 }
Ian Rogers466bb252011-10-14 03:29:56 -07003152 // Make this constructor public and fix the class to be our Proxy version
3153 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003154 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003155 return constructor;
3156}
3157
Brian Carlstromea46f952013-07-30 01:26:50 -07003158static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003159 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003160 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003161 CHECK_STREQ(constructor->GetName(), "<init>");
3162 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3163 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003164 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003165}
3166
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003167mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003168 Handle<mirror::Class> klass,
3169 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003170 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3171 // prototype method
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003172 auto* dex_cache = prototype->GetDeclaringClass()->GetDexCache();
3173 // Avoid dirtying the dex cache unless we need to.
3174 if (dex_cache->GetResolvedMethod(prototype->GetDexMethodIndex()) != prototype.Get()) {
3175 dex_cache->SetResolvedMethod(prototype->GetDexMethodIndex(), prototype.Get());
3176 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003177 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003178 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003179 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003180 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003181 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003182 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003183 }
Ian Rogers466bb252011-10-14 03:29:56 -07003184
3185 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3186 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003187 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003188 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003189
Ian Rogers466bb252011-10-14 03:29:56 -07003190 // At runtime the method looks like a reference and argument saving method, clone the code
3191 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003192 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003193 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003194
Ian Rogersc2b44472011-12-14 21:17:17 -08003195 return method;
3196}
Jesse Wilson95caa792011-10-12 18:14:17 -04003197
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003198static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3199 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003200 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003201 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003202 CHECK(!prototype->IsFinal());
3203 CHECK(method->IsFinal());
3204 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003205
3206 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3207 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07003208 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
3209 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003210 CHECK_EQ(prototype->GetDeclaringClass()->GetDexCache(), method->GetDexCache());
Ian Rogers19846512012-02-24 11:42:47 -08003211 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3212
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003213 CHECK_STREQ(method->GetName(), prototype->GetName());
3214 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003215 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07003216 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04003217}
3218
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003219static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3220 bool can_init_parents)
3221 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003222 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003223 return true;
3224 }
3225 if (!can_init_statics) {
3226 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07003227 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003228 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003229 return false;
3230 }
3231 // Check if there are encoded static values needing initialization.
3232 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003233 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003234 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003235 if (dex_class_def->static_values_off_ != 0) {
3236 return false;
3237 }
3238 }
3239 }
3240 if (!klass->IsInterface() && klass->HasSuperClass()) {
3241 mirror::Class* super_class = klass->GetSuperClass();
3242 if (!can_init_parents && !super_class->IsInitialized()) {
3243 return false;
3244 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003245 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003246 return false;
3247 }
3248 }
3249 }
3250 return true;
3251}
3252
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003253bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07003254 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003255 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3256
3257 // Are we already initialized and therefore done?
3258 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3259 // an initialized class will never change its state.
3260 if (klass->IsInitialized()) {
3261 return true;
3262 }
3263
3264 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003265 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003266 return false;
3267 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003268
Ian Rogers7b078e82014-09-10 14:44:24 -07003269 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003270 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003271 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003272 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003273
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003274 // Re-check under the lock in case another thread initialized ahead of us.
3275 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003276 return true;
3277 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003278
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003279 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003280 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003281 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003282 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003283 return false;
3284 }
3285
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003286 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003287
3288 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003289 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003290 if (!klass->IsVerified()) {
3291 // We failed to verify, expect either the klass to be erroneous or verification failed at
3292 // compile time.
3293 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003294 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003295 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003296 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003297 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003298 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003299 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003300 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07003301 } else {
3302 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003303 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003304 }
3305
Brian Carlstromd1422f82011-09-28 11:37:09 -07003306 // If the class is kStatusInitializing, either this thread is
3307 // initializing higher up the stack or another thread has beat us
3308 // to initializing and we need to wait. Either way, this
3309 // invocation of InitializeClass will not be responsible for
3310 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003311 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07003312 // Could have got an exception during verification.
3313 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003314 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003315 return false;
3316 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003317 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003318 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003319 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003320 return true;
3321 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003322 // No. That's fine. Wait for another thread to finish initializing.
3323 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003324 }
3325
3326 if (!ValidateSuperClassDescriptors(klass)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003327 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003328 return false;
3329 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003330 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003331
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003332 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003333
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003334 // From here out other threads may observe that we're initializing and so changes of state
3335 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003336 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003337 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003338
3339 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003340 }
3341
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003342 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003343 if (!klass->IsInterface() && klass->HasSuperClass()) {
3344 mirror::Class* super_class = klass->GetSuperClass();
3345 if (!super_class->IsInitialized()) {
3346 CHECK(!super_class->IsInterface());
3347 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003348 StackHandleScope<1> hs(self);
3349 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07003350 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003351 if (!super_initialized) {
3352 // The super class was verified ahead of entering initializing, we should only be here if
3353 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003354 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003355 << "Super class initialization failed for "
3356 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003357 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003358 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003359 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003360 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003361 // Initialization failed because the super-class is erroneous.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003362 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003363 return false;
3364 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003365 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003366 }
3367
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003368 const size_t num_static_fields = klass->NumStaticFields();
3369 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003370 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003371 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003372 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07003373 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003374 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003375 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003376
3377 // Eagerly fill in static fields so that the we don't have to do as many expensive
3378 // Class::FindStaticField in ResolveField.
3379 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003380 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003381 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003382 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003383 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003384 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07003385 } else {
3386 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003387 }
3388 }
3389
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003390 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
3391 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07003392 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003393 ClassDataItemIterator field_it(dex_file, class_data);
3394 if (value_it.HasNext()) {
3395 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003396 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003397 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003398 ArtField* field = ResolveField(
3399 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003400 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003401 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003402 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003403 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003404 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003405 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003406 }
3407 }
3408 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003409
Ian Rogersd91d6d62013-09-25 20:26:14 -07003410 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003411 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003412 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003413 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003414 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003415 }
3416
Ian Rogers7b078e82014-09-10 14:44:24 -07003417 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003418 uint64_t t1 = NanoTime();
3419
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003420 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003421 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003422 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003423
3424 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003425 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003426 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003427 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003428 } else if (Runtime::Current()->IsTransactionAborted()) {
3429 // The exception thrown when the transaction aborted has been caught and cleared
3430 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01003431 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
3432 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02003433 Runtime::Current()->ThrowTransactionAbortError(self);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003434 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003435 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003436 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003437 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3438 RuntimeStats* thread_stats = self->GetStats();
3439 ++global_stats->class_init_count;
3440 ++thread_stats->class_init_count;
3441 global_stats->class_init_time_ns += (t1 - t0);
3442 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003443 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003444 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003445 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003446 std::string temp;
3447 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003448 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003449 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003450 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003451 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003452 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003453 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003454 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003455}
3456
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003457bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003458 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003459 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003460 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003461 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003462 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08003463 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003464
3465 // When we wake up, repeat the test for init-in-progress. If
3466 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07003467 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003468 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003469 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003470 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003471 return false;
3472 }
3473 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003474 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003475 continue;
3476 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003477 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
3478 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003479 // Compile time initialization failed.
3480 return false;
3481 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003482 if (klass->IsErroneous()) {
3483 // The caller wants an exception, but it was thrown in a
3484 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003485 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003486 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003487 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003488 return false;
3489 }
3490 if (klass->IsInitialized()) {
3491 return true;
3492 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003493 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003494 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003495 }
Ian Rogers07140832014-09-30 15:43:59 -07003496 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003497}
3498
Ian Rogersb5fb2072014-12-02 17:22:02 -08003499static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
3500 Handle<mirror::ArtMethod> method1,
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003501 Handle<mirror::ArtMethod> method2,
3502 std::string* error_msg)
Ian Rogersb5fb2072014-12-02 17:22:02 -08003503 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3504 {
3505 StackHandleScope<1> hs(self);
3506 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
Vladimir Marko862f43c2015-02-10 18:22:57 +00003507 mirror::Class* other_return_type = method2->GetReturnType();
3508 // NOTE: return_type.Get() must be sequenced after method2->GetReturnType().
3509 if (UNLIKELY(other_return_type != return_type.Get())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003510 *error_msg = StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
3511 PrettyClassAndClassLoader(return_type.Get()).c_str(),
3512 return_type.Get(),
3513 PrettyClassAndClassLoader(other_return_type).c_str(),
3514 other_return_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003515 return false;
3516 }
3517 }
3518 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
3519 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
3520 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003521 if (types2 != nullptr && types2->Size() != 0) {
3522 *error_msg = StringPrintf("Type list mismatch with %s",
3523 PrettyMethod(method2.Get(), true).c_str());
3524 return false;
3525 }
3526 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003527 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003528 if (types1->Size() != 0) {
3529 *error_msg = StringPrintf("Type list mismatch with %s",
3530 PrettyMethod(method2.Get(), true).c_str());
3531 return false;
3532 }
3533 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003534 }
3535 uint32_t num_types = types1->Size();
3536 if (UNLIKELY(num_types != types2->Size())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003537 *error_msg = StringPrintf("Type list mismatch with %s",
3538 PrettyMethod(method2.Get(), true).c_str());
Ian Rogersb5fb2072014-12-02 17:22:02 -08003539 return false;
3540 }
3541 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00003542 StackHandleScope<1> hs(self);
3543 Handle<mirror::Class> param_type(hs.NewHandle(
3544 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true)));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003545 mirror::Class* other_param_type =
3546 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
Vladimir Marko862f43c2015-02-10 18:22:57 +00003547 // NOTE: param_type.Get() must be sequenced after method2->GetClassFromTypeIndex(...).
3548 if (UNLIKELY(param_type.Get() != other_param_type)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003549 *error_msg = StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
3550 i,
3551 PrettyClassAndClassLoader(param_type.Get()).c_str(),
3552 param_type.Get(),
3553 PrettyClassAndClassLoader(other_param_type).c_str(),
3554 other_param_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003555 return false;
3556 }
3557 }
3558 return true;
3559}
3560
3561
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003562bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003563 if (klass->IsInterface()) {
3564 return true;
3565 }
Ian Rogers151f2212014-05-06 11:27:27 -07003566 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07003567 Thread* self = Thread::Current();
3568 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003569 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
3570 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003571 if (klass->HasSuperClass() &&
3572 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003573 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003574 h_m.Assign(klass->GetVTableEntry(i));
3575 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003576 if (h_m.Get() != super_h_m.Get()) {
3577 std::string error_msg;
3578 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3579 ThrowLinkageError(klass.Get(),
3580 "Class %s method %s resolves differently in superclass %s: %s",
3581 PrettyDescriptor(klass.Get()).c_str(),
3582 PrettyMethod(h_m.Get()).c_str(),
3583 PrettyDescriptor(klass->GetSuperClass()).c_str(),
3584 error_msg.c_str());
3585 return false;
3586 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003587 }
3588 }
3589 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003590 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07003591 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
3592 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
3593 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003594 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
3595 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003596 if (h_m.Get() != super_h_m.Get()) {
3597 std::string error_msg;
3598 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3599 ThrowLinkageError(klass.Get(),
3600 "Class %s method %s resolves differently in interface %s: %s",
3601 PrettyDescriptor(klass.Get()).c_str(),
3602 PrettyMethod(h_m.Get()).c_str(),
3603 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str(),
3604 error_msg.c_str());
3605 return false;
3606 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003607 }
3608 }
3609 }
3610 }
3611 return true;
3612}
3613
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003614bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
3615 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003616 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003617 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003618 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003619 return true;
3620 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003621 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003622 if (!success) {
3623 if (can_init_fields && can_init_parents) {
3624 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
3625 }
3626 } else {
3627 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08003628 }
3629 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003630}
3631
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003632void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003633 ArtField* fields = new_class->GetIFields();
3634 for (size_t i = 0, count = new_class->NumInstanceFields(); i < count; i++) {
3635 if (fields[i].GetDeclaringClass() == temp_class) {
3636 fields[i].SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003637 }
3638 }
3639
3640 fields = new_class->GetSFields();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003641 for (size_t i = 0, count = new_class->NumStaticFields(); i < count; i++) {
3642 if (fields[i].GetDeclaringClass() == temp_class) {
3643 fields[i].SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003644 }
3645 }
3646
3647 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
3648 if (methods != nullptr) {
3649 for (int index = 0; index < methods->GetLength(); index ++) {
3650 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3651 methods->Get(index)->SetDeclaringClass(new_class);
3652 }
3653 }
3654 }
3655
3656 methods = new_class->GetVirtualMethods();
3657 if (methods != nullptr) {
3658 for (int index = 0; index < methods->GetLength(); index ++) {
3659 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3660 methods->Get(index)->SetDeclaringClass(new_class);
3661 }
3662 }
3663 }
3664}
3665
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003666bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
3667 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003668 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003669 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003670
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003671 if (!LinkSuperClass(klass)) {
3672 return false;
3673 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003674 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
3675 self, Runtime::Current()->GetImtUnimplementedMethod());
3676 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003677 return false;
3678 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003679 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003680 return false;
3681 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003682 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07003683 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003684 return false;
3685 }
3686 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003687 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003688
3689 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
3690 // We don't need to retire this class as it has no embedded tables or it was created the
3691 // correct size during class linker initialization.
3692 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
3693
3694 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003695 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003696 }
3697
3698 // This will notify waiters on klass that saw the not yet resolved
3699 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003700 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003701 *new_class = klass.Get();
3702 } else {
3703 CHECK(!klass->IsResolved());
3704 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003705 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003706 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003707 CHECK(self->IsExceptionPending()); // Expect an OOME.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003708 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003709 return false;
3710 }
3711
3712 CHECK_EQ((*new_class)->GetClassSize(), class_size);
3713 StackHandleScope<1> hs(self);
3714 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
3715 ObjectLock<mirror::Class> lock(self, new_class_h);
3716
3717 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
3718
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003719 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
3720 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003721 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003722
3723 // This will notify waiters on temp class that saw the not yet resolved class in the
3724 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003725 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003726
3727 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
3728 // This will notify waiters on new_class that saw the not yet resolved
3729 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003730 mirror::Class::SetStatus(new_class_h, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003731 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003732 return true;
3733}
3734
Andreas Gampefd9eb392014-11-06 16:52:58 -08003735static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
3736 size_t* virtual_methods,
3737 size_t* direct_methods,
3738 size_t* static_fields,
3739 size_t* instance_fields) {
3740 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
3741
3742 while (dex_data.HasNextStaticField()) {
3743 dex_data.Next();
3744 (*static_fields)++;
3745 }
3746 while (dex_data.HasNextInstanceField()) {
3747 dex_data.Next();
3748 (*instance_fields)++;
3749 }
3750 while (dex_data.HasNextDirectMethod()) {
3751 (*direct_methods)++;
3752 dex_data.Next();
3753 }
3754 while (dex_data.HasNextVirtualMethod()) {
3755 (*virtual_methods)++;
3756 dex_data.Next();
3757 }
3758 DCHECK(!dex_data.HasNext());
3759}
3760
3761static void DumpClass(std::ostream& os,
3762 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
3763 const char* suffix) {
3764 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
3765 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
3766 os << " Static fields:\n";
3767 while (dex_data.HasNextStaticField()) {
3768 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3769 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3770 dex_data.Next();
3771 }
3772 os << " Instance fields:\n";
3773 while (dex_data.HasNextInstanceField()) {
3774 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3775 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3776 dex_data.Next();
3777 }
3778 os << " Direct methods:\n";
3779 while (dex_data.HasNextDirectMethod()) {
3780 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3781 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3782 dex_data.Next();
3783 }
3784 os << " Virtual methods:\n";
3785 while (dex_data.HasNextVirtualMethod()) {
3786 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3787 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3788 dex_data.Next();
3789 }
3790}
3791
3792static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3793 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
3794 std::ostringstream os;
3795 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
3796 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
3797 return os.str();
3798}
3799
3800
3801// Very simple structural check on whether the classes match. Only compares the number of
3802// methods and fields.
3803static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3804 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
3805 std::string* error_msg) {
3806 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
3807 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
3808
3809 // Counters for current dex file.
3810 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
3811 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
3812 &dex_instance_fields1);
3813 // Counters for compile-time dex file.
3814 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
3815 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
3816 &dex_instance_fields2);
3817
3818 if (dex_virtual_methods1 != dex_virtual_methods2) {
3819 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3820 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
3821 dex_virtual_methods2, class_dump.c_str());
3822 return false;
3823 }
3824 if (dex_direct_methods1 != dex_direct_methods2) {
3825 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3826 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
3827 dex_direct_methods2, class_dump.c_str());
3828 return false;
3829 }
3830 if (dex_static_fields1 != dex_static_fields2) {
3831 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3832 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
3833 dex_static_fields2, class_dump.c_str());
3834 return false;
3835 }
3836 if (dex_instance_fields1 != dex_instance_fields2) {
3837 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3838 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
3839 dex_instance_fields2, class_dump.c_str());
3840 return false;
3841 }
3842
3843 return true;
3844}
3845
3846// Checks whether a the super-class changed from what we had at compile-time. This would
3847// invalidate quickening.
3848static bool CheckSuperClassChange(Handle<mirror::Class> klass,
3849 const DexFile& dex_file,
3850 const DexFile::ClassDef& class_def,
3851 mirror::Class* super_class)
3852 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3853 // Check for unexpected changes in the superclass.
3854 // Quick check 1) is the super_class class-loader the boot class loader? This always has
3855 // precedence.
3856 if (super_class->GetClassLoader() != nullptr &&
3857 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
3858 // which is implied by different dex cache.
3859 klass->GetDexCache() != super_class->GetDexCache()) {
3860 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
3861 // definition for the super-class, and (b) the files are in separate oat files. The oat files
3862 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
Richard Uhler07b3c232015-03-31 15:57:54 -07003863 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
3864 const OatFile* class_oat_file = nullptr;
3865 if (class_oat_dex_file != nullptr) {
3866 class_oat_file = class_oat_dex_file->GetOatFile();
3867 }
3868
Andreas Gampefd9eb392014-11-06 16:52:58 -08003869 if (class_oat_file != nullptr) {
Richard Uhler07b3c232015-03-31 15:57:54 -07003870 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
3871 const OatFile* loaded_super_oat_file = nullptr;
3872 if (loaded_super_oat_dex_file != nullptr) {
3873 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
3874 }
3875
Andreas Gampefd9eb392014-11-06 16:52:58 -08003876 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
3877 // Now check (a).
3878 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
3879 if (super_class_def != nullptr) {
3880 // Uh-oh, we found something. Do our check.
3881 std::string error_msg;
3882 if (!SimpleStructuralCheck(dex_file, *super_class_def,
3883 super_class->GetDexFile(), *super_class->GetClassDef(),
3884 &error_msg)) {
3885 // Print a warning to the log. This exception might be caught, e.g., as common in test
3886 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
3887 // only save the type of the exception.
3888 LOG(WARNING) << "Incompatible structural change detected: " <<
3889 StringPrintf(
3890 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3891 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3892 class_oat_file->GetLocation().c_str(),
3893 loaded_super_oat_file->GetLocation().c_str(),
3894 error_msg.c_str());
3895 ThrowIncompatibleClassChangeError(klass.Get(),
3896 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3897 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3898 class_oat_file->GetLocation().c_str(),
3899 loaded_super_oat_file->GetLocation().c_str(),
3900 error_msg.c_str());
3901 return false;
3902 }
3903 }
3904 }
3905 }
3906 }
3907 return true;
3908}
3909
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003910bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003911 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003912 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3913 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003914 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003915 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003916 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003917 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003918 return false;
3919 }
Ian Rogersbe125a92012-01-11 15:19:49 -08003920 // Verify
3921 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003922 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003923 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003924 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08003925 return false;
3926 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003927 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003928 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08003929
3930 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
3931 DCHECK(Thread::Current()->IsExceptionPending());
3932 return false;
3933 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003934 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003935 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003936 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003937 for (size_t i = 0; i < interfaces->Size(); i++) {
3938 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003939 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003940 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003941 DCHECK(Thread::Current()->IsExceptionPending());
3942 return false;
3943 }
3944 // Verify
3945 if (!klass->CanAccess(interface)) {
3946 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003947 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003948 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003949 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003950 return false;
3951 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003952 }
3953 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003954 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003955 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003956 return true;
3957}
3958
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003959bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003960 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003961 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003962 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003963 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003964 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003965 return false;
3966 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003967 return true;
3968 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003969 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003970 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
3971 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003972 return false;
3973 }
3974 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003975 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003976 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003977 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003978 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003979 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003980 return false;
3981 }
3982 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003983 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003984 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003985 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003986 return false;
3987 }
Elliott Hughes20cde902011-10-04 17:37:27 -07003988
Brian Carlstromf3632832014-05-20 15:36:53 -07003989 // Inherit kAccClassIsFinalizable from the superclass in case this
3990 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07003991 if (super->IsFinalizable()) {
3992 klass->SetFinalizable();
3993 }
3994
Elliott Hughes2da50362011-10-10 16:57:08 -07003995 // Inherit reference flags (if any) from the superclass.
3996 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
3997 if (reference_flags != 0) {
3998 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
3999 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004000 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004001 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004002 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004003 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004004 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004005 return false;
4006 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004007
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004008 if (kIsDebugBuild) {
4009 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004010 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004011 CHECK(super->IsResolved());
4012 super = super->GetSuperClass();
4013 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004014 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004015 return true;
4016}
4017
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004018// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004019bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004020 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4021 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004022 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004023 if (klass->IsInterface()) {
4024 // No vtable.
4025 size_t count = klass->NumVirtualMethods();
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004026 if (!IsUint<16>(count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004027 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004028 return false;
4029 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004030 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004031 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004032 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004033 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4034 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004035 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004036 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004037}
4038
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004039// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4040// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4041// caches in the implementation below.
4042class MethodNameAndSignatureComparator FINAL : public ValueObject {
4043 public:
4044 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4045 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4046 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4047 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004048 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4049 }
4050
4051 const char* GetName() {
4052 if (name_ == nullptr) {
4053 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4054 }
4055 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004056 }
4057
4058 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4059 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4060 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4061 const DexFile* other_dex_file = other->GetDexFile();
4062 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4063 if (dex_file_ == other_dex_file) {
4064 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4065 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004066 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004067 uint32_t other_name_len;
4068 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4069 &other_name_len);
4070 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4071 return false;
4072 }
4073 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4074 }
4075
4076 private:
4077 // Dex file for the method to compare against.
4078 const DexFile* const dex_file_;
4079 // MethodId for the method to compare against.
4080 const DexFile::MethodId* const mid_;
4081 // Lazily computed name from the dex file's strings.
4082 const char* name_;
4083 // Lazily computed name length.
4084 uint32_t name_len_;
4085};
4086
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004087class LinkVirtualHashTable {
4088 public:
4089 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4090 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4091 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4092 }
4093 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4094 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4095 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004096 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004097 uint32_t index = hash % hash_size_;
4098 // Linear probe until we have an empty slot.
4099 while (hash_table_[index] != invalid_index_) {
4100 if (++index == hash_size_) {
4101 index = 0;
4102 }
4103 }
4104 hash_table_[index] = virtual_method_index;
4105 }
4106 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4107 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4108 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004109 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004110 size_t index = hash % hash_size_;
4111 while (true) {
4112 const uint32_t value = hash_table_[index];
4113 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4114 // the block and can safely assume not found.
4115 if (value == invalid_index_) {
4116 break;
4117 }
4118 if (value != removed_index_) { // This signifies not already overriden.
4119 mirror::ArtMethod* virtual_method =
4120 klass_->GetVirtualMethodDuringLinking(value);
4121 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4122 hash_table_[index] = removed_index_;
4123 return value;
4124 }
4125 }
4126 if (++index == hash_size_) {
4127 index = 0;
4128 }
4129 }
4130 return GetNotFoundIndex();
4131 }
4132 static uint32_t GetNotFoundIndex() {
4133 return invalid_index_;
4134 }
4135
4136 private:
4137 static const uint32_t invalid_index_;
4138 static const uint32_t removed_index_;
4139
4140 Handle<mirror::Class> klass_;
4141 const size_t hash_size_;
4142 uint32_t* const hash_table_;
4143};
4144
4145const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4146const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4147
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004148bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004149 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004150 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004151 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4152 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004153 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004154 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004155 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004156 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4157 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4158 if (UNLIKELY(vtable.Get() == nullptr)) {
4159 CHECK(self->IsExceptionPending()); // OOME.
4160 return false;
4161 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004162 for (size_t i = 0; i < super_vtable_length; i++) {
4163 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004164 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004165 if (num_virtual_methods == 0) {
4166 klass->SetVTable(vtable.Get());
4167 return true;
4168 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004169 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004170 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4171 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4172 if (num_virtual_methods == 0) {
4173 klass->SetVTable(super_vtable);
4174 return true;
4175 }
4176 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004177 if (UNLIKELY(vtable.Get() == nullptr)) {
4178 CHECK(self->IsExceptionPending()); // OOME.
4179 return false;
4180 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004181 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004182 // How the algorithm works:
4183 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4184 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4185 // method which has not been matched to a vtable method, and j if the virtual method at the
4186 // index overrode the super virtual method at index j.
4187 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4188 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4189 // the need for the initial vtable which we later shrink back down).
4190 // 3. Add non overridden methods to the end of the vtable.
4191 static constexpr size_t kMaxStackHash = 250;
4192 const size_t hash_table_size = num_virtual_methods * 3;
4193 uint32_t* hash_table_ptr;
4194 std::unique_ptr<uint32_t[]> hash_heap_storage;
4195 if (hash_table_size <= kMaxStackHash) {
4196 hash_table_ptr = reinterpret_cast<uint32_t*>(
4197 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4198 } else {
4199 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4200 hash_table_ptr = hash_heap_storage.get();
4201 }
4202 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4203 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004204 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004205 hash_table.Add(i);
4206 }
4207 // Loop through each super vtable method and see if they are overriden by a method we added to
4208 // the hash table.
4209 for (size_t j = 0; j < super_vtable_length; ++j) {
4210 // Search the hash table to see if we are overidden by any method.
4211 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4212 MethodNameAndSignatureComparator super_method_name_comparator(
4213 super_method->GetInterfaceMethodIfProxy());
4214 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4215 if (hash_index != hash_table.GetNotFoundIndex()) {
4216 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4217 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4218 super_method->GetAccessFlags())) {
4219 if (super_method->IsFinal()) {
4220 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4221 PrettyMethod(virtual_method).c_str(),
4222 super_method->GetDeclaringClassDescriptor());
4223 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004224 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004225 vtable->SetWithoutChecks<false>(j, virtual_method);
4226 virtual_method->SetMethodIndex(j);
4227 } else {
4228 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004229 << " would have incorrectly overridden the package-private method in "
4230 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004231 }
4232 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004233 }
4234 // Add the non overridden methods at the end.
4235 size_t actual_count = super_vtable_length;
4236 for (size_t i = 0; i < num_virtual_methods; ++i) {
4237 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4238 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4239 if (method_idx < super_vtable_length &&
4240 local_method == vtable->GetWithoutChecks(method_idx)) {
4241 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004242 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004243 vtable->SetWithoutChecks<false>(actual_count, local_method);
4244 local_method->SetMethodIndex(actual_count);
4245 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004246 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004247 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004248 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004249 return false;
4250 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004251 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004252 CHECK_LE(actual_count, max_count);
4253 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004254 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004255 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004256 CHECK(self->IsExceptionPending()); // OOME.
4257 return false;
4258 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004259 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004260 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004261 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004262 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004263 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004264 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4265 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004266 return false;
4267 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004268 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4269 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004270 CHECK(self->IsExceptionPending()); // OOME.
4271 return false;
4272 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004273 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004274 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004275 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004276 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004277 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004278 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004279 }
4280 return true;
4281}
4282
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004283bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4284 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4285 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004286 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004287 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004288 const bool has_superclass = klass->HasSuperClass();
4289 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4290 const bool have_interfaces = interfaces.Get() != nullptr;
4291 const size_t num_interfaces =
4292 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4293 if (num_interfaces == 0) {
4294 if (super_ifcount == 0) {
4295 // Class implements no interfaces.
4296 DCHECK_EQ(klass->GetIfTableCount(), 0);
4297 DCHECK(klass->GetIfTable() == nullptr);
4298 return true;
4299 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004300 // Class implements same interfaces as parent, are any of these not marker interfaces?
4301 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004302 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004303 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004304 if (super_iftable->GetMethodArrayCount(i) > 0) {
4305 has_non_marker_interface = true;
4306 break;
4307 }
4308 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004309 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004310 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004311 klass->SetIfTable(super_iftable);
4312 return true;
4313 }
4314 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004315 size_t ifcount = super_ifcount + num_interfaces;
4316 for (size_t i = 0; i < num_interfaces; i++) {
4317 mirror::Class* interface = have_interfaces ?
4318 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4319 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004320 if (UNLIKELY(!interface->IsInterface())) {
4321 std::string temp;
4322 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4323 PrettyDescriptor(klass.Get()).c_str(),
4324 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4325 return false;
4326 }
4327 ifcount += interface->GetIfTableCount();
4328 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004329 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004330 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004331 CHECK(self->IsExceptionPending()); // OOME.
4332 return false;
4333 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004334 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004335 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004336 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004337 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004338 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004339 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004340 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004341 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004342 // Flatten the interface inheritance hierarchy.
4343 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004344 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004345 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4346 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004347 // Check if interface is already in iftable
4348 bool duplicate = false;
4349 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004350 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004351 if (existing_interface == interface) {
4352 duplicate = true;
4353 break;
4354 }
4355 }
4356 if (!duplicate) {
4357 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004358 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004359 // Add this interface's non-duplicate super-interfaces.
4360 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004361 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004362 bool super_duplicate = false;
4363 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004364 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004365 if (existing_interface == super_interface) {
4366 super_duplicate = true;
4367 break;
4368 }
4369 }
4370 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004371 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004372 }
4373 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004374 }
4375 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004376 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004377 // Shrink iftable in case duplicates were found
4378 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004379 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004380 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004381 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004382 CHECK(self->IsExceptionPending()); // OOME.
4383 return false;
4384 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004385 ifcount = idx;
4386 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004387 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004388 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004389 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004390 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004391 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004392 return true;
4393 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004394 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004395 size_t max_miranda_methods = 0; // The max size of miranda_list.
4396 for (size_t i = 0; i < ifcount; ++i) {
4397 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4398 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004399 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004400 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004401 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4402 hs.NewHandle(klass->GetVTableDuringLinking()));
4403 // Copy the IMT from the super class if possible.
4404 bool extend_super_iftable = false;
4405 if (has_superclass) {
4406 mirror::Class* super_class = klass->GetSuperClass();
4407 extend_super_iftable = true;
4408 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4409 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4410 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
4411 }
4412 } else {
4413 // No imt in the super class, need to reconstruct from the iftable.
4414 mirror::IfTable* if_table = super_class->GetIfTable();
4415 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4416 const size_t length = super_class->GetIfTableCount();
4417 for (size_t i = 0; i < length; ++i) {
4418 mirror::Class* interface = iftable->GetInterface(i);
4419 const size_t num_virtuals = interface->NumVirtualMethods();
4420 const size_t method_array_count = if_table->GetMethodArrayCount(i);
4421 DCHECK_EQ(num_virtuals, method_array_count);
4422 if (method_array_count == 0) {
4423 continue;
4424 }
4425 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
4426 for (size_t j = 0; j < num_virtuals; ++j) {
4427 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
4428 if (method->IsMiranda()) {
4429 continue;
4430 }
4431 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
4432 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4433 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4434 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4435 out_imt->SetReference(imt_index, method);
4436 } else if (imt_ref != conflict_method) {
4437 out_imt->SetReference(imt_index, conflict_method);
4438 }
4439 }
4440 }
4441 }
4442 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004443 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004444 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004445 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004446 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004447 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004448 const bool is_super = i < super_ifcount;
4449 const bool super_interface = is_super && extend_super_iftable;
4450 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
4451 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
4452 if (super_interface) {
4453 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
4454 DCHECK(if_table != nullptr);
4455 DCHECK(if_table->GetMethodArray(i) != nullptr);
4456 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004457 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004458 AsObjectArray<mirror::ArtMethod>());
4459 // We are overwriting a super class interface, try to only virtual methods instead of the
4460 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004461 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004462 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004463 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004464 // A new interface, we need the whole vtable incase a new interface method is implemented
4465 // in the whole superclass.
4466 input_array = vtable;
4467 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004468 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004469 CHECK(self->IsExceptionPending()); // OOME.
4470 return false;
4471 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004472 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004473 if (input_array.Get() == nullptr) {
4474 // If the added virtual methods is empty, do nothing.
4475 DCHECK(super_interface);
4476 continue;
4477 }
Ian Rogers62d6c772013-02-27 08:32:07 -08004478 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004479 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004480 MethodNameAndSignatureComparator interface_name_comparator(
4481 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07004482 int32_t k;
4483 // For each method listed in the interface's method list, find the
4484 // matching method in our class's method list. We want to favor the
4485 // subclass over the superclass, which just requires walking
4486 // back from the end of the vtable. (This only matters if the
4487 // superclass defines a private method and this class redefines
4488 // it -- otherwise it would use the same vtable slot. In .dex files
4489 // those don't end up in the virtual method table, so it shouldn't
4490 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004491 for (k = input_array->GetLength() - 1; k >= 0; --k) {
4492 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004493 mirror::ArtMethod* vtable_method_for_name_comparison =
4494 vtable_method->GetInterfaceMethodIfProxy();
4495 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004496 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004497 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004498 ThrowIllegalAccessError(
4499 klass.Get(),
4500 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004501 PrettyMethod(vtable_method).c_str(),
4502 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004503 return false;
4504 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004505 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004506 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004507 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4508 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4509 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4510 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4511 out_imt->SetReference(imt_index, vtable_method);
4512 } else if (imt_ref != conflict_method) {
4513 // If we are not a conflict and we have the same signature and name as the imt entry,
4514 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004515 MethodNameAndSignatureComparator imt_ref_name_comparator(
4516 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004517 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004518 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004519 out_imt->SetReference(imt_index, vtable_method);
4520 } else {
4521 out_imt->SetReference(imt_index, conflict_method);
4522 }
Jeff Hao88474b42013-10-23 16:24:40 -07004523 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004524 break;
4525 }
4526 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004527 if (k < 0 && !super_interface) {
4528 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004529 for (size_t l = 0; l < miranda_list_size; ++l) {
4530 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004531 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004532 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07004533 break;
4534 }
4535 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004536 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004537 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004538 miranda_method = interface_method->Clone(self)->AsArtMethod();
4539 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004540 CHECK(self->IsExceptionPending()); // OOME.
4541 return false;
4542 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004543 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004544 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004545 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004546 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004547 }
4548 }
4549 }
4550 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004551 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004552 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004553 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004554 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4555 if (old_method_count == 0) {
4556 virtuals = AllocArtMethodArray(self, new_method_count);
4557 } else {
4558 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4559 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004560 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004561 CHECK(self->IsExceptionPending()); // OOME.
4562 return false;
4563 }
4564 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004565
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004566 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004567 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004568 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004569 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004570 CHECK(self->IsExceptionPending()); // OOME.
4571 return false;
4572 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004573 for (size_t i = 0; i < miranda_list_size; ++i) {
4574 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004575 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004576 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4577 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4578 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004579 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004580 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004581 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004582 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004583 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004584
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004585 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004586 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
4587 for (int i = 0; i < check_vtable->GetLength(); ++i) {
4588 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004589 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004590 }
4591
Ian Rogers7b078e82014-09-10 14:44:24 -07004592 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004593 return true;
4594}
4595
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004596bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004597 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004598 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004599}
4600
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004601bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004602 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004603 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004604}
4605
Brian Carlstromdbc05252011-09-09 01:59:59 -07004606struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004607 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4608 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004609 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07004610 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004611 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07004612 // 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 -07004613 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4614 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004615 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00004616 if (type1 == Primitive::kPrimNot) {
4617 // Reference always goes first.
4618 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08004619 }
Vladimir Markod5777482014-11-12 17:02:02 +00004620 if (type2 == Primitive::kPrimNot) {
4621 // Reference always goes first.
4622 return false;
4623 }
4624 size_t size1 = Primitive::ComponentSize(type1);
4625 size_t size2 = Primitive::ComponentSize(type2);
4626 if (size1 != size2) {
4627 // Larger primitive types go first.
4628 return size1 > size2;
4629 }
4630 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
4631 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004632 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004633 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
4634 // by name and for equal names by type id index.
4635 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
4636 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07004637 }
4638};
4639
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004640bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07004641 size_t* class_size) {
4642 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004643 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
4644 ArtField* const fields = is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004645
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004646 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07004647 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004648 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00004649 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004650 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004651 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004652 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004653 CHECK(super_class->IsResolved())
4654 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004655 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004656 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004657 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004658
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004659 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004660
Brian Carlstromdbc05252011-09-09 01:59:59 -07004661 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07004662 // minimizes disruption of C++ version such as Class and Method.
Mathieu Chartierc7853442015-03-27 14:35:38 -07004663 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07004664 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07004665 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07004666 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004667 grouped_and_sorted_fields.push_back(&fields[i]);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004668 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004669 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4670 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004671
Fred Shih381e4ca2014-08-25 17:24:27 -07004672 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07004673 size_t current_field = 0;
4674 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07004675 FieldGaps gaps;
4676
Brian Carlstromdbc05252011-09-09 01:59:59 -07004677 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004678 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004679 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004680 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004681 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004682 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004683 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004684 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
4685 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07004686 MemberOffset old_offset = field_offset;
4687 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
4688 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
4689 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004690 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07004691 grouped_and_sorted_fields.pop_front();
4692 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004693 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00004694 field_offset = MemberOffset(field_offset.Uint32Value() +
4695 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004696 }
Fred Shih381e4ca2014-08-25 17:24:27 -07004697 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
4698 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00004699 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4700 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4701 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4702 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07004703 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
4704 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07004705 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004706
Elliott Hughesadb460d2011-10-05 17:02:34 -07004707 // 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 -07004708 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07004709 // We know there are no non-reference fields in the Reference classes, and we know
4710 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07004711 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07004712 CHECK_STREQ(fields[num_fields - 1].GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07004713 --num_reference_fields;
4714 }
4715
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004716 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004717 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004718 if (is_static) {
4719 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004720 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004721 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004722 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004723 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08004724 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
Jeff Haoc7d11882015-02-03 15:08:39 -08004725 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
4726 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartier2d721012014-11-10 11:08:06 -08004727 } else {
4728 std::string temp;
4729 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
4730 size_t previous_size = klass->GetObjectSize();
4731 if (previous_size != 0) {
4732 // Make sure that we didn't originally have an incorrect size.
4733 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
4734 }
4735 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004736 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004737 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004738 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004739
4740 if (kIsDebugBuild) {
4741 // Make sure that the fields array is ordered by name but all reference
4742 // offsets are at the beginning as far as alignment allows.
4743 MemberOffset start_ref_offset = is_static
4744 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
4745 : klass->GetFirstReferenceInstanceFieldOffset();
4746 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
4747 num_reference_fields *
4748 sizeof(mirror::HeapReference<mirror::Object>));
4749 MemberOffset current_ref_offset = start_ref_offset;
4750 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004751 ArtField* field = &fields[i];
4752 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
4753 << " class=" << PrettyClass(klass.Get()) << " field=" << PrettyField(field) << " offset="
4754 << field->GetOffset();
Vladimir Marko76649e82014-11-10 18:32:59 +00004755 if (i != 0) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004756 ArtField* const prev_field = &fields[i - 1];
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004757 // NOTE: The field names can be the same. This is not possible in the Java language
4758 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
4759 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00004760 }
4761 Primitive::Type type = field->GetTypeAsPrimitiveType();
4762 bool is_primitive = type != Primitive::kPrimNot;
4763 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
4764 strcmp("referent", field->GetName()) == 0) {
4765 is_primitive = true; // We lied above, so we have to expect a lie here.
4766 }
4767 MemberOffset offset = field->GetOffsetDuringLinking();
4768 if (is_primitive) {
4769 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
4770 // Shuffled before references.
4771 size_t type_size = Primitive::ComponentSize(type);
4772 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
4773 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
4774 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
4775 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
4776 }
4777 } else {
4778 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
4779 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
4780 sizeof(mirror::HeapReference<mirror::Object>));
4781 }
4782 }
4783 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
4784 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004785 return true;
4786}
4787
Vladimir Marko76649e82014-11-10 18:32:59 +00004788// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004789void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004790 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004791 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004792 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004793 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004794 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004795 // Compute reference offsets unless our superclass overflowed.
4796 if (reference_offsets != mirror::Class::kClassWalkSuper) {
4797 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00004798 if (num_reference_fields != 0u) {
4799 // All of the fields that contain object references are guaranteed be grouped in memory
4800 // starting at an appropriately aligned address after super class object data.
4801 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
4802 sizeof(mirror::HeapReference<mirror::Object>));
4803 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004804 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00004805 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004806 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004807 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00004808 reference_offsets |= (0xffffffffu << start_bit) &
4809 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004810 }
4811 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07004812 }
4813 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07004814 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004815}
4816
Mathieu Chartier590fee92013-09-13 13:46:47 -07004817mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004818 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004819 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004820 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004821 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004822 return resolved;
4823 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07004824 uint32_t utf16_length;
4825 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004826 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004827 dex_cache->SetResolvedString(string_idx, string);
4828 return string;
4829}
4830
Mathieu Chartier590fee92013-09-13 13:46:47 -07004831mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08004832 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004833 StackHandleScope<2> hs(Thread::Current());
4834 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
4835 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07004836 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
4837}
4838
4839mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004840 Handle<mirror::DexCache> dex_cache,
4841 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004842 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004843 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004844 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08004845 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07004846 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08004847 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004848 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05004849 // TODO: we used to throw here if resolved's class loader was not the
4850 // boot class loader. This was to permit different classes with the
4851 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004852 dex_cache->SetResolvedType(type_idx, resolved);
4853 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004854 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08004855 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08004856 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004857 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004858 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004859 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004860 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08004861 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08004862 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004863 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08004864 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004865 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004866 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004867 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07004868 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004869 return resolved;
4870}
4871
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004872mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004873 Handle<mirror::DexCache> dex_cache,
4874 Handle<mirror::ClassLoader> class_loader,
4875 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07004876 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004877 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07004878 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07004879 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004880 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004881 return resolved;
4882 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004883 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004884 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004885 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004886 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07004887 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004888 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004889 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004890 // Scan using method_idx, this saves string compares but will only hit for matching dex
4891 // caches/files.
4892 switch (type) {
4893 case kDirect: // Fall-through.
4894 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004895 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004896 break;
4897 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004898 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004899 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004900 break;
4901 case kSuper: // Fall-through.
4902 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004903 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004904 break;
4905 default:
4906 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07004907 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004908 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004909 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004910 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004911 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07004912 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07004913 switch (type) {
4914 case kDirect: // Fall-through.
4915 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08004916 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004917 break;
4918 case kInterface:
4919 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004920 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004921 break;
4922 case kSuper: // Fall-through.
4923 case kVirtual:
4924 resolved = klass->FindVirtualMethod(name, signature);
4925 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004926 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004927 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004928 // If we found a method, check for incompatible class changes.
4929 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004930 // Be a good citizen and update the dex cache to speed subsequent calls.
4931 dex_cache->SetResolvedMethod(method_idx, resolved);
4932 return resolved;
4933 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004934 // If we had a method, it's an incompatible-class-change error.
4935 if (resolved != nullptr) {
4936 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
4937 } else {
4938 // We failed to find the method which means either an access error, an incompatible class
4939 // change, or no such method. First try to find the method among direct and virtual methods.
4940 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
4941 const Signature signature = dex_file.GetMethodSignature(method_id);
4942 switch (type) {
4943 case kDirect:
4944 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07004945 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004946 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
4947 // have had a resolved method before, which triggers the "true" branch above.
4948 break;
4949 case kInterface:
4950 case kVirtual:
4951 case kSuper:
4952 resolved = klass->FindDirectMethod(name, signature);
4953 break;
4954 }
4955
4956 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08004957 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004958 if (resolved != nullptr && referrer.Get() != nullptr) {
4959 mirror::Class* methods_class = resolved->GetDeclaringClass();
4960 mirror::Class* referring_class = referrer->GetDeclaringClass();
4961 if (!referring_class->CanAccess(methods_class)) {
4962 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
4963 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004964 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004965 } else if (!referring_class->CanAccessMember(methods_class,
4966 resolved->GetAccessFlags())) {
4967 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004968 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004969 }
4970 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004971 if (!exception_generated) {
4972 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
4973 // interface methods and throw if we find the method there. If we find nothing, throw a
4974 // NoSuchMethodError.
4975 switch (type) {
4976 case kDirect:
4977 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004978 if (resolved != nullptr) {
4979 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4980 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004981 resolved = klass->FindInterfaceMethod(name, signature);
4982 if (resolved != nullptr) {
4983 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4984 } else {
4985 ThrowNoSuchMethodError(type, klass, name, signature);
4986 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004987 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004988 break;
4989 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004990 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004991 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
4992 } else {
4993 resolved = klass->FindVirtualMethod(name, signature);
4994 if (resolved != nullptr) {
4995 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4996 } else {
4997 ThrowNoSuchMethodError(type, klass, name, signature);
4998 }
4999 }
5000 break;
5001 case kSuper:
5002 if (resolved != nullptr) {
5003 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005004 } else {
5005 ThrowNoSuchMethodError(type, klass, name, signature);
5006 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005007 break;
5008 case kVirtual:
5009 if (resolved != nullptr) {
5010 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5011 } else {
5012 resolved = klass->FindInterfaceMethod(name, signature);
5013 if (resolved != nullptr) {
5014 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5015 } else {
5016 ThrowNoSuchMethodError(type, klass, name, signature);
5017 }
5018 }
5019 break;
5020 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005021 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005022 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005023 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005024 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005025 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005026}
5027
Mathieu Chartierc7853442015-03-27 14:35:38 -07005028ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
5029 Handle<mirror::DexCache> dex_cache,
5030 Handle<mirror::ClassLoader> class_loader, bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005031 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005032 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005033 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005034 return resolved;
5035 }
5036 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005037 Thread* const self = Thread::Current();
5038 StackHandleScope<1> hs(self);
5039 Handle<mirror::Class> klass(
5040 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005041 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005042 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005043 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005044 }
5045
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005046 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005047 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005048 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005049 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005050 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005051
Andreas Gampe58a5af82014-07-31 16:23:49 -07005052 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005053 const char* name = dex_file.GetFieldName(field_id);
5054 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5055 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005056 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005057 } else {
5058 resolved = klass->FindInstanceField(name, type);
5059 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005060 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005061 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005062 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005063 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005064 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07005065 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08005066 return resolved;
5067}
5068
Mathieu Chartierc7853442015-03-27 14:35:38 -07005069ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file, uint32_t field_idx,
5070 Handle<mirror::DexCache> dex_cache,
5071 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005072 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005073 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005074 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005075 return resolved;
5076 }
5077 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005078 Thread* self = Thread::Current();
5079 StackHandleScope<1> hs(self);
5080 Handle<mirror::Class> klass(
5081 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005082 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005083 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005084 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005085 }
5086
Ian Rogersdfb325e2013-10-30 01:00:44 -07005087 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5088 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005089 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005090 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005091 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005092 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08005093 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005094 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005095 }
5096 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005097}
5098
Brian Carlstromea46f952013-07-30 01:26:50 -07005099const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005100 uint32_t* length) {
5101 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5102 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005103 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005104 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005105 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005106}
5107
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005108void ClassLinker::DumpAllClasses(int flags) {
5109 if (dex_cache_image_class_lookup_required_) {
5110 MoveImageClassesToClassTable();
5111 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005112 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5113 // 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 -08005114 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005115 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005116 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005117 for (GcRoot<mirror::Class>& it : class_table_) {
5118 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005119 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005120 }
5121
5122 for (size_t i = 0; i < all_classes.size(); ++i) {
5123 all_classes[i]->DumpClass(std::cerr, flags);
5124 }
5125}
5126
Elliott Hughes956af0f2014-12-11 14:34:28 -08005127static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005128 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005129 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5130 base -= sizeof(void*); // Move backward so that code_offset != 0.
5131 const uint32_t code_offset = sizeof(void*);
5132 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005133}
5134
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005135bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5136 return (entry_point == GetQuickResolutionStub()) ||
5137 (quick_resolution_trampoline_ == entry_point);
5138}
5139
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005140bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5141 return (entry_point == GetQuickToInterpreterBridge()) ||
5142 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5143}
5144
5145bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5146 return (entry_point == GetQuickGenericJniStub()) ||
5147 (quick_generic_jni_trampoline_ == entry_point);
5148}
5149
5150const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5151 return GetQuickGenericJniStub();
5152}
5153
Elliott Hughes956af0f2014-12-11 14:34:28 -08005154void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5155 const void* method_code) const {
5156 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005157 oat_method.LinkMethod(method);
5158 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005159}
5160
5161void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5162 if (!method->IsNative()) {
5163 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005164 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5165 } else {
5166 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005167 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005168 oat_method.LinkMethod(method);
5169 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005170 }
5171}
5172
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005173void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005174 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005175 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005176 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005177 MoveImageClassesToClassTable();
5178 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005179 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005180 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5181 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005182}
5183
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005184size_t ClassLinker::NumLoadedClasses() {
5185 if (dex_cache_image_class_lookup_required_) {
5186 MoveImageClassesToClassTable();
5187 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005188 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005189 // Only return non zygote classes since these are the ones which apps which care about.
5190 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005191}
5192
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005193pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005194 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005195}
5196
5197pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005198 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005199}
5200
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005201void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005202 DCHECK(!init_done_);
5203
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005204 DCHECK(klass != nullptr);
5205 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005206
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005207 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005208 DCHECK(class_roots != nullptr);
5209 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005210 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005211}
5212
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005213const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5214 static const char* class_roots_descriptors[] = {
5215 "Ljava/lang/Class;",
5216 "Ljava/lang/Object;",
5217 "[Ljava/lang/Class;",
5218 "[Ljava/lang/Object;",
5219 "Ljava/lang/String;",
5220 "Ljava/lang/DexCache;",
5221 "Ljava/lang/ref/Reference;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005222 "Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005223 "Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005224 "Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005225 "Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005226 "Ljava/lang/reflect/Proxy;",
5227 "[Ljava/lang/String;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005228 "[Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005229 "[Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005230 "[Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005231 "[Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005232 "Ljava/lang/ClassLoader;",
5233 "Ljava/lang/Throwable;",
5234 "Ljava/lang/ClassNotFoundException;",
5235 "Ljava/lang/StackTraceElement;",
5236 "Z",
5237 "B",
5238 "C",
5239 "D",
5240 "F",
5241 "I",
5242 "J",
5243 "S",
5244 "V",
5245 "[Z",
5246 "[B",
5247 "[C",
5248 "[D",
5249 "[F",
5250 "[I",
5251 "[J",
5252 "[S",
5253 "[Ljava/lang/StackTraceElement;",
5254 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005255 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5256 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005257
5258 const char* descriptor = class_roots_descriptors[class_root];
5259 CHECK(descriptor != nullptr);
5260 return descriptor;
5261}
5262
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005263std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5264 const {
5265 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005266 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005267}
5268
5269bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005270 const GcRoot<mirror::Class>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005271 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5272 return false;
5273 }
5274 std::string temp;
5275 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5276}
5277
5278std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5279 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005280 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005281}
5282
5283bool ClassLinker::ClassDescriptorHashEquals::operator()(
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005284 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005285 if (a.Read()->GetClassLoader() != b.second) {
5286 return false;
5287 }
5288 return a.Read()->DescriptorEquals(b.first);
5289}
5290
5291bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005292 const char* descriptor) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005293 return a.Read()->DescriptorEquals(descriptor);
5294}
5295
5296std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005297 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005298}
5299
Sebastien Hertz6963e442014-11-26 22:11:27 +01005300bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07005301 if (Runtime::Current()->UseJit()) {
5302 // JIT can have direct code pointers from any method to any other method.
5303 return true;
5304 }
Sebastien Hertz6963e442014-11-26 22:11:27 +01005305 // Non-image methods don't use direct code pointer.
5306 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
5307 return false;
5308 }
5309 if (m->IsPrivate()) {
5310 // The method can only be called inside its own oat file. Therefore it won't be called using
5311 // its direct code if the oat file has been compiled in PIC mode.
Sebastien Hertz6963e442014-11-26 22:11:27 +01005312 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
Richard Uhler07b3c232015-03-31 15:57:54 -07005313 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Sebastien Hertz6963e442014-11-26 22:11:27 +01005314 if (oat_dex_file == nullptr) {
5315 // No oat file: the method has not been compiled.
5316 return false;
5317 }
5318 const OatFile* oat_file = oat_dex_file->GetOatFile();
5319 return oat_file != nullptr && !oat_file->IsPic();
5320 } else {
5321 // The method can be called outside its own oat file. Therefore it won't be called using its
5322 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
5323 ReaderMutexLock mu(Thread::Current(), dex_lock_);
5324 for (const OatFile* oat_file : oat_files_) {
5325 if (!oat_file->IsPic()) {
5326 return true;
5327 }
5328 }
5329 return false;
5330 }
5331}
5332
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005333jobject ClassLinker::CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files) {
5334 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
5335 // We could move the jobject to the callers, but all call-sites do this...
5336 ScopedObjectAccessUnchecked soa(self);
5337
5338 // Register the dex files.
5339 for (const DexFile* dex_file : dex_files) {
5340 RegisterDexFile(*dex_file);
5341 }
5342
5343 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005344 StackHandleScope<10> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005345
Mathieu Chartierc7853442015-03-27 14:35:38 -07005346 ArtField* dex_elements_field =
5347 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005348
Mathieu Chartierc7853442015-03-27 14:35:38 -07005349 mirror::Class* dex_elements_class = dex_elements_field->GetType<true>();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005350 DCHECK(dex_elements_class != nullptr);
5351 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005352 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
5353 mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005354 Handle<mirror::Class> h_dex_element_class =
5355 hs.NewHandle(dex_elements_class->GetComponentType());
5356
Mathieu Chartierc7853442015-03-27 14:35:38 -07005357 ArtField* element_file_field =
5358 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
5359 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005360
Mathieu Chartierc7853442015-03-27 14:35:38 -07005361 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
5362 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005363
5364 // Fill the elements array.
5365 int32_t index = 0;
5366 for (const DexFile* dex_file : dex_files) {
5367 StackHandleScope<3> hs2(self);
5368
5369 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(self, 1));
5370 DCHECK(h_long_array.Get() != nullptr);
5371 h_long_array->Set(0, reinterpret_cast<intptr_t>(dex_file));
5372
5373 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07005374 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005375 DCHECK(h_dex_file.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005376 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005377
5378 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
5379 DCHECK(h_element.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005380 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005381
5382 h_dex_elements->Set(index, h_element.Get());
5383 index++;
5384 }
5385 DCHECK_EQ(index, h_dex_elements->GetLength());
5386
5387 // Create DexPathList.
5388 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07005389 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005390 DCHECK(h_dex_path_list.Get() != nullptr);
5391 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005392 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005393
5394 // Create PathClassLoader.
5395 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
5396 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
5397 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
5398 h_path_class_class->AllocObject(self));
5399 DCHECK(h_path_class_loader.Get() != nullptr);
5400 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005401 ArtField* path_list_field =
5402 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList);
5403 DCHECK(path_list_field != nullptr);
5404 path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005405
5406 // Make a pretend boot-classpath.
5407 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07005408 ArtField* const parent_field =
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005409 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07005410 "Ljava/lang/ClassLoader;");
5411 DCHECK(parent_field!= nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005412 mirror::Object* boot_cl =
5413 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005414 parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005415
5416 // Make it a global ref and return.
5417 ScopedLocalRef<jobject> local_ref(
5418 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
5419 return soa.Env()->NewGlobalRef(local_ref.get());
5420}
5421
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005422} // namespace art