blob: dc8bf2ac5ee4d8ad139f60bf041af1dfb5571377 [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
Andreas Gampebfdcdc12015-04-22 18:10:36 -070095static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Ian Rogersb726dcb2012-09-05 08:57:23 -070096 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampebfdcdc12015-04-22 18:10:36 -070097 mirror::ArtMethod* method = self->GetCurrentMethod(nullptr);
98 StackHandleScope<1> hs(self);
99 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
100 method->GetDeclaringClass()->GetClassLoader()
101 : nullptr));
102 mirror::Class* exception_class = class_linker->FindClass(self, descriptor, class_loader);
103
104 if (exception_class == nullptr) {
105 // No exc class ~ no <init>-with-string.
106 CHECK(self->IsExceptionPending());
107 self->ClearException();
108 return false;
109 }
110
111 mirror::ArtMethod* exception_init_method =
112 exception_class->FindDeclaredDirectMethod("<init>", "(Ljava/lang/String;)V");
113 return exception_init_method != nullptr;
114}
115
116void ClassLinker::ThrowEarlierClassFailure(mirror::Class* c) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700117 // The class failed to initialize on a previous attempt, so we want to throw
118 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
119 // failed in verification, in which case v2 5.4.1 says we need to re-throw
120 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800121 Runtime* const runtime = Runtime::Current();
122 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -0700123 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
124 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700125
Elliott Hughes5c599942012-06-13 16:45:05 -0700126 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800127 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800128 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700129 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
130 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000131 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700132 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700133 if (c->GetVerifyErrorClass() != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700134 // TODO: change the verifier to store an _instance_, with a useful detail message?
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700135 // It's possible the exception doesn't have a <init>(String).
Ian Rogers7b078e82014-09-10 14:44:24 -0700136 std::string temp;
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700137 const char* descriptor = c->GetVerifyErrorClass()->GetDescriptor(&temp);
138
139 if (HasInitWithString(self, this, descriptor)) {
140 self->ThrowNewException(descriptor, PrettyDescriptor(c).c_str());
141 } else {
142 self->ThrowNewException(descriptor, nullptr);
143 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700144 } else {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000145 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
Ian Rogers7b078e82014-09-10 14:44:24 -0700146 PrettyDescriptor(c).c_str());
147 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700148 }
149}
150
Brian Carlstromb23eab12014-10-08 17:55:21 -0700151static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
152 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
153 if (VLOG_IS_ON(class_linker)) {
154 std::string temp;
155 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000156 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700157 }
158}
159
160static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
161 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700162 Thread* self = Thread::Current();
163 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700164
165 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700166 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700167
168 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700169 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
170 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700171
Elliott Hughesa4f94742012-05-29 16:28:38 -0700172 // We only wrap non-Error exceptions; an Error can just be used as-is.
173 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000174 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700175 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700176 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700177}
178
Fred Shih381e4ca2014-08-25 17:24:27 -0700179// Gap between two fields in object layout.
180struct FieldGap {
181 uint32_t start_offset; // The offset from the start of the object.
182 uint32_t size; // The gap size of 1, 2, or 4 bytes.
183};
184struct FieldGapsComparator {
185 explicit FieldGapsComparator() {
186 }
187 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
188 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800189 // Sort by gap size, largest first. Secondary sort by starting offset.
190 return lhs.size > rhs.size || (lhs.size == rhs.size && lhs.start_offset < rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700191 }
192};
193typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
194
195// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800196static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700197 DCHECK(gaps != nullptr);
198
199 uint32_t current_offset = gap_start;
200 while (current_offset != gap_end) {
201 size_t remaining = gap_end - current_offset;
202 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
203 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
204 current_offset += sizeof(uint32_t);
205 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
206 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
207 current_offset += sizeof(uint16_t);
208 } else {
209 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
210 current_offset += sizeof(uint8_t);
211 }
212 DCHECK_LE(current_offset, gap_end) << "Overran gap";
213 }
214}
215// Shuffle fields forward, making use of gaps whenever possible.
216template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000217static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700218 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700219 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700220 FieldGaps* gaps)
221 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
222 DCHECK(current_field_idx != nullptr);
223 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700224 DCHECK(gaps != nullptr);
225 DCHECK(field_offset != nullptr);
226
227 DCHECK(IsPowerOfTwo(n));
228 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700229 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700230 Primitive::Type type = field->GetTypeAsPrimitiveType();
231 if (Primitive::ComponentSize(type) < n) {
232 break;
233 }
234 if (!IsAligned<n>(field_offset->Uint32Value())) {
235 MemberOffset old_offset = *field_offset;
236 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
237 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
238 }
239 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
240 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700241 if (!gaps->empty() && gaps->top().size >= n) {
242 FieldGap gap = gaps->top();
243 gaps->pop();
244 DCHECK(IsAligned<n>(gap.start_offset));
245 field->SetOffset(MemberOffset(gap.start_offset));
246 if (gap.size > n) {
247 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
248 }
249 } else {
250 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
251 field->SetOffset(*field_offset);
252 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
253 }
254 ++(*current_field_idx);
255 }
256}
257
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800258ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700259 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700260 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700261 dex_cache_image_class_lookup_required_(false),
262 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800263 class_roots_(nullptr),
264 array_iftable_(nullptr),
265 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700266 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800267 log_new_dex_caches_roots_(false),
268 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700269 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800270 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800271 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100272 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800273 quick_to_interpreter_bridge_trampoline_(nullptr),
274 image_pointer_size_(sizeof(void*)) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700275 CHECK(intern_table_ != nullptr);
276 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
277 find_array_class_cache_[i] = GcRoot<mirror::Class>(nullptr);
278 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700279}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700280
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800281void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800282 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700283 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700284
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700285 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700286
Elliott Hughes30646832011-10-13 16:59:46 -0700287 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700288 Thread* const self = Thread::Current();
289 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700290 // 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 -0800291 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700292 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
293 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700294 heap->AllocNonMovableObject<true>(self, nullptr,
295 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700296 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700297 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700298 mirror::Class::SetClassClass(java_lang_Class.Get());
299 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700300 if (kUseBakerOrBrooksReadBarrier) {
301 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800302 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700303 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700304 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800305 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800306 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700307
Elliott Hughes418d20f2011-09-22 14:00:39 -0700308 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700309 Handle<mirror::Class> class_array_class(hs.NewHandle(
310 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700311 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700312
Ian Rogers23435d02012-09-24 11:23:12 -0700313 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700314 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
315 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700316 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700317 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700318 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700319 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700320
Ian Rogers23435d02012-09-24 11:23:12 -0700321 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700322 Handle<mirror::Class> object_array_class(hs.NewHandle(
323 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700324 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700325
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700326 // Setup the char (primitive) class to be used for char[].
327 Handle<mirror::Class> char_class(hs.NewHandle(
328 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700329 // The primitive char class won't be initialized by
330 // InitializePrimitiveClass until line 459, but strings (and
331 // internal char arrays) will be allocated before that and the
332 // component size, which is computed from the primitive type, needs
333 // to be set here.
334 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700335
Ian Rogers23435d02012-09-24 11:23:12 -0700336 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700337 Handle<mirror::Class> char_array_class(hs.NewHandle(
338 AllocClass(self, java_lang_Class.Get(),
339 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700340 char_array_class->SetComponentType(char_class.Get());
341 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700342
Ian Rogers23435d02012-09-24 11:23:12 -0700343 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700344 Handle<mirror::Class> java_lang_String(hs.NewHandle(
345 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700346 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700347 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700348 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400349
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700350 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700351 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
352 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
353 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
354 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700355 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700356
Ian Rogers23435d02012-09-24 11:23:12 -0700357 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700358 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700359 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
360 kClassRootsMax));
361 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700362 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
363 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
364 SetClassRoot(kClassArrayClass, class_array_class.Get());
365 SetClassRoot(kObjectArrayClass, object_array_class.Get());
366 SetClassRoot(kCharArrayClass, char_array_class.Get());
367 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700368 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700369
370 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700371 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
372 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
373 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
374 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
375 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
376 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
377 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
378 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700379
Ian Rogers23435d02012-09-24 11:23:12 -0700380 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700381 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700382
Ian Rogers23435d02012-09-24 11:23:12 -0700383 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700384 Handle<mirror::Class> int_array_class(hs.NewHandle(
385 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700386 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700387 mirror::IntArray::SetArrayClass(int_array_class.Get());
388 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700389
Mathieu Chartierc7853442015-03-27 14:35:38 -0700390 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
391 Handle<mirror::Class> long_array_class(hs.NewHandle(
392 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
393 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
394 mirror::LongArray::SetArrayClass(long_array_class.Get());
395 SetClassRoot(kLongArrayClass, long_array_class.Get());
396
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700397 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700398
Ian Rogers52813c92012-10-11 11:50:38 -0700399 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700400 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
401 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700402 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700403 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700404 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700405
Mathieu Chartierc7853442015-03-27 14:35:38 -0700406 // Constructor, Method, and AbstractMethod are necessary so
Brian Carlstromf3632832014-05-20 15:36:53 -0700407 // that FindClass can link members.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700408
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700409 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
410 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700411 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800412 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
413 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700414 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700415 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700416 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700417
418 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700419 Handle<mirror::Class> object_array_string(hs.NewHandle(
420 AllocClass(self, java_lang_Class.Get(),
421 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700422 object_array_string->SetComponentType(java_lang_String.Get());
423 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700424
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700425 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
426 AllocClass(self, java_lang_Class.Get(),
427 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700428 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
429 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700430
Ian Rogers23435d02012-09-24 11:23:12 -0700431 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
432 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
433 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700434 CHECK_NE(0U, boot_class_path.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800435 for (auto& dex_file : boot_class_path) {
436 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700437 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800438 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700439 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700440
441 // now we can use FindSystemClass
442
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700443 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700444 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
445 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700446
Jeff Hao88474b42013-10-23 16:24:40 -0700447 // Create runtime resolution and imt conflict methods. Also setup the default imt.
448 Runtime* runtime = Runtime::Current();
449 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
450 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700451 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700452 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
453
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700454 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
455 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700456 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800457 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700458 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700459 quick_resolution_trampoline_ = GetQuickResolutionStub();
460 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
461 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700462 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700463
Mathieu Chartier66f19252012-09-18 08:57:04 -0700464 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700465 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700466 CHECK_EQ(java_lang_Object.Get(), FindSystemClass(self, "Ljava/lang/Object;"));
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700467 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700468 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800469 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700470 if (java_lang_String.Get() != String_class) {
471 std::ostringstream os1, os2;
472 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
473 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
474 LOG(FATAL) << os1.str() << "\n\n" << os2.str();
475 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700476 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700477 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700478 CHECK_EQ(java_lang_DexCache.Get(), FindSystemClass(self, "Ljava/lang/DexCache;"));
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700479 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700480
Ian Rogers23435d02012-09-24 11:23:12 -0700481 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800482 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800483 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700484
Ian Rogers98379392014-02-24 16:53:16 -0800485 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800486 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700487
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700488 CHECK_EQ(char_array_class.Get(), FindSystemClass(self, "[C"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700489
Ian Rogers98379392014-02-24 16:53:16 -0800490 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800491 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700492
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700493 CHECK_EQ(int_array_class.Get(), FindSystemClass(self, "[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700494
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700495 CHECK_EQ(long_array_class.Get(), FindSystemClass(self, "[J"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700496
Ian Rogers98379392014-02-24 16:53:16 -0800497 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800498 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700499
Ian Rogers98379392014-02-24 16:53:16 -0800500 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800501 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700502
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700503 CHECK_EQ(class_array_class.Get(), FindSystemClass(self, "[Ljava/lang/Class;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700504
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700505 CHECK_EQ(object_array_class.Get(), FindSystemClass(self, "[Ljava/lang/Object;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700506
Ian Rogers23435d02012-09-24 11:23:12 -0700507 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700508 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
509 CHECK(java_lang_Cloneable.Get() != nullptr);
510 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
511 CHECK(java_io_Serializable.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700512 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
513 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700514 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
515 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700516
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700517 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
518 // suspension.
519 CHECK_EQ(java_lang_Cloneable.Get(),
520 mirror::Class::GetDirectInterface(self, class_array_class, 0));
521 CHECK_EQ(java_io_Serializable.Get(),
522 mirror::Class::GetDirectInterface(self, class_array_class, 1));
523 CHECK_EQ(java_lang_Cloneable.Get(),
524 mirror::Class::GetDirectInterface(self, object_array_class, 0));
525 CHECK_EQ(java_io_Serializable.Get(),
526 mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700527 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700528 // dex_cache_ fields and register them in class_table_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700529 CHECK_EQ(java_lang_Class.Get(), FindSystemClass(self, "Ljava/lang/Class;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700530
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700531 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700532 CHECK_EQ(java_lang_reflect_ArtMethod.Get(),
533 FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;"));
534 CHECK_EQ(object_array_string.Get(),
535 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
536 CHECK_EQ(object_array_art_method.Get(),
537 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700538
Ian Rogers23435d02012-09-24 11:23:12 -0700539 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700540
Ian Rogers23435d02012-09-24 11:23:12 -0700541 // Create java.lang.reflect.Proxy root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700542 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700543
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700544 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700545 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
546 CHECK(class_root != nullptr);
547 SetClassRoot(kJavaLangReflectField, class_root);
548 mirror::Field::SetClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700549
550 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700551 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
552 CHECK(class_root != nullptr);
553 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
554 mirror::Field::SetArrayClass(class_root);
555
556 // Create java.lang.reflect.Constructor.class root and array root.
557 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
558 CHECK(class_root != nullptr);
559 SetClassRoot(kJavaLangReflectConstructor, class_root);
560 mirror::Constructor::SetClass(class_root);
561 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
562 CHECK(class_root != nullptr);
563 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
564 mirror::Constructor::SetArrayClass(class_root);
565
566 // Create java.lang.reflect.Method.class root and array root.
567 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
568 CHECK(class_root != nullptr);
569 SetClassRoot(kJavaLangReflectMethod, class_root);
570 mirror::Method::SetClass(class_root);
571 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
572 CHECK(class_root != nullptr);
573 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
574 mirror::Method::SetArrayClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700575
Brian Carlstrom1f870082011-08-23 16:02:11 -0700576 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700577 // finish initializing Reference class
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700578 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700579 CHECK_EQ(java_lang_ref_Reference.Get(), FindSystemClass(self, "Ljava/lang/ref/Reference;"));
Fred Shih4ee7a662014-07-11 09:59:27 -0700580 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
581 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700582 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
583 class_root->SetAccessFlags(class_root->GetAccessFlags() |
584 kAccClassIsReference | kAccClassIsFinalizerReference);
585 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
586 class_root->SetAccessFlags(class_root->GetAccessFlags() | kAccClassIsReference |
587 kAccClassIsPhantomReference);
588 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
589 class_root->SetAccessFlags(class_root->GetAccessFlags() | kAccClassIsReference);
590 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
591 class_root->SetAccessFlags(class_root->GetAccessFlags() | kAccClassIsReference |
592 kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700593
Ian Rogers23435d02012-09-24 11:23:12 -0700594 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700595 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
596 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
597 SetClassRoot(kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700598
jeffhao8cd6dda2012-02-22 10:15:34 -0800599 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700600 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800601 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800602 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700603 SetClassRoot(kJavaLangClassNotFoundException,
604 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800605 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700606 SetClassRoot(kJavaLangStackTraceElementArrayClass,
607 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800608 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700609
Andreas Gampe76bd8802014-12-10 16:43:58 -0800610 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
611 // initialized.
612 {
613 const DexFile& dex_file = java_lang_Object->GetDexFile();
614 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
615 CHECK(void_string_id != nullptr);
616 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
617 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
618 CHECK(void_type_id != nullptr);
619 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
620 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
621 // as referrer so the used dex cache is core's one.
622 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
623 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
624 self->AssertNoPendingException();
625 }
626
Ian Rogers98379392014-02-24 16:53:16 -0800627 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700628
Brian Carlstroma004aa92012-02-08 18:05:09 -0800629 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700630}
631
Ian Rogers98379392014-02-24 16:53:16 -0800632void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800633 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700634
635 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700636 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700637 // as the types of the field can't be resolved prior to the runtime being
638 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800639 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700640 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800641 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800642
Mathieu Chartierc7853442015-03-27 14:35:38 -0700643 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700644 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
645 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700646
Mathieu Chartierc7853442015-03-27 14:35:38 -0700647 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700648 CHECK_STREQ(queue->GetName(), "queue");
649 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700650
Mathieu Chartierc7853442015-03-27 14:35:38 -0700651 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700652 CHECK_STREQ(queueNext->GetName(), "queueNext");
653 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700654
Mathieu Chartierc7853442015-03-27 14:35:38 -0700655 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700656 CHECK_STREQ(referent->GetName(), "referent");
657 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700658
Mathieu Chartierc7853442015-03-27 14:35:38 -0700659 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700660 CHECK_STREQ(zombie->GetName(), "zombie");
661 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700662
Brian Carlstroma663ea52011-08-19 23:33:41 -0700663 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700664 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700665 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800666 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700667 CHECK(klass != nullptr);
668 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700669 // note SetClassRoot does additional validation.
670 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700671 }
672
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700673 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700674
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700675 // disable the slow paths in FindClass and CreatePrimitiveClass now
676 // that Object, Class, and Object[] are setup
677 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700678
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800679 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700680}
681
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700682void ClassLinker::RunRootClinits() {
683 Thread* self = Thread::Current();
684 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800685 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700686 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700687 StackHandleScope<1> hs(self);
688 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700689 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700690 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700691 }
692 }
693}
694
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700695const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700696 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800697 if (kIsDebugBuild) {
698 for (size_t i = 0; i < oat_files_.size(); ++i) {
699 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700700 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800701 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700702 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
703 oat_files_.push_back(oat_file);
704 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800705}
706
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700707OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
708 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700709 OatFile* oat_file = space->ReleaseOatFile();
710 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700711 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700712 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700713}
714
Richard Uhler66d874d2015-01-15 09:37:19 -0800715std::vector<std::unique_ptr<const DexFile>> ClassLinker::OpenDexFilesFromOat(
716 const char* dex_location, const char* oat_location,
717 std::vector<std::string>* error_msgs) {
718 CHECK(error_msgs != nullptr);
Calin Juravle621962a2014-09-02 15:53:55 +0100719
Richard Uhler66d874d2015-01-15 09:37:19 -0800720 // Verify we aren't holding the mutator lock, which could starve GC if we
721 // have to generate or relocate an oat file.
722 Locks::mutator_lock_->AssertNotHeld(Thread::Current());
723
724 OatFileAssistant oat_file_assistant(dex_location, oat_location, kRuntimeISA,
725 !Runtime::Current()->IsAotCompiler());
726
727 // Lock the target oat location to avoid races generating and loading the
728 // oat file.
729 std::string error_msg;
730 if (!oat_file_assistant.Lock(&error_msg)) {
731 // Don't worry too much if this fails. If it does fail, it's unlikely we
732 // can generate an oat file anyway.
733 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700734 }
735
Richard Uhler66d874d2015-01-15 09:37:19 -0800736 // Check if we already have an up-to-date oat file open.
737 const OatFile* source_oat_file = nullptr;
738 {
739 ReaderMutexLock mu(Thread::Current(), dex_lock_);
740 for (const OatFile* oat_file : oat_files_) {
741 CHECK(oat_file != nullptr);
742 if (oat_file_assistant.GivenOatFileIsUpToDate(*oat_file)) {
743 source_oat_file = oat_file;
744 break;
Andreas Gampe833a4852014-05-21 18:46:59 -0700745 }
746 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700747 }
748
Richard Uhler66d874d2015-01-15 09:37:19 -0800749 // If we didn't have an up-to-date oat file open, try to load one from disk.
750 if (source_oat_file == nullptr) {
751 // Update the oat file on disk if we can. This may fail, but that's okay.
752 // Best effort is all that matters here.
753 if (!oat_file_assistant.MakeUpToDate(&error_msg)) {
754 LOG(WARNING) << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700755 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700756
Richard Uhler66d874d2015-01-15 09:37:19 -0800757 // Get the oat file on disk.
758 std::unique_ptr<OatFile> oat_file = oat_file_assistant.GetBestOatFile();
759 if (oat_file.get() != nullptr) {
760 source_oat_file = oat_file.release();
761 RegisterOatFile(source_oat_file);
Andreas Gampe833a4852014-05-21 18:46:59 -0700762 }
763 }
764
Richard Uhler66d874d2015-01-15 09:37:19 -0800765 std::vector<std::unique_ptr<const DexFile>> dex_files;
Andreas Gampe833a4852014-05-21 18:46:59 -0700766
Richard Uhler66d874d2015-01-15 09:37:19 -0800767 // Load the dex files from the oat file.
768 if (source_oat_file != nullptr) {
769 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
770 if (dex_files.empty()) {
771 error_msgs->push_back("Failed to open dex files from "
772 + source_oat_file->GetLocation());
Andreas Gampe833a4852014-05-21 18:46:59 -0700773 }
774 }
775
Richard Uhler66d874d2015-01-15 09:37:19 -0800776 // Fall back to running out of the original dex file if we couldn't load any
777 // dex_files from the oat file.
778 if (dex_files.empty()) {
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700779 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800780 if (!DexFile::Open(dex_location, dex_location, &error_msg, &dex_files)) {
781 LOG(WARNING) << error_msg;
782 error_msgs->push_back("Failed to open dex files from "
783 + std::string(dex_location));
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700784 }
785 } else {
786 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
787 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700788 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800789 return dex_files;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700790}
791
Brian Carlstromae826982011-11-09 01:33:42 -0800792const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700793 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700794 for (size_t i = 0; i < oat_files_.size(); i++) {
795 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700796 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -0800797 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700798 return oat_file;
799 }
800 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700801 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -0700802}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700803
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800804void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700805 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700806 DCHECK(obj != nullptr);
807 DCHECK(class_linker != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700808 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700809 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -0700810 if (!method->IsNative()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800811 const size_t pointer_size = class_linker->image_pointer_size_;
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800812 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800813 if (!method->IsRuntimeMethod() && method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800814 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
815 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -0700816 }
817 }
818 }
819}
820
Mathieu Chartierc7853442015-03-27 14:35:38 -0700821void SanityCheckObjectsCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED)
822 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
823 DCHECK(obj != nullptr);
824 CHECK(obj->GetClass() != nullptr) << "Null class " << obj;
825 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
826 if (obj->IsClass()) {
827 auto klass = obj->AsClass();
828 ArtField* fields[2] = { klass->GetSFields(), klass->GetIFields() };
829 size_t num_fields[2] = { klass->NumStaticFields(), klass->NumInstanceFields() };
830 for (size_t i = 0; i < 2; ++i) {
831 for (size_t j = 0; j < num_fields[i]; ++j) {
832 CHECK_EQ(fields[i][j].GetDeclaringClass(), klass);
833 }
834 }
835 }
836}
837
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700838void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800839 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700840 CHECK(!init_done_);
841
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700842 Runtime* const runtime = Runtime::Current();
843 Thread* const self = Thread::Current();
844 gc::Heap* const heap = runtime->GetHeap();
845 gc::space::ImageSpace* const space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700846 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700847 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700848 OatFile& oat_file = GetImageOatFile(space);
849 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
850 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700851 const char* image_file_location = oat_file.GetOatHeader().
852 GetStoreValueByKey(OatHeader::kImageLocationKey);
853 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700854 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -0700855 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -0800856 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +0100857 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800858 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
859 mirror::ObjectArray<mirror::DexCache>* dex_caches =
860 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700861
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700862 StackHandleScope<1> hs(self);
863 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
864 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
865 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700866 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700867
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700868 // Special case of setting up the String class early so that we can test arbitrary objects
869 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700870 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800871
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700872 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700873 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700874 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800875 StackHandleScope<1> hs2(self);
876 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700877 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700878 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
879 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700880 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700881 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800882 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
883 if (dex_file.get() == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700884 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700885 << " from within oat file " << oat_file.GetLocation()
886 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -0800887 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700888 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700889
890 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
891
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800892 AppendToBootClassPath(*dex_file.get(), dex_cache);
893 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700894 }
895
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700896 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
897 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -0700898 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -0800899 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700900 if (!runtime->IsAotCompiler()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800901 // Aot compiler supports having an image with a different pointer size than the runtime. This
Mathieu Chartier2d721012014-11-10 11:08:06 -0800902 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
903 // also use 32 bit dex2oat on a system with 64 bit apps.
904 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
905 << sizeof(void*);
906 }
907 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
908 image_pointer_size_ = 4;
909 } else {
910 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
911 image_pointer_size_ = 8;
912 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700913
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700914 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800915 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700916 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700917 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700918 if (kSanityCheckObjects) {
919 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
920 auto* dex_cache = dex_caches->Get(i);
921 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
922 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
923 if (field != nullptr) {
924 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
925 }
926 }
927 }
928 heap->VisitObjects(SanityCheckObjectsCallback, nullptr);
929 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700930
931 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800932 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700933 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700934
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800935 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700936 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800937 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800938 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700939 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
940 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700941 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
942 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
943 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
944 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
Fred Shih4ee7a662014-07-11 09:59:27 -0700945 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800946 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
947 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
948 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
949 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
950 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
951 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
952 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
953 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
954 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
955 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700956
Ian Rogers98379392014-02-24 16:53:16 -0800957 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700958
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800959 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700960}
961
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700962void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700963 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700964 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
965 visitor, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700966 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800967 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700968 buffered_visitor.VisitRoot(root);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700969 root.Read()->VisitFieldRoots(buffered_visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800970 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700971 // PreZygote classes can't move so we won't need to update fields' declaring classes.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800972 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700973 buffered_visitor.VisitRoot(root);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700974 root.Read()->VisitFieldRoots(buffered_visitor);
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700975 }
976 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800977 for (auto& root : new_class_roots_) {
978 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700979 old_ref->VisitFieldRoots(buffered_visitor);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700980 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800981 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700982 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700983 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
984 // corresponding object. This is slow, but luckily for us, this may only happen with a
985 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800986 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800987 DCHECK(it != class_table_.end());
988 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700989 }
990 }
991 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700992 buffered_visitor.Flush(); // Flush before clearing new_class_roots_.
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700993 if ((flags & kVisitRootFlagClearRootLog) != 0) {
994 new_class_roots_.clear();
995 }
996 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
997 log_new_class_table_roots_ = true;
998 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
999 log_new_class_table_roots_ = false;
1000 }
1001 // We deliberately ignore the class roots in the image since we
1002 // handle image roots by using the MS/CMS rescanning of dirty cards.
1003}
1004
Brian Carlstroma663ea52011-08-19 23:33:41 -07001005// Keep in sync with InitCallback. Anything we visit, we need to
1006// reinit references to when reinitializing a ClassLinker from a
1007// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001008void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
1009 class_roots_.VisitRoot(visitor, RootInfo(kRootVMInternal));
1010 Thread* const self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001011 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001012 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001013 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001014 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001015 dex_cache.VisitRoot(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001016 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001017 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1018 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001019 dex_caches_[index].VisitRoot(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001020 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001021 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001022 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1023 new_dex_cache_roots_.clear();
1024 }
1025 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1026 log_new_dex_caches_roots_ = true;
1027 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1028 log_new_dex_caches_roots_ = false;
1029 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001030 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001031 VisitClassRoots(visitor, flags);
1032 array_iftable_.VisitRoot(visitor, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001033 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001034 find_array_class_cache_[i].VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001035 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001036}
1037
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001038void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1039 if (dex_cache_image_class_lookup_required_) {
1040 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001041 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001042 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001043 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001044 for (GcRoot<mirror::Class>& root : class_table_) {
1045 if (!visitor(root.Read(), arg)) {
1046 return;
1047 }
1048 }
1049 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1050 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001051 return;
1052 }
1053 }
1054}
1055
Ian Rogersdbf3be02014-08-29 15:40:08 -07001056static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001057 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001058 classes->insert(c);
1059 return true;
1060}
1061
Ian Rogersdbf3be02014-08-29 15:40:08 -07001062struct GetClassesVisitorArrayArg {
1063 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1064 int32_t index;
1065 bool success;
1066};
1067
1068static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1069 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1070 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1071 if (arg->index < (*arg->classes)->GetLength()) {
1072 (*arg->classes)->Set(arg->index, c);
1073 arg->index++;
1074 return true;
1075 } else {
1076 arg->success = false;
1077 return false;
1078 }
1079}
1080
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001081void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001082 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1083 // is avoiding duplicates.
1084 if (!kMovingClasses) {
1085 std::set<mirror::Class*> classes;
1086 VisitClasses(GetClassesVisitorSet, &classes);
1087 for (mirror::Class* klass : classes) {
1088 if (!visitor(klass, arg)) {
1089 return;
1090 }
1091 }
1092 } else {
1093 Thread* self = Thread::Current();
1094 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001095 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001096 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1097 GetClassesVisitorArrayArg local_arg;
1098 local_arg.classes = &classes;
1099 local_arg.success = false;
1100 // We size the array assuming classes won't be added to the class table during the visit.
1101 // If this assumption fails we iterate again.
1102 while (!local_arg.success) {
1103 size_t class_table_size;
1104 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001105 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001106 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001107 }
1108 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1109 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1110 classes.Assign(
1111 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1112 CHECK(classes.Get() != nullptr); // OOME.
1113 local_arg.index = 0;
1114 local_arg.success = true;
1115 VisitClasses(GetClassesVisitorArray, &local_arg);
1116 }
1117 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1118 // If the class table shrank during creation of the clases array we expect null elements. If
1119 // the class table grew then the loop repeats. If classes are created after the loop has
1120 // finished then we don't visit.
1121 mirror::Class* klass = classes->Get(i);
1122 if (klass != nullptr && !visitor(klass, arg)) {
1123 return;
1124 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001125 }
1126 }
1127}
1128
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001129ClassLinker::~ClassLinker() {
Brian Carlstromea46f952013-07-30 01:26:50 -07001130 mirror::ArtMethod::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001131 mirror::Class::ResetClass();
1132 mirror::Constructor::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001133 mirror::Field::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001134 mirror::Method::ResetClass();
1135 mirror::Reference::ResetClass();
1136 mirror::StackTraceElement::ResetClass();
1137 mirror::String::ResetClass();
1138 mirror::Throwable::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001139 mirror::BooleanArray::ResetArrayClass();
1140 mirror::ByteArray::ResetArrayClass();
1141 mirror::CharArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001142 mirror::Constructor::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001143 mirror::DoubleArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001144 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001145 mirror::FloatArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001146 mirror::Method::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001147 mirror::IntArray::ResetArrayClass();
1148 mirror::LongArray::ResetArrayClass();
1149 mirror::ShortArray::ResetArrayClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001150 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001151}
1152
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001153mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001154 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001155 StackHandleScope<16> hs(self);
1156 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1157 Handle<mirror::DexCache> dex_cache(
1158 hs.NewHandle(down_cast<mirror::DexCache*>(
1159 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1160 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001161 if (dex_cache.Get() == nullptr) {
1162 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001163 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001164 Handle<mirror::String>
1165 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001166 if (location.Get() == nullptr) {
1167 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001168 }
Ian Rogers700a4022014-05-19 16:49:03 -07001169 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001170 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001171 if (strings.Get() == nullptr) {
1172 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001173 }
Ian Rogers700a4022014-05-19 16:49:03 -07001174 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001175 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001176 if (types.Get() == nullptr) {
1177 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001178 }
Ian Rogers700a4022014-05-19 16:49:03 -07001179 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001180 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001181 if (methods.Get() == nullptr) {
1182 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001183 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001184 Handle<mirror::Array> fields;
1185 if (image_pointer_size_ == 8) {
1186 fields = hs.NewHandle<mirror::Array>(mirror::LongArray::Alloc(self, dex_file.NumFieldIds()));
1187 } else {
1188 fields = hs.NewHandle<mirror::Array>(mirror::IntArray::Alloc(self, dex_file.NumFieldIds()));
1189 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001190 if (fields.Get() == nullptr) {
1191 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001192 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001193 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1194 fields.Get());
1195 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001196}
1197
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001198mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001199 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001200 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001201 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001202 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001203 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001204 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1205 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001206 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001207 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001208 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001209 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001210 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001211}
1212
Ian Rogers6fac4472014-02-25 17:01:10 -08001213mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001214 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001215}
1216
Brian Carlstromea46f952013-07-30 01:26:50 -07001217mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001218 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001219 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001220}
1221
Mathieu Chartier590fee92013-09-13 13:46:47 -07001222mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1223 Thread* self, size_t length) {
1224 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1225 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001226}
1227
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001228mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1229 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001230 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001231
1232 // For temporary classes we must wait for them to be retired.
1233 if (init_done_ && klass->IsTemp()) {
1234 CHECK(!klass->IsResolved());
1235 if (klass->IsErroneous()) {
1236 ThrowEarlierClassFailure(klass);
1237 return nullptr;
1238 }
1239 StackHandleScope<1> hs(self);
1240 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1241 ObjectLock<mirror::Class> lock(self, h_class);
1242 // Loop and wait for the resolving thread to retire this class.
1243 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1244 lock.WaitIgnoringInterrupts();
1245 }
1246 if (h_class->IsErroneous()) {
1247 ThrowEarlierClassFailure(h_class.Get());
1248 return nullptr;
1249 }
1250 CHECK(h_class->IsRetired());
1251 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001252 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
1253 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001254 }
1255
Brian Carlstromaded5f72011-10-07 17:15:04 -07001256 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001257 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001258 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001259 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1260 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001261 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001262 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1263 ThrowClassCircularityError(h_class.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001264 mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001265 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001266 }
1267 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001268 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001269 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001270 }
1271 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001272
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001273 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001274 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001275 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001276 }
1277 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001278 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001279 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001280 return klass;
1281}
1282
Ian Rogers68b56852014-08-29 20:19:11 -07001283typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
1284
1285// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001286ClassPathEntry FindInClassPath(const char* descriptor,
1287 size_t hash, const std::vector<const DexFile*>& class_path) {
1288 for (const DexFile* dex_file : class_path) {
1289 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001290 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07001291 return ClassPathEntry(dex_file, dex_class_def);
1292 }
1293 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001294 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07001295}
1296
Andreas Gampef865ea92015-04-13 22:14:19 -07001297static bool IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1298 mirror::ClassLoader* class_loader)
1299 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1300 return class_loader == nullptr ||
1301 class_loader->GetClass() ==
1302 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader);
1303}
1304
1305bool ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1306 Thread* self, const char* descriptor,
1307 size_t hash,
1308 Handle<mirror::ClassLoader> class_loader,
1309 mirror::Class** result) {
1310 // Termination case: boot class-loader.
1311 if (IsBootClassLoader(soa, class_loader.Get())) {
1312 // The boot class loader, search the boot class path.
1313 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
1314 if (pair.second != nullptr) {
1315 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
1316 if (klass != nullptr) {
1317 *result = EnsureResolved(self, descriptor, klass);
1318 } else {
1319 *result = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(),
1320 *pair.first, *pair.second);
1321 }
1322 if (*result == nullptr) {
1323 CHECK(self->IsExceptionPending()) << descriptor;
1324 self->ClearException();
1325 }
Ian Rogers32427292014-11-19 14:05:21 -08001326 } else {
Andreas Gampef865ea92015-04-13 22:14:19 -07001327 *result = nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001328 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001329 return true;
1330 }
1331
1332 // Unsupported class-loader?
1333 if (class_loader->GetClass() !=
1334 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)) {
1335 *result = nullptr;
1336 return false;
1337 }
1338
1339 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
1340 StackHandleScope<4> hs(self);
1341 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
1342 bool recursive_result = FindClassInPathClassLoader(soa, self, descriptor, hash, h_parent, result);
1343
1344 if (!recursive_result) {
1345 // Something wrong up the chain.
1346 return false;
1347 }
1348
1349 if (*result != nullptr) {
1350 // Found the class up the chain.
1351 return true;
1352 }
1353
1354 // Handle this step.
1355 // Handle as if this is the child PathClassLoader.
1356 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
1357 // We need to get the DexPathList and loop through it.
1358 ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
1359 ArtField* const dex_file_field =
1360 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
1361 mirror::Object* dex_path_list =
1362 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
1363 GetObject(class_loader.Get());
1364 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
1365 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1366 mirror::Object* dex_elements_obj =
1367 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1368 GetObject(dex_path_list);
1369 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1370 // at the mCookie which is a DexFile vector.
1371 if (dex_elements_obj != nullptr) {
1372 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
1373 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
1374 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
1375 mirror::Object* element = dex_elements->GetWithoutChecks(i);
1376 if (element == nullptr) {
1377 // Should never happen, fall back to java code to throw a NPE.
1378 break;
1379 }
1380 mirror::Object* dex_file = dex_file_field->GetObject(element);
1381 if (dex_file != nullptr) {
1382 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
1383 if (long_array == nullptr) {
1384 // This should never happen so log a warning.
1385 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001386 break;
1387 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001388 int32_t long_array_size = long_array->GetLength();
1389 for (int32_t j = 0; j < long_array_size; ++j) {
1390 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
1391 long_array->GetWithoutChecks(j)));
1392 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
1393 if (dex_class_def != nullptr) {
1394 RegisterDexFile(*cp_dex_file);
1395 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
1396 *cp_dex_file, *dex_class_def);
1397 if (klass == nullptr) {
1398 CHECK(self->IsExceptionPending()) << descriptor;
1399 self->ClearException();
1400 // TODO: Is it really right to break here, and not check the other dex files?
1401 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001402 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001403 *result = klass;
1404 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001405 }
1406 }
1407 }
1408 }
1409 }
Ian Rogers32427292014-11-19 14:05:21 -08001410 self->AssertNoPendingException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001411 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001412
1413 // Result is still null from the parent call, no need to set it again...
1414 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001415}
1416
Ian Rogers98379392014-02-24 16:53:16 -08001417mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001418 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001419 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001420 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001421 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001422 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001423 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1424 // for primitive classes that aren't backed by dex files.
1425 return FindPrimitiveClass(descriptor[0]);
1426 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001427 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001428 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001429 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07001430 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001431 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001432 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001433 // Class is not yet loaded.
1434 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001435 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001436 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001437 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001438 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07001439 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001440 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07001441 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07001442 } else {
1443 // The boot class loader is searched ahead of the application class loader, failures are
1444 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
1445 // trigger the chaining with a proper stack trace.
1446 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001447 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07001448 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05001449 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001450 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001451 ScopedObjectAccessUnchecked soa(self);
Andreas Gampef865ea92015-04-13 22:14:19 -07001452 mirror::Class* cp_klass;
1453 if (FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader, &cp_klass)) {
1454 // The chain was understood. So the value in cp_klass is either the class we were looking
1455 // for, or not found.
1456 if (cp_klass != nullptr) {
1457 return cp_klass;
1458 }
1459 // TODO: We handle the boot classpath loader in FindClassInPathClassLoader. Try to unify this
1460 // and the branch above. TODO: throw the right exception here.
1461
1462 // We'll let the Java-side rediscover all this and throw the exception with the right stack
1463 // trace.
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07001464 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001465
1466 if (Runtime::Current()->IsAotCompiler()) {
1467 // Oops, compile-time, can't run actual class-loader code.
1468 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
1469 self->SetException(pre_allocated);
1470 return nullptr;
1471 }
1472
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001473 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001474 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001475 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07001476 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07001477 {
1478 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001479 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1480 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07001481 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001482 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07001483 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07001484 }
Ian Rogers68b56852014-08-29 20:19:11 -07001485 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001486 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1487 WellKnownClasses::java_lang_ClassLoader_loadClass,
1488 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001489 }
Ian Rogers98379392014-02-24 16:53:16 -08001490 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001491 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07001492 return nullptr;
1493 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08001494 // broken loader - throw NPE to be compatible with Dalvik
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001495 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
1496 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07001497 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08001498 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001499 // success, return mirror::Class*
1500 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001501 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001502 }
Ian Rogers07140832014-09-30 15:43:59 -07001503 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001504}
1505
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001506mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001507 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001508 const DexFile& dex_file,
1509 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001510 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001511 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001512
Brian Carlstromaded5f72011-10-07 17:15:04 -07001513 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001514 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001515 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001516 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001517 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001518 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001519 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001520 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001521 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001522 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1523 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001524 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001525 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001526 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001527 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001528 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001529 }
1530
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001531 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001532 // Allocate a class with the status of not ready.
1533 // Interface object should get the right size here. Regular class will
1534 // figure out the right size later and be replaced with one of the right
1535 // size when the class becomes resolved.
1536 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001537 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001538 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001539 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07001540 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001541 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001542 klass->SetDexCache(FindDexCache(dex_file));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001543
1544 SetupClass(dex_file, dex_class_def, klass, class_loader.Get());
1545
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001546 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001547 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001548
Mathieu Chartier590fee92013-09-13 13:46:47 -07001549 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001550 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001551 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001552 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1553 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001554 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001555 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001556
Mathieu Chartierc7853442015-03-27 14:35:38 -07001557 // Load the fields and other things after we are inserted in the table. This is so that we don't
1558 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
1559 // other reason is that the field roots are only visited from the class table. So we need to be
1560 // inserted before we allocate / fill in these fields.
1561 LoadClass(self, dex_file, dex_class_def, klass);
1562 if (self->IsExceptionPending()) {
1563 // An exception occured during load, set status to erroneous while holding klass' lock in case
1564 // notification is necessary.
1565 if (!klass->IsErroneous()) {
1566 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
1567 }
1568 return nullptr;
1569 }
1570
Brian Carlstromaded5f72011-10-07 17:15:04 -07001571 // Finish loading (if necessary) by finding parents
1572 CHECK(!klass->IsLoaded());
1573 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1574 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001575 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001576 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001577 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001578 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001579 }
1580 CHECK(klass->IsLoaded());
1581 // Link the class (if necessary)
1582 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001583 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001584 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001585
1586 mirror::Class* new_class = nullptr;
1587 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001588 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001589 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001590 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001591 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001592 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001593 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07001594 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001595 CHECK(new_class != nullptr) << descriptor;
1596 CHECK(new_class->IsResolved()) << descriptor;
1597
1598 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001599
Sebastien Hertza8a697f2015-01-15 12:28:47 +01001600 // Instrumentation may have updated entrypoints for all methods of all
1601 // classes. However it could not update methods of this class while we
1602 // were loading it. Now the class is resolved, we can update entrypoints
1603 // as required by instrumentation.
1604 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
1605 // We must be in the kRunnable state to prevent instrumentation from
1606 // suspending all threads to update entrypoints while we are doing it
1607 // for this class.
1608 DCHECK_EQ(self->GetState(), kRunnable);
1609 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(new_class_h.Get());
1610 }
1611
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001612 /*
1613 * We send CLASS_PREPARE events to the debugger from here. The
1614 * definition of "preparation" is creating the static fields for a
1615 * class and initializing them to the standard default values, but not
1616 * executing any code (that comes later, during "initialization").
1617 *
1618 * We did the static preparation in LinkClass.
1619 *
1620 * The class has been prepared and resolved but possibly not yet verified
1621 * at this point.
1622 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001623 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001624
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001625 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001626}
1627
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001628uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
1629 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07001630 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001631 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07001632 size_t num_8 = 0;
1633 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001634 size_t num_32 = 0;
1635 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001636 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001637 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1638 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001639 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001640 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07001641 switch (c) {
1642 case 'L':
1643 case '[':
1644 num_ref++;
1645 break;
1646 case 'J':
1647 case 'D':
1648 num_64++;
1649 break;
1650 case 'I':
1651 case 'F':
1652 num_32++;
1653 break;
1654 case 'S':
1655 case 'C':
1656 num_16++;
1657 break;
1658 case 'B':
1659 case 'Z':
1660 num_8++;
1661 break;
1662 default:
1663 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08001664 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001665 }
1666 }
1667 }
Fred Shih37f05ef2014-07-16 18:38:08 -07001668 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001669}
1670
Ian Rogers97b52f82014-08-14 11:34:07 -07001671OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
1672 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001673 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Richard Uhler07b3c232015-03-31 15:57:54 -07001674 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001675 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001676 *found = false;
1677 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001678 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001679 *found = true;
1680 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08001681}
1682
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001683static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
1684 uint32_t method_idx) {
1685 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07001686 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001687 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001688 ClassDataItemIterator it(dex_file, class_data);
1689 // Skip fields
1690 while (it.HasNextStaticField()) {
1691 it.Next();
1692 }
1693 while (it.HasNextInstanceField()) {
1694 it.Next();
1695 }
1696 // Process methods
1697 size_t class_def_method_index = 0;
1698 while (it.HasNextDirectMethod()) {
1699 if (it.GetMemberIndex() == method_idx) {
1700 return class_def_method_index;
1701 }
1702 class_def_method_index++;
1703 it.Next();
1704 }
1705 while (it.HasNextVirtualMethod()) {
1706 if (it.GetMemberIndex() == method_idx) {
1707 return class_def_method_index;
1708 }
1709 class_def_method_index++;
1710 it.Next();
1711 }
1712 DCHECK(!it.HasNext());
1713 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08001714 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001715}
1716
Ian Rogers97b52f82014-08-14 11:34:07 -07001717const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08001718 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001719 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001720 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08001721 size_t oat_method_index;
1722 if (method->IsStatic() || method->IsDirect()) {
1723 // Simple case where the oat method index was stashed at load time.
1724 oat_method_index = method->GetMethodIndex();
1725 } else {
1726 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1727 // by search for its position in the declared virtual methods.
1728 oat_method_index = declaring_class->NumDirectMethods();
1729 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001730 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001731 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07001732 // Check method index instead of identity in case of duplicate method definitions.
1733 if (method->GetDexMethodIndex() ==
1734 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001735 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001736 break;
1737 }
Ian Rogersf320b632012-03-13 18:47:47 -07001738 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001739 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001740 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
1741 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001742 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001743 DCHECK_EQ(oat_method_index,
1744 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001745 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001746 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07001747 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
1748 declaring_class->GetDexClassDefIndex(),
1749 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001750 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001751 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001752 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001753 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07001754}
1755
1756// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001757const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001758 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07001759 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001760 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07001761 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001762 bool found;
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001763 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1764 if (found) {
1765 auto* code = oat_method.GetQuickCode();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001766 if (code != nullptr) {
1767 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08001768 }
1769 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001770 jit::Jit* const jit = Runtime::Current()->GetJit();
1771 if (jit != nullptr) {
1772 auto* code = jit->GetCodeCache()->GetCodeFor(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001773 if (code != nullptr) {
1774 return code;
1775 }
1776 }
1777 if (method->IsNative()) {
1778 // No code and native? Use generic trampoline.
1779 return GetQuickGenericJniStub();
1780 }
1781 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07001782}
1783
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001784const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
1785 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
1786 return nullptr;
1787 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001788 bool found;
1789 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1790 if (found) {
1791 return oat_method.GetQuickCode();
1792 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001793 jit::Jit* jit = Runtime::Current()->GetJit();
1794 if (jit != nullptr) {
1795 auto* code = jit->GetCodeCache()->GetCodeFor(method);
1796 if (code != nullptr) {
1797 return code;
1798 }
1799 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001800 return nullptr;
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001801}
1802
Ian Rogersef7d42f2014-01-06 12:55:46 -08001803const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
1804 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001805 bool found;
1806 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
1807 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001808 return nullptr;
1809 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001810 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001811 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001812}
1813
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001814// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001815static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07001816 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08001817 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001818 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08001819 // May return true for native code, in the case of generic JNI
1820 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001821 return true;
1822 }
1823 // If interpreter mode is enabled, every method (except native and proxy) must
1824 // be run with interpreter.
1825 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
1826 !method->IsNative() && !method->IsProxyMethod();
1827}
1828
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001829void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08001830 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07001831 if (klass->NumDirectMethods() == 0) {
1832 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08001833 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001834 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001835 if (!runtime->IsStarted()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001836 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001837 return; // OAT file unavailable.
1838 }
Ian Rogers19846512012-02-24 11:42:47 -08001839 }
Alex Light64ad14d2014-08-19 14:23:13 -07001840
Mathieu Chartierf8322842014-05-16 10:59:25 -07001841 const DexFile& dex_file = klass->GetDexFile();
1842 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07001843 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07001844 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07001845 // There should always be class data if there were direct methods.
1846 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08001847 ClassDataItemIterator it(dex_file, class_data);
1848 // Skip fields
1849 while (it.HasNextStaticField()) {
1850 it.Next();
1851 }
1852 while (it.HasNextInstanceField()) {
1853 it.Next();
1854 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001855 bool has_oat_class;
1856 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1857 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07001858 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001859 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001860 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001861 if (!method->IsStatic()) {
1862 // Only update static methods.
1863 continue;
Ian Rogers19846512012-02-24 11:42:47 -08001864 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001865 const void* quick_code = nullptr;
1866 if (has_oat_class) {
1867 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001868 quick_code = oat_method.GetQuickCode();
1869 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001870 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001871 if (enter_interpreter) {
1872 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07001873 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001874 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001875 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08001876 } else {
1877 quick_code = GetQuickToInterpreterBridge();
1878 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001879 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001880 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08001881 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001882 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08001883}
1884
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001885void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07001886 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001887 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001888 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001889 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001890 // The following code only applies to a non-compiler runtime.
1891 return;
1892 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001893 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001894 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001895 if (oat_class != nullptr) {
1896 // Every kind of method should at least get an invoke stub from the oat_method.
1897 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001898 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001899 oat_method.LinkMethod(method.Get());
1900 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001901
Jeff Hao16743632013-05-08 10:59:04 -07001902 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001903 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08001904 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001905 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001906 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001907 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07001908 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001909 }
1910
Brian Carlstrom92827a52011-10-10 15:50:01 -07001911 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001912 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001913 return;
1914 }
Ian Rogers19846512012-02-24 11:42:47 -08001915
1916 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001917 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001918 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
1919 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001920 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001921 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001922 if (!method->IsNative()) {
1923 // Set entry point from compiled code if there's no code or in interpreter only mode.
1924 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001925 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001926 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001927 }
Ian Rogers0d6de042012-02-29 08:50:26 -08001928 }
jeffhao26c0a1a2012-01-17 16:28:33 -08001929
Ian Rogers62d6c772013-02-27 08:32:07 -08001930 if (method->IsNative()) {
1931 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001932 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07001933
1934 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001935 // We have a native method here without code. Then it should have either the generic JNI
1936 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
1937 // TODO: this doesn't handle all the cases where trampolines may be installed.
1938 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1939 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07001940 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001941 }
1942}
1943
Mathieu Chartierc7853442015-03-27 14:35:38 -07001944void ClassLinker::SetupClass(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1945 Handle<mirror::Class> klass, mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001946 CHECK(klass.Get() != nullptr);
1947 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001948 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001949 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001950 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001951
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001952 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07001953 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07001954 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001955 klass->SetAccessFlags(access_flags);
1956 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001957 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001958 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001959
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001960 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001961 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08001962 CHECK(klass->GetDexCacheStrings() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001963}
Brian Carlstrom934486c2011-07-12 23:42:50 -07001964
Mathieu Chartierc7853442015-03-27 14:35:38 -07001965void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
1966 const DexFile::ClassDef& dex_class_def,
1967 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07001968 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001969 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001970 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001971 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001972 bool has_oat_class = false;
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001973 if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001974 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1975 &has_oat_class);
1976 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001977 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07001978 }
1979 }
1980 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001981 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001982 }
1983}
1984
Mathieu Chartierc7853442015-03-27 14:35:38 -07001985ArtField* ClassLinker::AllocArtFieldArray(Thread* self, size_t length) {
1986 auto* const la = Runtime::Current()->GetLinearAlloc();
1987 auto* ptr = reinterpret_cast<ArtField*>(la->AllocArray<ArtField>(self, length));
1988 CHECK(ptr!= nullptr);
1989 std::uninitialized_fill_n(ptr, length, ArtField());
1990 return ptr;
1991}
1992
Ian Rogers7b078e82014-09-10 14:44:24 -07001993void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07001994 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001995 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001996 const OatFile::OatClass* oat_class) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001997 // Load static fields.
Ian Rogers0571d352011-11-03 19:51:38 -07001998 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001999 const size_t num_sfields = it.NumStaticFields();
2000 ArtField* sfields = num_sfields != 0 ? AllocArtFieldArray(self, num_sfields) : nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002001 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07002002 CHECK_LT(i, num_sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002003 LoadField(it, klass, &sfields[i]);
Ian Rogers0571d352011-11-03 19:51:38 -07002004 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002005 klass->SetSFields(sfields);
2006 klass->SetNumStaticFields(num_sfields);
2007 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
2008 // Load instance fields.
2009 const size_t num_ifields = it.NumInstanceFields();
2010 ArtField* ifields = num_ifields != 0 ? AllocArtFieldArray(self, num_ifields) : nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002011 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07002012 CHECK_LT(i, num_ifields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002013 LoadField(it, klass, &ifields[i]);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002014 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002015 klass->SetIFields(ifields);
2016 klass->SetNumInstanceFields(num_ifields);
2017 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07002018 // Note: We cannot have thread suspension until the field arrays are setup or else
2019 // Class::VisitFieldRoots may miss some fields.
2020 self->AllowThreadSuspension();
Ian Rogers0571d352011-11-03 19:51:38 -07002021 // Load methods.
2022 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002023 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002024 mirror::ObjectArray<mirror::ArtMethod>* directs =
2025 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002026 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002027 CHECK(self->IsExceptionPending()); // OOME.
2028 return;
2029 }
2030 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002031 }
Ian Rogers0571d352011-11-03 19:51:38 -07002032 if (it.NumVirtualMethods() != 0) {
2033 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002034 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2035 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002036 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002037 CHECK(self->IsExceptionPending()); // OOME.
2038 return;
2039 }
2040 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002041 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002042 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002043 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2044 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002045 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002046 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002047 StackHandleScope<1> hs(self);
2048 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002049 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002050 CHECK(self->IsExceptionPending()); // OOME.
2051 return;
2052 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002053 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002054 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002055 uint32_t it_method_index = it.GetMemberIndex();
2056 if (last_dex_method_index == it_method_index) {
2057 // duplicate case
2058 method->SetMethodIndex(last_class_def_method_index);
2059 } else {
2060 method->SetMethodIndex(class_def_method_index);
2061 last_dex_method_index = it_method_index;
2062 last_class_def_method_index = class_def_method_index;
2063 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002064 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002065 }
2066 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002067 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002068 StackHandleScope<1> hs(self);
2069 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002070 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002071 CHECK(self->IsExceptionPending()); // OOME.
2072 return;
2073 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002074 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002075 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002076 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002077 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002078 }
2079 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002080}
2081
Mathieu Chartierc7853442015-03-27 14:35:38 -07002082void ClassLinker::LoadField(const ClassDataItemIterator& it, Handle<mirror::Class> klass,
2083 ArtField* dst) {
2084 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002085 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002086 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002087 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002088}
2089
Brian Carlstromea46f952013-07-30 01:26:50 -07002090mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002091 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002092 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002093 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002094 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002095 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002096
Brian Carlstromea46f952013-07-30 01:26:50 -07002097 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002098 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002099 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002100 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002101 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002102 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002103
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002104 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002105 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002106 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002107 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002108
Ian Rogers19846512012-02-24 11:42:47 -08002109 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002110 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002111
Andreas Gampe51829322014-08-25 15:05:04 -07002112 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002113
Ian Rogersdfb325e2013-10-30 01:00:44 -07002114 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002115 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002116 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2117 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002118 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002119 klass->SetFinalizable();
2120 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002121 std::string temp;
2122 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002123 // The Enum class declares a "final" finalize() method to prevent subclasses from
2124 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2125 // subclasses, so we exclude it here.
2126 // We also want to avoid setting the flag on Object, where we know that finalize() is
2127 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002128 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2129 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002130 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002131 }
2132 }
2133 }
2134 } else if (method_name[0] == '<') {
2135 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002136 bool is_init = (strcmp("<init>", method_name) == 0);
2137 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002138 if (UNLIKELY(!is_init && !is_clinit)) {
2139 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2140 } else {
2141 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2142 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002143 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002144 access_flags |= kAccConstructor;
2145 }
2146 }
2147 }
2148 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002149
Mathieu Chartier66f19252012-09-18 08:57:04 -07002150 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002151}
2152
Ian Rogers7b078e82014-09-10 14:44:24 -07002153void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002154 StackHandleScope<1> hs(self);
2155 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002156 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2157 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002158 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002159}
2160
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002161void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002162 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002163 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002164 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002165 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002166}
2167
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002168bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002169 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002170 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002171 mirror::DexCache* dex_cache = GetDexCache(i);
2172 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002173 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002174 }
2175 }
2176 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002177}
2178
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002179bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002180 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002181 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002182}
2183
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002184void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002185 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002186 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002187 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002188 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2189 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002190 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002191 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002192 if (log_new_dex_caches_roots_) {
2193 // TODO: This is not safe if we can remove dex caches.
2194 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2195 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002196}
2197
Brian Carlstromaded5f72011-10-07 17:15:04 -07002198void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002199 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002200 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002201 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002202 if (IsDexFileRegisteredLocked(dex_file)) {
2203 return;
2204 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002205 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002206 // Don't alloc while holding the lock, since allocation may need to
2207 // suspend all threads and another thread may need the dex_lock_ to
2208 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002209 StackHandleScope<1> hs(self);
2210 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002211 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2212 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002213 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002214 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002215 if (IsDexFileRegisteredLocked(dex_file)) {
2216 return;
2217 }
2218 RegisterDexFileLocked(dex_file, dex_cache);
2219 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002220}
2221
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002222void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002223 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002224 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002225 RegisterDexFileLocked(dex_file, dex_cache);
2226}
2227
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002228mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002229 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002230 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002231 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002232 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002233 if (dex_cache->GetDexFile() == &dex_file) {
2234 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002235 }
2236 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002237 // Search matching by location name.
2238 std::string location(dex_file.GetLocation());
2239 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002240 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002241 if (dex_cache->GetDexFile()->GetLocation() == location) {
2242 return dex_cache;
2243 }
2244 }
2245 // Failure, dump diagnostic and abort.
2246 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002247 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002248 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2249 }
2250 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002251 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002252}
2253
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002254void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002255 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08002256 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002257 mirror::DexCache* dex_cache = GetDexCache(i);
2258 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08002259 }
2260}
2261
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002262mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002263 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002264 if (UNLIKELY(klass == nullptr)) {
2265 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002266 }
2267 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002268}
2269
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002270mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2271 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002272 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07002273 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002274 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002275 StackHandleScope<1> hs(self);
2276 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002277 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002278 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
2279 h_class->SetPrimitiveType(type);
2280 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002281 const char* descriptor = Primitive::Descriptor(type);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002282 mirror::Class* existing = InsertClass(descriptor, h_class.Get(),
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002283 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002284 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002285 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07002286}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002287
Brian Carlstrombe977852011-07-19 14:54:54 -07002288// Create an array class (i.e. the class object for the array, not the
2289// array itself). "descriptor" looks like "[C" or "[[[[B" or
2290// "[Ljava/lang/String;".
2291//
2292// If "descriptor" refers to an array of primitives, look up the
2293// primitive type's internally-generated class object.
2294//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002295// "class_loader" is the class loader of the class that's referring to
2296// us. It's used to ensure that we're looking for the element type in
2297// the right context. It does NOT become the class loader for the
2298// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002299//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002300// Returns null with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002301mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002302 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002303 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002304 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002305 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002306 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
2307 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002308 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002309 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002310 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002311 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
2312 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002313 if (component_type.Get() == nullptr) {
2314 DCHECK(self->IsExceptionPending());
2315 return nullptr;
2316 } else {
2317 self->ClearException();
2318 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002319 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002320 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2321 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2322 return nullptr;
2323 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002324 // See if the component type is already loaded. Array classes are
2325 // always associated with the class loader of their underlying
2326 // element type -- an array of Strings goes with the loader for
2327 // java/lang/String -- so we need to look for it there. (The
2328 // caller should have checked for the existence of the class
2329 // before calling here, but they did so with *their* class loader,
2330 // not the component type's loader.)
2331 //
2332 // If we find it, the caller adds "loader" to the class' initiating
2333 // loader list, which should prevent us from going through this again.
2334 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002335 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002336 // are the same, because our caller (FindClass) just did the
2337 // lookup. (Even if we get this wrong we still have correct behavior,
2338 // because we effectively do this lookup again when we add the new
2339 // class to the hash table --- necessary because of possible races with
2340 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002341 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002342 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002343 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002344 return new_class;
2345 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002346 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002347
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002348 // Fill out the fields in the Class.
2349 //
2350 // It is possible to execute some methods against arrays, because
2351 // all arrays are subclasses of java_lang_Object_, so we need to set
2352 // up a vtable. We can just point at the one in java_lang_Object_.
2353 //
2354 // Array classes are simple enough that we don't need to do a full
2355 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002356 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002357 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002358 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002359 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002360 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002361 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002362 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002363 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002364 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002365 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002366 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002367 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002368 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002369 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002370 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002371 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002372 } else if (strcmp(descriptor, "[J") == 0) {
2373 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002374 }
2375 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002376 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002377 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002378 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002379 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002380 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002381 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002382 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002383 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002384 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002385 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002386 new_class->SetSuperClass(java_lang_Object);
2387 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002388 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002389 new_class->SetClassLoader(component_type->GetClassLoader());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002390 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002391 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002392 StackHandleScope<mirror::Class::kImtSize> hs2(self,
2393 Runtime::Current()->GetImtUnimplementedMethod());
2394 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002395 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002396 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002397 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002398 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002399
2400
2401 // All arrays have java/lang/Cloneable and java/io/Serializable as
2402 // interfaces. We need to set that up here, so that stuff like
2403 // "instanceof" works right.
2404 //
2405 // Note: The GC could run during the call to FindSystemClass,
2406 // so we need to make sure the class object is GC-valid while we're in
2407 // there. Do this by clearing the interface list so the GC will just
2408 // think that the entries are null.
2409
2410
2411 // Use the single, global copies of "interfaces" and "iftable"
2412 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002413 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002414 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002415 CHECK(array_iftable != nullptr);
2416 new_class->SetIfTable(array_iftable);
2417 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002418
Elliott Hughes00626c22013-06-14 15:04:14 -07002419 // Inherit access flags from the component type.
2420 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2421 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2422 access_flags &= kAccJavaFlagsMask;
2423 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002424 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002425 access_flags |= kAccAbstract | kAccFinal;
2426 access_flags &= ~kAccInterface;
2427
2428 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002429
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002430 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002431 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002432 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002433 }
2434 // Another thread must have loaded the class after we
2435 // started but before we finished. Abandon what we've
2436 // done.
2437 //
2438 // (Yes, this happens.)
2439
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002440 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002441}
2442
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002443mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002444 switch (type) {
2445 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002446 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002447 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002448 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002449 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002450 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002451 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002452 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002453 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002454 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002455 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002456 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002457 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002458 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002459 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002460 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002461 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002462 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002463 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002464 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002465 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002466 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002467 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002468 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002469}
2470
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002471mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2472 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002473 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002474 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002475 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002476 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08002477 source += " from ";
2478 source += dex_cache->GetLocation()->ToModifiedUtf8();
2479 }
2480 LOG(INFO) << "Loaded class " << descriptor << source;
2481 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002482 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002483 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002484 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002485 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002486 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002487 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002488 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002489 // Check a class loaded with the system class loader matches one in the image if the class
2490 // is in the image.
2491 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002492 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002493 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002494 }
2495 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002496 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002497 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002498 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002499 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002500 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002501 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002502}
2503
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002504mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
2505 size_t hash) {
2506 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002507 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
2508 hash);
2509 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002510 CHECK(klass->IsProxyClass());
2511 return nullptr;
2512 }
2513
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002514 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002515 CHECK_NE(existing, klass) << descriptor;
2516 CHECK(!existing->IsResolved()) << descriptor;
2517 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
2518
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002519 CHECK(!klass->IsTemp()) << descriptor;
2520 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
2521 dex_cache_image_class_lookup_required_) {
2522 // Check a class loaded with the system class loader matches one in the image if the class
2523 // is in the image.
2524 existing = LookupClassFromImage(descriptor);
2525 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002526 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002527 }
2528 }
2529 VerifyObject(klass);
2530
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002531 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002532 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002533 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002534 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002535 }
2536
2537 return existing;
2538}
2539
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002540bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002541 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002542 auto pair = std::make_pair(descriptor, class_loader);
2543 auto it = class_table_.Find(pair);
2544 if (it != class_table_.end()) {
2545 class_table_.Erase(it);
2546 return true;
2547 }
2548 it = pre_zygote_class_table_.Find(pair);
2549 if (it != pre_zygote_class_table_.end()) {
2550 pre_zygote_class_table_.Erase(it);
2551 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08002552 }
2553 return false;
2554}
2555
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002556mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002557 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002558 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002559 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002560 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002561 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002562 return result;
2563 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07002564 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002565 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
2566 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002567 } else {
2568 // Lookup failed but need to search dex_caches_.
2569 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002570 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002571 InsertClass(descriptor, result, hash);
2572 } else {
2573 // Searching the image dex files/caches failed, we don't want to get into this situation
2574 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2575 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07002576 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002577 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2578 MoveImageClassesToClassTable();
2579 }
2580 }
2581 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002582 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002583}
2584
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002585mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002586 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002587 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002588 auto descriptor_pair = std::make_pair(descriptor, class_loader);
2589 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
2590 if (it == pre_zygote_class_table_.end()) {
2591 it = class_table_.FindWithHash(descriptor_pair, hash);
2592 if (it == class_table_.end()) {
2593 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07002594 }
2595 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002596 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002597}
2598
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002599static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
2600 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2601 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002602 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002603 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2604 return root->AsObjectArray<mirror::DexCache>();
2605}
2606
2607void ClassLinker::MoveImageClassesToClassTable() {
2608 Thread* self = Thread::Current();
2609 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2610 if (!dex_cache_image_class_lookup_required_) {
2611 return; // All dex cache classes are already in the class table.
2612 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002613 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002614 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002615 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002616 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2617 mirror::DexCache* dex_cache = dex_caches->Get(i);
2618 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
2619 for (int32_t j = 0; j < types->GetLength(); j++) {
2620 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002621 if (klass != nullptr) {
2622 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002623 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002624 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002625 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
2626 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002627 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002628 << PrettyClassAndClassLoader(klass);
2629 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002630 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002631 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002632 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002633 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002634 }
2635 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002636 }
2637 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002638 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002639}
2640
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002641void ClassLinker::MoveClassTableToPreZygote() {
2642 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2643 DCHECK(pre_zygote_class_table_.Empty());
2644 pre_zygote_class_table_ = std::move(class_table_);
2645 class_table_.Clear();
2646}
2647
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002648mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002649 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002650 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2651 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
2652 mirror::DexCache* dex_cache = dex_caches->Get(i);
2653 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00002654 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002655 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002656 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002657 const DexFile::TypeId* type_id =
2658 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002659 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002660 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
2661 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002662 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002663 return klass;
2664 }
2665 }
2666 }
2667 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002668 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002669}
2670
2671void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
2672 result.clear();
2673 if (dex_cache_image_class_lookup_required_) {
2674 MoveImageClassesToClassTable();
2675 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002676 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2677 while (true) {
2678 auto it = class_table_.Find(descriptor);
2679 if (it == class_table_.end()) {
2680 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002681 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002682 result.push_back(it->Read());
2683 class_table_.Erase(it);
2684 }
2685 for (mirror::Class* k : result) {
2686 class_table_.Insert(GcRoot<mirror::Class>(k));
2687 }
2688 size_t pre_zygote_start = result.size();
2689 // Now handle the pre zygote table.
2690 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
2691 // called from the debugger.
2692 while (true) {
2693 auto it = pre_zygote_class_table_.Find(descriptor);
2694 if (it == pre_zygote_class_table_.end()) {
2695 break;
2696 }
2697 result.push_back(it->Read());
2698 pre_zygote_class_table_.Erase(it);
2699 }
2700 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
2701 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002702 }
2703}
2704
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002705void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002706 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002707 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08002708
Ian Rogers9ffb0392012-09-10 11:56:50 -07002709 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002710 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07002711 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07002712 return;
2713 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002714 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002715 return;
2716 }
jeffhao98eacac2011-09-14 16:11:53 -07002717
Ian Rogers9ffb0392012-09-10 11:56:50 -07002718 // The class might already be erroneous, for example at compile time if we attempted to verify
2719 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002720 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002721 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002722 return;
2723 }
2724
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002725 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002726 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002727 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002728 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002729 << PrettyClass(klass.Get());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002730 CHECK(!Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002731 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002732 }
jeffhao98eacac2011-09-14 16:11:53 -07002733
Jeff Hao4a200f52014-04-01 14:58:49 -07002734 // Skip verification if disabled.
2735 if (!Runtime::Current()->IsVerificationEnabled()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002736 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07002737 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07002738 return;
2739 }
2740
Ian Rogers9ffb0392012-09-10 11:56:50 -07002741 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002742 StackHandleScope<2> hs(self);
2743 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002744 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07002745 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002746 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002747
2748 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002749 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002750 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002751 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07002752 std::string error_msg(
2753 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
2754 PrettyDescriptor(klass.Get()).c_str(),
2755 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08002756 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002757 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002758 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002759 self->ClearException();
2760 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002761 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
2762 if (cause.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002763 self->GetException()->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002764 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08002765 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002766 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00002767 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
2768 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002769 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002770 return;
2771 }
2772 }
2773
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002774 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07002775 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002776 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002777 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002778 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002779 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002780 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002781 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002782 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
2783 PrettyDescriptor(klass.Get()).c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002784 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07002785 return;
2786 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002787 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08002788 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07002789 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002790 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002791 Runtime::Current()->IsAotCompiler(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002792 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002793 }
2794 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07002795 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002796 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07002797 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2798 << " because: " << error_msg;
2799 }
Ian Rogers1f539342012-10-03 21:09:42 -07002800 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002801 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002802 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002803 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002804 // Even though there were no verifier failures we need to respect whether the super-class
2805 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002806 if (super.Get() == nullptr || super->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002807 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002808 } else {
2809 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002810 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002811 // Pretend a soft failure occured so that we don't consider the class verified below.
2812 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002813 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002814 } else {
2815 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
2816 // Soft failures at compile time should be retried at runtime. Soft
2817 // failures at runtime will be handled by slow paths in the generated
2818 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002819 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002820 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002821 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002822 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002823 // As this is a fake verified status, make sure the methods are _not_ marked preverified
2824 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07002825 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002826 }
2827 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07002828 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002829 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08002830 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2831 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002832 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002833 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002834 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002835 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002836 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002837 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002838 // Let the interpreter know it by setting the kAccPreverified flag onto each
2839 // method.
2840 // Note: we're going here during compilation and at runtime. When we set the
2841 // kAccPreverified flag when compiling image classes, the flag is recorded
2842 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07002843 EnsurePreverifiedMethods(klass);
2844 }
2845}
2846
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002847void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002848 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002849 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07002850 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002851 }
jeffhao98eacac2011-09-14 16:11:53 -07002852}
2853
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002854bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
2855 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002856 // If we're compiling, we can only verify the class using the oat file if
2857 // we are not compiling the image or if the class we're verifying is not part of
2858 // the app. In other words, we will only check for preverification of bootclasspath
2859 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002860 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002861 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002862 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002863 return false;
2864 }
2865 // We are compiling an app (not the image).
2866
2867 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002868 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002869 return false;
2870 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002871 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002872
Richard Uhler07b3c232015-03-31 15:57:54 -07002873 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002874 // In case we run without an image there won't be a backing oat file.
2875 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07002876 return false;
2877 }
2878
Andreas Gampe76bd8802014-12-10 16:43:58 -08002879 // We may be running with a preopted oat file but without image. In this case,
2880 // we don't skip verification of preverified classes to ensure we initialize
2881 // dex caches with all types resolved during verification.
2882 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
2883 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
2884 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
2885 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002886 if (!Runtime::Current()->IsAotCompiler() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08002887 !Runtime::Current()->GetHeap()->HasImageSpace() &&
2888 klass->GetClassLoader() != nullptr) {
2889 return false;
2890 }
2891
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002892 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002893 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002894 if (oat_file_class_status == mirror::Class::kStatusVerified ||
2895 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002896 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002897 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002898 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07002899 // Compile time verification failed with a soft error. Compile time verification can fail
2900 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08002901 // class ... {
2902 // Foo x;
2903 // .... () {
2904 // if (...) {
2905 // v1 gets assigned a type of resolved class Foo
2906 // } else {
2907 // v1 gets assigned a type of unresolved class Bar
2908 // }
2909 // iput x = v1
2910 // } }
2911 // when we merge v1 following the if-the-else it results in Conflict
2912 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2913 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2914 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2915 // at compile time).
2916 return false;
2917 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002918 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07002919 // Compile time verification failed with a hard error. This is caused by invalid instructions
2920 // in the class. These errors are unrecoverable.
2921 return false;
2922 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002923 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002924 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2925 // not loading the class.
2926 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2927 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002928 return false;
2929 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002930 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002931 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002932 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07002933 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08002934 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002935}
2936
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002937void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002938 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002939 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2940 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2941 }
2942 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2943 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2944 }
2945}
2946
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002947void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07002948 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002949 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2950 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002951 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002952 return; // native or abstract method
2953 }
2954 if (code_item->tries_size_ == 0) {
2955 return; // nothing to process
2956 }
Ian Rogers13735952014-10-08 12:43:28 -07002957 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002958 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2959 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2960 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2961 CatchHandlerIterator iterator(handlers_ptr);
2962 for (; iterator.HasNext(); iterator.Next()) {
2963 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2964 // unresolved exception types will be ignored by exception delivery
2965 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002966 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002967 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002968 DCHECK(Thread::Current()->IsExceptionPending());
2969 Thread::Current()->ClearException();
2970 }
2971 }
2972 }
2973 handlers_ptr = iterator.EndDataPointer();
2974 }
2975}
2976
Brian Carlstromea46f952013-07-30 01:26:50 -07002977static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002978static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
2979 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08002980
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07002981mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07002982 jobjectArray interfaces, jobject loader,
2983 jobjectArray methods, jobjectArray throws) {
2984 Thread* self = soa.Self();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07002985 StackHandleScope<9> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002986 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002987 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002988 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002989 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002990 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002991 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002992 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002993 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07002994 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
2995 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002996 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08002997 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002998 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002999 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003000 klass->SetDexCache(proxy_class->GetDexCache());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003001 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003002
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003003 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07003004 const size_t num_fields = 2;
3005 ArtField* sfields = AllocArtFieldArray(self, num_fields);
3006 klass->SetSFields(sfields);
3007 klass->SetNumStaticFields(num_fields);
3008
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003009 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3010 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartierc7853442015-03-27 14:35:38 -07003011 ArtField* interfaces_sfield = &sfields[0];
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003012 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003013 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003014 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003015
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003016 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartierc7853442015-03-27 14:35:38 -07003017 ArtField* throws_sfield = &sfields[1];
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003018 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003019 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003020 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003021
Ian Rogers466bb252011-10-14 03:29:56 -07003022 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003023 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003024 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003025 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003026 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003027 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003028 }
3029 klass->SetDirectMethods(directs);
3030 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003031 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003032 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003033 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003034 }
3035 klass->SetDirectMethod(0, constructor);
3036 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003037
Mathieu Chartier590fee92013-09-13 13:46:47 -07003038 // Create virtual method using specified prototypes.
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003039 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>*>(methods));
3040 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
3041 << PrettyClass(h_methods->GetClass());
3042 const size_t num_virtual_methods = h_methods->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003043 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003044 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3045 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003046 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003047 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003048 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003049 }
3050 klass->SetVirtualMethods(virtuals);
3051 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003052 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003053 StackHandleScope<1> hs2(self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003054 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(h_methods->Get(i)->GetArtMethod()));
Ian Rogersa436fde2013-08-27 23:34:06 -07003055 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003056 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003057 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003058 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003059 }
3060 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003061 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003062
3063 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003064 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003065 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003066
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003067 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3068 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003069 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003070 // Must hold lock on object when resolved.
3071 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003072 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003073 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003074 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003075 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003076 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003077 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003078 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003079 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003080
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003081 CHECK(klass->IsRetired());
3082 CHECK_NE(klass.Get(), new_class);
3083 klass.Assign(new_class);
3084
3085 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003086 interfaces_sfield->SetObject<false>(klass.Get(),
3087 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003088 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003089 throws_sfield->SetObject<false>(klass.Get(),
3090 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003091
3092 {
3093 // Lock on klass is released. Lock new class object.
3094 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003095 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003096 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003097
3098 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003099 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003100 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003101 CheckProxyConstructor(klass->GetDirectMethod(0));
3102 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003103 StackHandleScope<2> hs2(self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003104 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(h_methods->Get(i)->GetArtMethod()));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003105 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003106 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003107 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003108
Mathieu Chartier590fee92013-09-13 13:46:47 -07003109 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003110 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003111 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003112 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3113
3114 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003115 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003116 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003117
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003118 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003119 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003120 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003121 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003122 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003123 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3124 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003125 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003126 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003127}
3128
Ian Rogersef7d42f2014-01-06 12:55:46 -08003129std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003130 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003131 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003132 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003133 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3134}
3135
Ian Rogersef7d42f2014-01-06 12:55:46 -08003136mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3137 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003138 DCHECK(proxy_class->IsProxyClass());
3139 DCHECK(proxy_method->IsProxyMethod());
Ian Rogers16f93672012-02-14 12:29:06 -08003140 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003141 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003142 // Locate the dex cache of the original interface/Object
3143 for (const GcRoot<mirror::DexCache>& root : dex_caches_) {
3144 auto* dex_cache = root.Read();
3145 if (proxy_method->HasSameDexCacheResolvedTypes(dex_cache->GetResolvedTypes())) {
3146 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(
3147 proxy_method->GetDexMethodIndex());
3148 CHECK(resolved_method != nullptr);
3149 return resolved_method;
Ian Rogers16f93672012-02-14 12:29:06 -08003150 }
3151 }
3152 }
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003153 LOG(FATAL) << "Didn't find dex cache for " << PrettyClass(proxy_class) << " "
3154 << PrettyMethod(proxy_method);
3155 UNREACHABLE();
Ian Rogers16f93672012-02-14 12:29:06 -08003156}
3157
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003158
Brian Carlstromea46f952013-07-30 01:26:50 -07003159mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003160 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003161 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003162 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003163 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003164 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003165 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3166 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003167 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3168 // constructor method.
3169 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3170 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003171 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3172 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003173 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3174 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003175 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003176 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003177 }
Ian Rogers466bb252011-10-14 03:29:56 -07003178 // Make this constructor public and fix the class to be our Proxy version
3179 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003180 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003181 return constructor;
3182}
3183
Brian Carlstromea46f952013-07-30 01:26:50 -07003184static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003185 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003186 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003187 CHECK_STREQ(constructor->GetName(), "<init>");
3188 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3189 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003190 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003191}
3192
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003193mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003194 Handle<mirror::Class> klass,
3195 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003196 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3197 // prototype method
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003198 auto* dex_cache = prototype->GetDeclaringClass()->GetDexCache();
3199 // Avoid dirtying the dex cache unless we need to.
3200 if (dex_cache->GetResolvedMethod(prototype->GetDexMethodIndex()) != prototype.Get()) {
3201 dex_cache->SetResolvedMethod(prototype->GetDexMethodIndex(), prototype.Get());
3202 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003203 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003204 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003205 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003206 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003207 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003208 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003209 }
Ian Rogers466bb252011-10-14 03:29:56 -07003210
3211 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3212 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003213 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003214 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003215
Ian Rogers466bb252011-10-14 03:29:56 -07003216 // At runtime the method looks like a reference and argument saving method, clone the code
3217 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003218 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003219 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003220
Ian Rogersc2b44472011-12-14 21:17:17 -08003221 return method;
3222}
Jesse Wilson95caa792011-10-12 18:14:17 -04003223
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003224static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3225 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003226 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003227 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003228 CHECK(!prototype->IsFinal());
3229 CHECK(method->IsFinal());
3230 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003231
3232 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3233 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07003234 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
3235 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003236 CHECK_EQ(prototype->GetDeclaringClass()->GetDexCache(), method->GetDexCache());
Ian Rogers19846512012-02-24 11:42:47 -08003237 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3238
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003239 CHECK_STREQ(method->GetName(), prototype->GetName());
3240 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003241 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07003242 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04003243}
3244
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003245static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3246 bool can_init_parents)
3247 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003248 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003249 return true;
3250 }
3251 if (!can_init_statics) {
3252 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07003253 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003254 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003255 return false;
3256 }
3257 // Check if there are encoded static values needing initialization.
3258 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003259 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003260 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003261 if (dex_class_def->static_values_off_ != 0) {
3262 return false;
3263 }
3264 }
3265 }
3266 if (!klass->IsInterface() && klass->HasSuperClass()) {
3267 mirror::Class* super_class = klass->GetSuperClass();
3268 if (!can_init_parents && !super_class->IsInitialized()) {
3269 return false;
3270 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003271 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003272 return false;
3273 }
3274 }
3275 }
3276 return true;
3277}
3278
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003279bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07003280 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003281 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3282
3283 // Are we already initialized and therefore done?
3284 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3285 // an initialized class will never change its state.
3286 if (klass->IsInitialized()) {
3287 return true;
3288 }
3289
3290 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003291 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003292 return false;
3293 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003294
Ian Rogers7b078e82014-09-10 14:44:24 -07003295 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003296 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003297 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003298 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003299
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003300 // Re-check under the lock in case another thread initialized ahead of us.
3301 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003302 return true;
3303 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003304
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003305 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003306 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003307 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003308 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003309 return false;
3310 }
3311
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003312 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003313
3314 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003315 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003316 if (!klass->IsVerified()) {
3317 // We failed to verify, expect either the klass to be erroneous or verification failed at
3318 // compile time.
3319 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003320 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003321 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003322 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003323 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003324 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003325 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003326 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07003327 } else {
3328 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003329 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003330 }
3331
Brian Carlstromd1422f82011-09-28 11:37:09 -07003332 // If the class is kStatusInitializing, either this thread is
3333 // initializing higher up the stack or another thread has beat us
3334 // to initializing and we need to wait. Either way, this
3335 // invocation of InitializeClass will not be responsible for
3336 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003337 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07003338 // Could have got an exception during verification.
3339 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003340 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003341 return false;
3342 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003343 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003344 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003345 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003346 return true;
3347 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003348 // No. That's fine. Wait for another thread to finish initializing.
3349 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003350 }
3351
3352 if (!ValidateSuperClassDescriptors(klass)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003353 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003354 return false;
3355 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003356 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003357
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003358 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003359
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003360 // From here out other threads may observe that we're initializing and so changes of state
3361 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003362 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003363 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003364
3365 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003366 }
3367
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003368 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003369 if (!klass->IsInterface() && klass->HasSuperClass()) {
3370 mirror::Class* super_class = klass->GetSuperClass();
3371 if (!super_class->IsInitialized()) {
3372 CHECK(!super_class->IsInterface());
3373 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003374 StackHandleScope<1> hs(self);
3375 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07003376 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003377 if (!super_initialized) {
3378 // The super class was verified ahead of entering initializing, we should only be here if
3379 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003380 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003381 << "Super class initialization failed for "
3382 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003383 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003384 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003385 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003386 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003387 // Initialization failed because the super-class is erroneous.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003388 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003389 return false;
3390 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003391 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003392 }
3393
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003394 const size_t num_static_fields = klass->NumStaticFields();
3395 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003396 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003397 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003398 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07003399 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003400 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003401 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003402
3403 // Eagerly fill in static fields so that the we don't have to do as many expensive
3404 // Class::FindStaticField in ResolveField.
3405 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003406 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003407 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003408 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003409 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003410 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07003411 } else {
3412 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003413 }
3414 }
3415
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003416 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
3417 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07003418 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003419 ClassDataItemIterator field_it(dex_file, class_data);
3420 if (value_it.HasNext()) {
3421 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003422 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003423 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003424 ArtField* field = ResolveField(
3425 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003426 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003427 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003428 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003429 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003430 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003431 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003432 }
3433 }
3434 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003435
Ian Rogersd91d6d62013-09-25 20:26:14 -07003436 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003437 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003438 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003439 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003440 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003441 }
3442
Ian Rogers7b078e82014-09-10 14:44:24 -07003443 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003444 uint64_t t1 = NanoTime();
3445
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003446 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003447 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003448 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003449
3450 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003451 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003452 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003453 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003454 } else if (Runtime::Current()->IsTransactionAborted()) {
3455 // The exception thrown when the transaction aborted has been caught and cleared
3456 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01003457 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
3458 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02003459 Runtime::Current()->ThrowTransactionAbortError(self);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003460 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003461 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003462 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003463 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3464 RuntimeStats* thread_stats = self->GetStats();
3465 ++global_stats->class_init_count;
3466 ++thread_stats->class_init_count;
3467 global_stats->class_init_time_ns += (t1 - t0);
3468 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003469 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003470 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003471 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003472 std::string temp;
3473 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003474 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003475 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003476 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003477 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003478 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003479 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003480 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003481}
3482
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003483bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003484 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003485 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003486 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003487 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003488 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08003489 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003490
3491 // When we wake up, repeat the test for init-in-progress. If
3492 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07003493 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003494 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003495 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003496 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003497 return false;
3498 }
3499 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003500 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003501 continue;
3502 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003503 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
3504 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003505 // Compile time initialization failed.
3506 return false;
3507 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003508 if (klass->IsErroneous()) {
3509 // The caller wants an exception, but it was thrown in a
3510 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003511 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003512 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003513 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003514 return false;
3515 }
3516 if (klass->IsInitialized()) {
3517 return true;
3518 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003519 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003520 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003521 }
Ian Rogers07140832014-09-30 15:43:59 -07003522 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003523}
3524
Ian Rogersb5fb2072014-12-02 17:22:02 -08003525static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
3526 Handle<mirror::ArtMethod> method1,
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003527 Handle<mirror::ArtMethod> method2,
3528 std::string* error_msg)
Ian Rogersb5fb2072014-12-02 17:22:02 -08003529 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3530 {
3531 StackHandleScope<1> hs(self);
3532 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
Vladimir Marko862f43c2015-02-10 18:22:57 +00003533 mirror::Class* other_return_type = method2->GetReturnType();
3534 // NOTE: return_type.Get() must be sequenced after method2->GetReturnType().
3535 if (UNLIKELY(other_return_type != return_type.Get())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003536 *error_msg = StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
3537 PrettyClassAndClassLoader(return_type.Get()).c_str(),
3538 return_type.Get(),
3539 PrettyClassAndClassLoader(other_return_type).c_str(),
3540 other_return_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003541 return false;
3542 }
3543 }
3544 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
3545 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
3546 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003547 if (types2 != nullptr && types2->Size() != 0) {
3548 *error_msg = StringPrintf("Type list mismatch with %s",
3549 PrettyMethod(method2.Get(), true).c_str());
3550 return false;
3551 }
3552 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003553 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003554 if (types1->Size() != 0) {
3555 *error_msg = StringPrintf("Type list mismatch with %s",
3556 PrettyMethod(method2.Get(), true).c_str());
3557 return false;
3558 }
3559 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003560 }
3561 uint32_t num_types = types1->Size();
3562 if (UNLIKELY(num_types != types2->Size())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003563 *error_msg = StringPrintf("Type list mismatch with %s",
3564 PrettyMethod(method2.Get(), true).c_str());
Ian Rogersb5fb2072014-12-02 17:22:02 -08003565 return false;
3566 }
3567 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00003568 StackHandleScope<1> hs(self);
3569 Handle<mirror::Class> param_type(hs.NewHandle(
3570 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true)));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003571 mirror::Class* other_param_type =
3572 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
Vladimir Marko862f43c2015-02-10 18:22:57 +00003573 // NOTE: param_type.Get() must be sequenced after method2->GetClassFromTypeIndex(...).
3574 if (UNLIKELY(param_type.Get() != other_param_type)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003575 *error_msg = StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
3576 i,
3577 PrettyClassAndClassLoader(param_type.Get()).c_str(),
3578 param_type.Get(),
3579 PrettyClassAndClassLoader(other_param_type).c_str(),
3580 other_param_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003581 return false;
3582 }
3583 }
3584 return true;
3585}
3586
3587
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003588bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003589 if (klass->IsInterface()) {
3590 return true;
3591 }
Ian Rogers151f2212014-05-06 11:27:27 -07003592 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07003593 Thread* self = Thread::Current();
3594 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003595 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
3596 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003597 if (klass->HasSuperClass() &&
3598 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003599 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003600 h_m.Assign(klass->GetVTableEntry(i));
3601 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003602 if (h_m.Get() != super_h_m.Get()) {
3603 std::string error_msg;
3604 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3605 ThrowLinkageError(klass.Get(),
3606 "Class %s method %s resolves differently in superclass %s: %s",
3607 PrettyDescriptor(klass.Get()).c_str(),
3608 PrettyMethod(h_m.Get()).c_str(),
3609 PrettyDescriptor(klass->GetSuperClass()).c_str(),
3610 error_msg.c_str());
3611 return false;
3612 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003613 }
3614 }
3615 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003616 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07003617 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
3618 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
3619 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003620 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
3621 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003622 if (h_m.Get() != super_h_m.Get()) {
3623 std::string error_msg;
3624 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3625 ThrowLinkageError(klass.Get(),
3626 "Class %s method %s resolves differently in interface %s: %s",
3627 PrettyDescriptor(klass.Get()).c_str(),
3628 PrettyMethod(h_m.Get()).c_str(),
3629 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str(),
3630 error_msg.c_str());
3631 return false;
3632 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003633 }
3634 }
3635 }
3636 }
3637 return true;
3638}
3639
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003640bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
3641 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003642 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003643 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003644 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003645 return true;
3646 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003647 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003648 if (!success) {
3649 if (can_init_fields && can_init_parents) {
3650 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
3651 }
3652 } else {
3653 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08003654 }
3655 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003656}
3657
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003658void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003659 ArtField* fields = new_class->GetIFields();
3660 for (size_t i = 0, count = new_class->NumInstanceFields(); i < count; i++) {
3661 if (fields[i].GetDeclaringClass() == temp_class) {
3662 fields[i].SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003663 }
3664 }
3665
3666 fields = new_class->GetSFields();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003667 for (size_t i = 0, count = new_class->NumStaticFields(); i < count; i++) {
3668 if (fields[i].GetDeclaringClass() == temp_class) {
3669 fields[i].SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003670 }
3671 }
3672
3673 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
3674 if (methods != nullptr) {
3675 for (int index = 0; index < methods->GetLength(); index ++) {
3676 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3677 methods->Get(index)->SetDeclaringClass(new_class);
3678 }
3679 }
3680 }
3681
3682 methods = new_class->GetVirtualMethods();
3683 if (methods != nullptr) {
3684 for (int index = 0; index < methods->GetLength(); index ++) {
3685 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3686 methods->Get(index)->SetDeclaringClass(new_class);
3687 }
3688 }
3689 }
3690}
3691
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003692bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
3693 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003694 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003695 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003696
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003697 if (!LinkSuperClass(klass)) {
3698 return false;
3699 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003700 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
3701 self, Runtime::Current()->GetImtUnimplementedMethod());
3702 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003703 return false;
3704 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003705 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003706 return false;
3707 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003708 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07003709 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003710 return false;
3711 }
3712 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003713 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003714
3715 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
3716 // We don't need to retire this class as it has no embedded tables or it was created the
3717 // correct size during class linker initialization.
3718 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
3719
3720 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003721 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003722 }
3723
3724 // This will notify waiters on klass that saw the not yet resolved
3725 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003726 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003727 *new_class = klass.Get();
3728 } else {
3729 CHECK(!klass->IsResolved());
3730 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003731 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003732 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003733 CHECK(self->IsExceptionPending()); // Expect an OOME.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003734 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003735 return false;
3736 }
3737
3738 CHECK_EQ((*new_class)->GetClassSize(), class_size);
3739 StackHandleScope<1> hs(self);
3740 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
3741 ObjectLock<mirror::Class> lock(self, new_class_h);
3742
3743 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
3744
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003745 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
3746 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003747 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003748
3749 // This will notify waiters on temp class that saw the not yet resolved class in the
3750 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003751 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003752
3753 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
3754 // This will notify waiters on new_class that saw the not yet resolved
3755 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003756 mirror::Class::SetStatus(new_class_h, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003757 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003758 return true;
3759}
3760
Andreas Gampefd9eb392014-11-06 16:52:58 -08003761static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
3762 size_t* virtual_methods,
3763 size_t* direct_methods,
3764 size_t* static_fields,
3765 size_t* instance_fields) {
3766 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
3767
3768 while (dex_data.HasNextStaticField()) {
3769 dex_data.Next();
3770 (*static_fields)++;
3771 }
3772 while (dex_data.HasNextInstanceField()) {
3773 dex_data.Next();
3774 (*instance_fields)++;
3775 }
3776 while (dex_data.HasNextDirectMethod()) {
3777 (*direct_methods)++;
3778 dex_data.Next();
3779 }
3780 while (dex_data.HasNextVirtualMethod()) {
3781 (*virtual_methods)++;
3782 dex_data.Next();
3783 }
3784 DCHECK(!dex_data.HasNext());
3785}
3786
3787static void DumpClass(std::ostream& os,
3788 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
3789 const char* suffix) {
3790 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
3791 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
3792 os << " Static fields:\n";
3793 while (dex_data.HasNextStaticField()) {
3794 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3795 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3796 dex_data.Next();
3797 }
3798 os << " Instance fields:\n";
3799 while (dex_data.HasNextInstanceField()) {
3800 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3801 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3802 dex_data.Next();
3803 }
3804 os << " Direct methods:\n";
3805 while (dex_data.HasNextDirectMethod()) {
3806 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3807 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3808 dex_data.Next();
3809 }
3810 os << " Virtual methods:\n";
3811 while (dex_data.HasNextVirtualMethod()) {
3812 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3813 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3814 dex_data.Next();
3815 }
3816}
3817
3818static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3819 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
3820 std::ostringstream os;
3821 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
3822 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
3823 return os.str();
3824}
3825
3826
3827// Very simple structural check on whether the classes match. Only compares the number of
3828// methods and fields.
3829static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3830 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
3831 std::string* error_msg) {
3832 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
3833 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
3834
3835 // Counters for current dex file.
3836 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
3837 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
3838 &dex_instance_fields1);
3839 // Counters for compile-time dex file.
3840 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
3841 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
3842 &dex_instance_fields2);
3843
3844 if (dex_virtual_methods1 != dex_virtual_methods2) {
3845 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3846 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
3847 dex_virtual_methods2, class_dump.c_str());
3848 return false;
3849 }
3850 if (dex_direct_methods1 != dex_direct_methods2) {
3851 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3852 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
3853 dex_direct_methods2, class_dump.c_str());
3854 return false;
3855 }
3856 if (dex_static_fields1 != dex_static_fields2) {
3857 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3858 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
3859 dex_static_fields2, class_dump.c_str());
3860 return false;
3861 }
3862 if (dex_instance_fields1 != dex_instance_fields2) {
3863 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3864 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
3865 dex_instance_fields2, class_dump.c_str());
3866 return false;
3867 }
3868
3869 return true;
3870}
3871
3872// Checks whether a the super-class changed from what we had at compile-time. This would
3873// invalidate quickening.
3874static bool CheckSuperClassChange(Handle<mirror::Class> klass,
3875 const DexFile& dex_file,
3876 const DexFile::ClassDef& class_def,
3877 mirror::Class* super_class)
3878 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3879 // Check for unexpected changes in the superclass.
3880 // Quick check 1) is the super_class class-loader the boot class loader? This always has
3881 // precedence.
3882 if (super_class->GetClassLoader() != nullptr &&
3883 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
3884 // which is implied by different dex cache.
3885 klass->GetDexCache() != super_class->GetDexCache()) {
3886 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
3887 // definition for the super-class, and (b) the files are in separate oat files. The oat files
3888 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
Richard Uhler07b3c232015-03-31 15:57:54 -07003889 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
3890 const OatFile* class_oat_file = nullptr;
3891 if (class_oat_dex_file != nullptr) {
3892 class_oat_file = class_oat_dex_file->GetOatFile();
3893 }
3894
Andreas Gampefd9eb392014-11-06 16:52:58 -08003895 if (class_oat_file != nullptr) {
Richard Uhler07b3c232015-03-31 15:57:54 -07003896 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
3897 const OatFile* loaded_super_oat_file = nullptr;
3898 if (loaded_super_oat_dex_file != nullptr) {
3899 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
3900 }
3901
Andreas Gampefd9eb392014-11-06 16:52:58 -08003902 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
3903 // Now check (a).
3904 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
3905 if (super_class_def != nullptr) {
3906 // Uh-oh, we found something. Do our check.
3907 std::string error_msg;
3908 if (!SimpleStructuralCheck(dex_file, *super_class_def,
3909 super_class->GetDexFile(), *super_class->GetClassDef(),
3910 &error_msg)) {
3911 // Print a warning to the log. This exception might be caught, e.g., as common in test
3912 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
3913 // only save the type of the exception.
3914 LOG(WARNING) << "Incompatible structural change detected: " <<
3915 StringPrintf(
3916 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3917 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3918 class_oat_file->GetLocation().c_str(),
3919 loaded_super_oat_file->GetLocation().c_str(),
3920 error_msg.c_str());
3921 ThrowIncompatibleClassChangeError(klass.Get(),
3922 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3923 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3924 class_oat_file->GetLocation().c_str(),
3925 loaded_super_oat_file->GetLocation().c_str(),
3926 error_msg.c_str());
3927 return false;
3928 }
3929 }
3930 }
3931 }
3932 }
3933 return true;
3934}
3935
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003936bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003937 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003938 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3939 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003940 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003941 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003942 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003943 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003944 return false;
3945 }
Ian Rogersbe125a92012-01-11 15:19:49 -08003946 // Verify
3947 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003948 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003949 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003950 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08003951 return false;
3952 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003953 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003954 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08003955
3956 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
3957 DCHECK(Thread::Current()->IsExceptionPending());
3958 return false;
3959 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003960 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003961 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003962 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003963 for (size_t i = 0; i < interfaces->Size(); i++) {
3964 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003965 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003966 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003967 DCHECK(Thread::Current()->IsExceptionPending());
3968 return false;
3969 }
3970 // Verify
3971 if (!klass->CanAccess(interface)) {
3972 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003973 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003974 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003975 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003976 return false;
3977 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003978 }
3979 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003980 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003981 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003982 return true;
3983}
3984
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003985bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003986 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003987 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003988 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003989 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003990 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003991 return false;
3992 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003993 return true;
3994 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003995 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003996 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
3997 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003998 return false;
3999 }
4000 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004001 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004002 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004003 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004004 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004005 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004006 return false;
4007 }
4008 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004009 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004010 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004011 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004012 return false;
4013 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004014
Brian Carlstromf3632832014-05-20 15:36:53 -07004015 // Inherit kAccClassIsFinalizable from the superclass in case this
4016 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004017 if (super->IsFinalizable()) {
4018 klass->SetFinalizable();
4019 }
4020
Elliott Hughes2da50362011-10-10 16:57:08 -07004021 // Inherit reference flags (if any) from the superclass.
4022 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4023 if (reference_flags != 0) {
4024 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4025 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004026 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004027 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004028 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004029 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004030 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004031 return false;
4032 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004033
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004034 if (kIsDebugBuild) {
4035 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004036 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004037 CHECK(super->IsResolved());
4038 super = super->GetSuperClass();
4039 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004040 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004041 return true;
4042}
4043
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004044// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004045bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004046 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4047 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004048 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004049 if (klass->IsInterface()) {
4050 // No vtable.
4051 size_t count = klass->NumVirtualMethods();
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004052 if (!IsUint<16>(count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004053 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004054 return false;
4055 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004056 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004057 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004058 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004059 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4060 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004061 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004062 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004063}
4064
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004065// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4066// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4067// caches in the implementation below.
4068class MethodNameAndSignatureComparator FINAL : public ValueObject {
4069 public:
4070 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4071 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4072 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4073 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004074 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4075 }
4076
4077 const char* GetName() {
4078 if (name_ == nullptr) {
4079 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4080 }
4081 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004082 }
4083
4084 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4085 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4086 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4087 const DexFile* other_dex_file = other->GetDexFile();
4088 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4089 if (dex_file_ == other_dex_file) {
4090 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4091 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004092 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004093 uint32_t other_name_len;
4094 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4095 &other_name_len);
4096 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4097 return false;
4098 }
4099 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4100 }
4101
4102 private:
4103 // Dex file for the method to compare against.
4104 const DexFile* const dex_file_;
4105 // MethodId for the method to compare against.
4106 const DexFile::MethodId* const mid_;
4107 // Lazily computed name from the dex file's strings.
4108 const char* name_;
4109 // Lazily computed name length.
4110 uint32_t name_len_;
4111};
4112
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004113class LinkVirtualHashTable {
4114 public:
4115 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4116 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4117 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4118 }
4119 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4120 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4121 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004122 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004123 uint32_t index = hash % hash_size_;
4124 // Linear probe until we have an empty slot.
4125 while (hash_table_[index] != invalid_index_) {
4126 if (++index == hash_size_) {
4127 index = 0;
4128 }
4129 }
4130 hash_table_[index] = virtual_method_index;
4131 }
4132 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4133 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4134 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004135 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004136 size_t index = hash % hash_size_;
4137 while (true) {
4138 const uint32_t value = hash_table_[index];
4139 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4140 // the block and can safely assume not found.
4141 if (value == invalid_index_) {
4142 break;
4143 }
4144 if (value != removed_index_) { // This signifies not already overriden.
4145 mirror::ArtMethod* virtual_method =
4146 klass_->GetVirtualMethodDuringLinking(value);
4147 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4148 hash_table_[index] = removed_index_;
4149 return value;
4150 }
4151 }
4152 if (++index == hash_size_) {
4153 index = 0;
4154 }
4155 }
4156 return GetNotFoundIndex();
4157 }
4158 static uint32_t GetNotFoundIndex() {
4159 return invalid_index_;
4160 }
4161
4162 private:
4163 static const uint32_t invalid_index_;
4164 static const uint32_t removed_index_;
4165
4166 Handle<mirror::Class> klass_;
4167 const size_t hash_size_;
4168 uint32_t* const hash_table_;
4169};
4170
4171const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4172const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4173
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004174bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004175 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004176 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004177 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4178 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004179 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004180 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004181 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004182 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4183 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4184 if (UNLIKELY(vtable.Get() == nullptr)) {
4185 CHECK(self->IsExceptionPending()); // OOME.
4186 return false;
4187 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004188 for (size_t i = 0; i < super_vtable_length; i++) {
4189 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004190 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004191 if (num_virtual_methods == 0) {
4192 klass->SetVTable(vtable.Get());
4193 return true;
4194 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004195 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004196 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4197 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4198 if (num_virtual_methods == 0) {
4199 klass->SetVTable(super_vtable);
4200 return true;
4201 }
4202 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004203 if (UNLIKELY(vtable.Get() == nullptr)) {
4204 CHECK(self->IsExceptionPending()); // OOME.
4205 return false;
4206 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004207 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004208 // How the algorithm works:
4209 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4210 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4211 // method which has not been matched to a vtable method, and j if the virtual method at the
4212 // index overrode the super virtual method at index j.
4213 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4214 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4215 // the need for the initial vtable which we later shrink back down).
4216 // 3. Add non overridden methods to the end of the vtable.
4217 static constexpr size_t kMaxStackHash = 250;
4218 const size_t hash_table_size = num_virtual_methods * 3;
4219 uint32_t* hash_table_ptr;
4220 std::unique_ptr<uint32_t[]> hash_heap_storage;
4221 if (hash_table_size <= kMaxStackHash) {
4222 hash_table_ptr = reinterpret_cast<uint32_t*>(
4223 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4224 } else {
4225 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4226 hash_table_ptr = hash_heap_storage.get();
4227 }
4228 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4229 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004230 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004231 hash_table.Add(i);
4232 }
4233 // Loop through each super vtable method and see if they are overriden by a method we added to
4234 // the hash table.
4235 for (size_t j = 0; j < super_vtable_length; ++j) {
4236 // Search the hash table to see if we are overidden by any method.
4237 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4238 MethodNameAndSignatureComparator super_method_name_comparator(
4239 super_method->GetInterfaceMethodIfProxy());
4240 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4241 if (hash_index != hash_table.GetNotFoundIndex()) {
4242 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4243 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4244 super_method->GetAccessFlags())) {
4245 if (super_method->IsFinal()) {
4246 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4247 PrettyMethod(virtual_method).c_str(),
4248 super_method->GetDeclaringClassDescriptor());
4249 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004250 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004251 vtable->SetWithoutChecks<false>(j, virtual_method);
4252 virtual_method->SetMethodIndex(j);
4253 } else {
4254 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004255 << " would have incorrectly overridden the package-private method in "
4256 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004257 }
4258 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004259 }
4260 // Add the non overridden methods at the end.
4261 size_t actual_count = super_vtable_length;
4262 for (size_t i = 0; i < num_virtual_methods; ++i) {
4263 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4264 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4265 if (method_idx < super_vtable_length &&
4266 local_method == vtable->GetWithoutChecks(method_idx)) {
4267 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004268 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004269 vtable->SetWithoutChecks<false>(actual_count, local_method);
4270 local_method->SetMethodIndex(actual_count);
4271 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004272 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004273 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004274 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004275 return false;
4276 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004277 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004278 CHECK_LE(actual_count, max_count);
4279 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004280 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004281 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004282 CHECK(self->IsExceptionPending()); // OOME.
4283 return false;
4284 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004285 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004286 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004287 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004288 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004289 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004290 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4291 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004292 return false;
4293 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004294 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4295 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004296 CHECK(self->IsExceptionPending()); // OOME.
4297 return false;
4298 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004299 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004300 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004301 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004302 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004303 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004304 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004305 }
4306 return true;
4307}
4308
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004309bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4310 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4311 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004312 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004313 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004314 const bool has_superclass = klass->HasSuperClass();
4315 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4316 const bool have_interfaces = interfaces.Get() != nullptr;
4317 const size_t num_interfaces =
4318 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4319 if (num_interfaces == 0) {
4320 if (super_ifcount == 0) {
4321 // Class implements no interfaces.
4322 DCHECK_EQ(klass->GetIfTableCount(), 0);
4323 DCHECK(klass->GetIfTable() == nullptr);
4324 return true;
4325 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004326 // Class implements same interfaces as parent, are any of these not marker interfaces?
4327 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004328 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004329 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004330 if (super_iftable->GetMethodArrayCount(i) > 0) {
4331 has_non_marker_interface = true;
4332 break;
4333 }
4334 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004335 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004336 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004337 klass->SetIfTable(super_iftable);
4338 return true;
4339 }
4340 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004341 size_t ifcount = super_ifcount + num_interfaces;
4342 for (size_t i = 0; i < num_interfaces; i++) {
4343 mirror::Class* interface = have_interfaces ?
4344 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4345 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004346 if (UNLIKELY(!interface->IsInterface())) {
4347 std::string temp;
4348 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4349 PrettyDescriptor(klass.Get()).c_str(),
4350 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4351 return false;
4352 }
4353 ifcount += interface->GetIfTableCount();
4354 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004355 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004356 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004357 CHECK(self->IsExceptionPending()); // OOME.
4358 return false;
4359 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004360 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004361 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004362 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004363 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004364 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004365 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004366 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004367 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004368 // Flatten the interface inheritance hierarchy.
4369 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004370 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004371 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4372 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004373 // Check if interface is already in iftable
4374 bool duplicate = false;
4375 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004376 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004377 if (existing_interface == interface) {
4378 duplicate = true;
4379 break;
4380 }
4381 }
4382 if (!duplicate) {
4383 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004384 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004385 // Add this interface's non-duplicate super-interfaces.
4386 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004387 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004388 bool super_duplicate = false;
4389 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004390 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004391 if (existing_interface == super_interface) {
4392 super_duplicate = true;
4393 break;
4394 }
4395 }
4396 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004397 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004398 }
4399 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004400 }
4401 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004402 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004403 // Shrink iftable in case duplicates were found
4404 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004405 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004406 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004407 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004408 CHECK(self->IsExceptionPending()); // OOME.
4409 return false;
4410 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004411 ifcount = idx;
4412 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004413 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004414 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004415 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004416 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004417 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004418 return true;
4419 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004420 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004421 size_t max_miranda_methods = 0; // The max size of miranda_list.
4422 for (size_t i = 0; i < ifcount; ++i) {
4423 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4424 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004425 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004426 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004427 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4428 hs.NewHandle(klass->GetVTableDuringLinking()));
4429 // Copy the IMT from the super class if possible.
4430 bool extend_super_iftable = false;
4431 if (has_superclass) {
4432 mirror::Class* super_class = klass->GetSuperClass();
4433 extend_super_iftable = true;
4434 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4435 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4436 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
4437 }
4438 } else {
4439 // No imt in the super class, need to reconstruct from the iftable.
4440 mirror::IfTable* if_table = super_class->GetIfTable();
4441 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4442 const size_t length = super_class->GetIfTableCount();
4443 for (size_t i = 0; i < length; ++i) {
4444 mirror::Class* interface = iftable->GetInterface(i);
4445 const size_t num_virtuals = interface->NumVirtualMethods();
4446 const size_t method_array_count = if_table->GetMethodArrayCount(i);
4447 DCHECK_EQ(num_virtuals, method_array_count);
4448 if (method_array_count == 0) {
4449 continue;
4450 }
4451 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
4452 for (size_t j = 0; j < num_virtuals; ++j) {
4453 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
4454 if (method->IsMiranda()) {
4455 continue;
4456 }
4457 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
4458 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4459 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4460 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4461 out_imt->SetReference(imt_index, method);
4462 } else if (imt_ref != conflict_method) {
4463 out_imt->SetReference(imt_index, conflict_method);
4464 }
4465 }
4466 }
4467 }
4468 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004469 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004470 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004471 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004472 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004473 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004474 const bool is_super = i < super_ifcount;
4475 const bool super_interface = is_super && extend_super_iftable;
4476 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
4477 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
4478 if (super_interface) {
4479 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
4480 DCHECK(if_table != nullptr);
4481 DCHECK(if_table->GetMethodArray(i) != nullptr);
4482 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004483 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004484 AsObjectArray<mirror::ArtMethod>());
4485 // We are overwriting a super class interface, try to only virtual methods instead of the
4486 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004487 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004488 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004489 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004490 // A new interface, we need the whole vtable incase a new interface method is implemented
4491 // in the whole superclass.
4492 input_array = vtable;
4493 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004494 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004495 CHECK(self->IsExceptionPending()); // OOME.
4496 return false;
4497 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004498 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004499 if (input_array.Get() == nullptr) {
4500 // If the added virtual methods is empty, do nothing.
4501 DCHECK(super_interface);
4502 continue;
4503 }
Ian Rogers62d6c772013-02-27 08:32:07 -08004504 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004505 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004506 MethodNameAndSignatureComparator interface_name_comparator(
4507 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07004508 int32_t k;
4509 // For each method listed in the interface's method list, find the
4510 // matching method in our class's method list. We want to favor the
4511 // subclass over the superclass, which just requires walking
4512 // back from the end of the vtable. (This only matters if the
4513 // superclass defines a private method and this class redefines
4514 // it -- otherwise it would use the same vtable slot. In .dex files
4515 // those don't end up in the virtual method table, so it shouldn't
4516 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004517 for (k = input_array->GetLength() - 1; k >= 0; --k) {
4518 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004519 mirror::ArtMethod* vtable_method_for_name_comparison =
4520 vtable_method->GetInterfaceMethodIfProxy();
4521 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004522 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004523 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004524 ThrowIllegalAccessError(
4525 klass.Get(),
4526 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004527 PrettyMethod(vtable_method).c_str(),
4528 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004529 return false;
4530 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004531 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004532 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004533 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4534 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4535 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4536 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4537 out_imt->SetReference(imt_index, vtable_method);
4538 } else if (imt_ref != conflict_method) {
4539 // If we are not a conflict and we have the same signature and name as the imt entry,
4540 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004541 MethodNameAndSignatureComparator imt_ref_name_comparator(
4542 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004543 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004544 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004545 out_imt->SetReference(imt_index, vtable_method);
4546 } else {
4547 out_imt->SetReference(imt_index, conflict_method);
4548 }
Jeff Hao88474b42013-10-23 16:24:40 -07004549 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004550 break;
4551 }
4552 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004553 if (k < 0 && !super_interface) {
4554 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004555 for (size_t l = 0; l < miranda_list_size; ++l) {
4556 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004557 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004558 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07004559 break;
4560 }
4561 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004562 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004563 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004564 miranda_method = interface_method->Clone(self)->AsArtMethod();
4565 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004566 CHECK(self->IsExceptionPending()); // OOME.
4567 return false;
4568 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004569 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004570 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004571 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004572 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004573 }
4574 }
4575 }
4576 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004577 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004578 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004579 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004580 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4581 if (old_method_count == 0) {
4582 virtuals = AllocArtMethodArray(self, new_method_count);
4583 } else {
4584 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4585 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004586 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004587 CHECK(self->IsExceptionPending()); // OOME.
4588 return false;
4589 }
4590 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004591
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004592 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004593 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004594 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004595 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004596 CHECK(self->IsExceptionPending()); // OOME.
4597 return false;
4598 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004599 for (size_t i = 0; i < miranda_list_size; ++i) {
4600 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004601 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004602 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4603 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4604 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004605 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004606 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004607 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004608 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004609 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004610
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004611 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004612 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
4613 for (int i = 0; i < check_vtable->GetLength(); ++i) {
4614 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004615 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004616 }
4617
Ian Rogers7b078e82014-09-10 14:44:24 -07004618 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004619 return true;
4620}
4621
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004622bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004623 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004624 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004625}
4626
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004627bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004628 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004629 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004630}
4631
Brian Carlstromdbc05252011-09-09 01:59:59 -07004632struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004633 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4634 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004635 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07004636 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004637 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07004638 // 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 -07004639 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4640 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004641 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00004642 if (type1 == Primitive::kPrimNot) {
4643 // Reference always goes first.
4644 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08004645 }
Vladimir Markod5777482014-11-12 17:02:02 +00004646 if (type2 == Primitive::kPrimNot) {
4647 // Reference always goes first.
4648 return false;
4649 }
4650 size_t size1 = Primitive::ComponentSize(type1);
4651 size_t size2 = Primitive::ComponentSize(type2);
4652 if (size1 != size2) {
4653 // Larger primitive types go first.
4654 return size1 > size2;
4655 }
4656 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
4657 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004658 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004659 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
4660 // by name and for equal names by type id index.
4661 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
4662 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07004663 }
4664};
4665
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004666bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07004667 size_t* class_size) {
4668 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004669 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
4670 ArtField* const fields = is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004671
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004672 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07004673 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004674 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00004675 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004676 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004677 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004678 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004679 CHECK(super_class->IsResolved())
4680 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004681 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004682 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004683 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004684
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004685 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004686
Brian Carlstromdbc05252011-09-09 01:59:59 -07004687 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07004688 // minimizes disruption of C++ version such as Class and Method.
Mathieu Chartierc7853442015-03-27 14:35:38 -07004689 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07004690 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07004691 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07004692 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004693 grouped_and_sorted_fields.push_back(&fields[i]);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004694 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004695 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4696 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004697
Fred Shih381e4ca2014-08-25 17:24:27 -07004698 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07004699 size_t current_field = 0;
4700 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07004701 FieldGaps gaps;
4702
Brian Carlstromdbc05252011-09-09 01:59:59 -07004703 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004704 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004705 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004706 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004707 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004708 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004709 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004710 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
4711 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07004712 MemberOffset old_offset = field_offset;
4713 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
4714 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
4715 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004716 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07004717 grouped_and_sorted_fields.pop_front();
4718 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004719 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00004720 field_offset = MemberOffset(field_offset.Uint32Value() +
4721 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004722 }
Fred Shih381e4ca2014-08-25 17:24:27 -07004723 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
4724 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00004725 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4726 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4727 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4728 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07004729 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
4730 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07004731 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004732
Elliott Hughesadb460d2011-10-05 17:02:34 -07004733 // 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 -07004734 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07004735 // We know there are no non-reference fields in the Reference classes, and we know
4736 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07004737 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07004738 CHECK_STREQ(fields[num_fields - 1].GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07004739 --num_reference_fields;
4740 }
4741
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004742 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004743 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004744 if (is_static) {
4745 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004746 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004747 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004748 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004749 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08004750 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
Jeff Haoc7d11882015-02-03 15:08:39 -08004751 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
4752 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartier2d721012014-11-10 11:08:06 -08004753 } else {
4754 std::string temp;
4755 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
4756 size_t previous_size = klass->GetObjectSize();
4757 if (previous_size != 0) {
4758 // Make sure that we didn't originally have an incorrect size.
4759 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
4760 }
4761 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004762 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004763 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004764 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004765
4766 if (kIsDebugBuild) {
4767 // Make sure that the fields array is ordered by name but all reference
4768 // offsets are at the beginning as far as alignment allows.
4769 MemberOffset start_ref_offset = is_static
4770 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
4771 : klass->GetFirstReferenceInstanceFieldOffset();
4772 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
4773 num_reference_fields *
4774 sizeof(mirror::HeapReference<mirror::Object>));
4775 MemberOffset current_ref_offset = start_ref_offset;
4776 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004777 ArtField* field = &fields[i];
4778 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
4779 << " class=" << PrettyClass(klass.Get()) << " field=" << PrettyField(field) << " offset="
4780 << field->GetOffset();
Vladimir Marko76649e82014-11-10 18:32:59 +00004781 if (i != 0) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004782 ArtField* const prev_field = &fields[i - 1];
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004783 // NOTE: The field names can be the same. This is not possible in the Java language
4784 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
4785 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00004786 }
4787 Primitive::Type type = field->GetTypeAsPrimitiveType();
4788 bool is_primitive = type != Primitive::kPrimNot;
4789 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
4790 strcmp("referent", field->GetName()) == 0) {
4791 is_primitive = true; // We lied above, so we have to expect a lie here.
4792 }
4793 MemberOffset offset = field->GetOffsetDuringLinking();
4794 if (is_primitive) {
4795 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
4796 // Shuffled before references.
4797 size_t type_size = Primitive::ComponentSize(type);
4798 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
4799 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
4800 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
4801 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
4802 }
4803 } else {
4804 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
4805 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
4806 sizeof(mirror::HeapReference<mirror::Object>));
4807 }
4808 }
4809 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
4810 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004811 return true;
4812}
4813
Vladimir Marko76649e82014-11-10 18:32:59 +00004814// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004815void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004816 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004817 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004818 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004819 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004820 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004821 // Compute reference offsets unless our superclass overflowed.
4822 if (reference_offsets != mirror::Class::kClassWalkSuper) {
4823 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00004824 if (num_reference_fields != 0u) {
4825 // All of the fields that contain object references are guaranteed be grouped in memory
4826 // starting at an appropriately aligned address after super class object data.
4827 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
4828 sizeof(mirror::HeapReference<mirror::Object>));
4829 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004830 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00004831 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004832 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004833 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00004834 reference_offsets |= (0xffffffffu << start_bit) &
4835 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004836 }
4837 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07004838 }
4839 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07004840 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004841}
4842
Mathieu Chartier590fee92013-09-13 13:46:47 -07004843mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004844 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004845 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004846 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004847 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004848 return resolved;
4849 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07004850 uint32_t utf16_length;
4851 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004852 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004853 dex_cache->SetResolvedString(string_idx, string);
4854 return string;
4855}
4856
Mathieu Chartier590fee92013-09-13 13:46:47 -07004857mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08004858 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004859 StackHandleScope<2> hs(Thread::Current());
4860 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
4861 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07004862 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
4863}
4864
4865mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004866 Handle<mirror::DexCache> dex_cache,
4867 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004868 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004869 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004870 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08004871 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07004872 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08004873 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004874 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05004875 // TODO: we used to throw here if resolved's class loader was not the
4876 // boot class loader. This was to permit different classes with the
4877 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004878 dex_cache->SetResolvedType(type_idx, resolved);
4879 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004880 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08004881 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08004882 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004883 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004884 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004885 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004886 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08004887 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08004888 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004889 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08004890 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004891 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004892 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004893 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07004894 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004895 return resolved;
4896}
4897
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004898mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004899 Handle<mirror::DexCache> dex_cache,
4900 Handle<mirror::ClassLoader> class_loader,
4901 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07004902 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004903 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07004904 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07004905 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004906 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004907 return resolved;
4908 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004909 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004910 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004911 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004912 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07004913 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004914 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004915 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004916 // Scan using method_idx, this saves string compares but will only hit for matching dex
4917 // caches/files.
4918 switch (type) {
4919 case kDirect: // Fall-through.
4920 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004921 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004922 break;
4923 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004924 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004925 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004926 break;
4927 case kSuper: // Fall-through.
4928 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004929 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004930 break;
4931 default:
4932 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07004933 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004934 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004935 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004936 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004937 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07004938 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07004939 switch (type) {
4940 case kDirect: // Fall-through.
4941 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08004942 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004943 break;
4944 case kInterface:
4945 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004946 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004947 break;
4948 case kSuper: // Fall-through.
4949 case kVirtual:
4950 resolved = klass->FindVirtualMethod(name, signature);
4951 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004952 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004953 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004954 // If we found a method, check for incompatible class changes.
4955 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004956 // Be a good citizen and update the dex cache to speed subsequent calls.
4957 dex_cache->SetResolvedMethod(method_idx, resolved);
4958 return resolved;
4959 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004960 // If we had a method, it's an incompatible-class-change error.
4961 if (resolved != nullptr) {
4962 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
4963 } else {
4964 // We failed to find the method which means either an access error, an incompatible class
4965 // change, or no such method. First try to find the method among direct and virtual methods.
4966 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
4967 const Signature signature = dex_file.GetMethodSignature(method_id);
4968 switch (type) {
4969 case kDirect:
4970 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07004971 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004972 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
4973 // have had a resolved method before, which triggers the "true" branch above.
4974 break;
4975 case kInterface:
4976 case kVirtual:
4977 case kSuper:
4978 resolved = klass->FindDirectMethod(name, signature);
4979 break;
4980 }
4981
4982 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08004983 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004984 if (resolved != nullptr && referrer.Get() != nullptr) {
4985 mirror::Class* methods_class = resolved->GetDeclaringClass();
4986 mirror::Class* referring_class = referrer->GetDeclaringClass();
4987 if (!referring_class->CanAccess(methods_class)) {
4988 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
4989 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004990 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004991 } else if (!referring_class->CanAccessMember(methods_class,
4992 resolved->GetAccessFlags())) {
4993 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004994 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004995 }
4996 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004997 if (!exception_generated) {
4998 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
4999 // interface methods and throw if we find the method there. If we find nothing, throw a
5000 // NoSuchMethodError.
5001 switch (type) {
5002 case kDirect:
5003 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005004 if (resolved != nullptr) {
5005 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5006 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005007 resolved = klass->FindInterfaceMethod(name, signature);
5008 if (resolved != nullptr) {
5009 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5010 } else {
5011 ThrowNoSuchMethodError(type, klass, name, signature);
5012 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005013 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005014 break;
5015 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005016 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005017 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5018 } else {
5019 resolved = klass->FindVirtualMethod(name, signature);
5020 if (resolved != nullptr) {
5021 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5022 } else {
5023 ThrowNoSuchMethodError(type, klass, name, signature);
5024 }
5025 }
5026 break;
5027 case kSuper:
5028 if (resolved != nullptr) {
5029 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005030 } else {
5031 ThrowNoSuchMethodError(type, klass, name, signature);
5032 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005033 break;
5034 case kVirtual:
5035 if (resolved != nullptr) {
5036 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5037 } else {
5038 resolved = klass->FindInterfaceMethod(name, signature);
5039 if (resolved != nullptr) {
5040 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5041 } else {
5042 ThrowNoSuchMethodError(type, klass, name, signature);
5043 }
5044 }
5045 break;
5046 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005047 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005048 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005049 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005050 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005051 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005052}
5053
Mathieu Chartierc7853442015-03-27 14:35:38 -07005054ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
5055 Handle<mirror::DexCache> dex_cache,
5056 Handle<mirror::ClassLoader> class_loader, bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005057 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005058 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005059 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005060 return resolved;
5061 }
5062 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005063 Thread* const self = Thread::Current();
5064 StackHandleScope<1> hs(self);
5065 Handle<mirror::Class> klass(
5066 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005067 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005068 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005069 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005070 }
5071
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005072 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005073 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005074 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005075 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005076 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005077
Andreas Gampe58a5af82014-07-31 16:23:49 -07005078 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005079 const char* name = dex_file.GetFieldName(field_id);
5080 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5081 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005082 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005083 } else {
5084 resolved = klass->FindInstanceField(name, type);
5085 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005086 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005087 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005088 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005089 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005090 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07005091 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08005092 return resolved;
5093}
5094
Mathieu Chartierc7853442015-03-27 14:35:38 -07005095ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file, uint32_t field_idx,
5096 Handle<mirror::DexCache> dex_cache,
5097 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005098 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005099 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005100 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005101 return resolved;
5102 }
5103 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005104 Thread* self = Thread::Current();
5105 StackHandleScope<1> hs(self);
5106 Handle<mirror::Class> klass(
5107 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005108 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005109 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005110 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005111 }
5112
Ian Rogersdfb325e2013-10-30 01:00:44 -07005113 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5114 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005115 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005116 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005117 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005118 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08005119 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005120 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005121 }
5122 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005123}
5124
Brian Carlstromea46f952013-07-30 01:26:50 -07005125const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005126 uint32_t* length) {
5127 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5128 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005129 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005130 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005131 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005132}
5133
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005134void ClassLinker::DumpAllClasses(int flags) {
5135 if (dex_cache_image_class_lookup_required_) {
5136 MoveImageClassesToClassTable();
5137 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005138 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5139 // 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 -08005140 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005141 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005142 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005143 for (GcRoot<mirror::Class>& it : class_table_) {
5144 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005145 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005146 }
5147
5148 for (size_t i = 0; i < all_classes.size(); ++i) {
5149 all_classes[i]->DumpClass(std::cerr, flags);
5150 }
5151}
5152
Elliott Hughes956af0f2014-12-11 14:34:28 -08005153static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005154 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005155 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5156 base -= sizeof(void*); // Move backward so that code_offset != 0.
5157 const uint32_t code_offset = sizeof(void*);
5158 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005159}
5160
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005161bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5162 return (entry_point == GetQuickResolutionStub()) ||
5163 (quick_resolution_trampoline_ == entry_point);
5164}
5165
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005166bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5167 return (entry_point == GetQuickToInterpreterBridge()) ||
5168 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5169}
5170
5171bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5172 return (entry_point == GetQuickGenericJniStub()) ||
5173 (quick_generic_jni_trampoline_ == entry_point);
5174}
5175
5176const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5177 return GetQuickGenericJniStub();
5178}
5179
Elliott Hughes956af0f2014-12-11 14:34:28 -08005180void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5181 const void* method_code) const {
5182 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005183 oat_method.LinkMethod(method);
5184 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005185}
5186
5187void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5188 if (!method->IsNative()) {
5189 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005190 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5191 } else {
5192 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005193 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005194 oat_method.LinkMethod(method);
5195 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005196 }
5197}
5198
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005199void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005200 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005201 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005202 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005203 MoveImageClassesToClassTable();
5204 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005205 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005206 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5207 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005208}
5209
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005210size_t ClassLinker::NumLoadedClasses() {
5211 if (dex_cache_image_class_lookup_required_) {
5212 MoveImageClassesToClassTable();
5213 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005214 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005215 // Only return non zygote classes since these are the ones which apps which care about.
5216 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005217}
5218
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005219pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005220 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005221}
5222
5223pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005224 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005225}
5226
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005227void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005228 DCHECK(!init_done_);
5229
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005230 DCHECK(klass != nullptr);
5231 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005232
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005233 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005234 DCHECK(class_roots != nullptr);
5235 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005236 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005237}
5238
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005239const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5240 static const char* class_roots_descriptors[] = {
5241 "Ljava/lang/Class;",
5242 "Ljava/lang/Object;",
5243 "[Ljava/lang/Class;",
5244 "[Ljava/lang/Object;",
5245 "Ljava/lang/String;",
5246 "Ljava/lang/DexCache;",
5247 "Ljava/lang/ref/Reference;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005248 "Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005249 "Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005250 "Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005251 "Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005252 "Ljava/lang/reflect/Proxy;",
5253 "[Ljava/lang/String;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005254 "[Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005255 "[Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005256 "[Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005257 "[Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005258 "Ljava/lang/ClassLoader;",
5259 "Ljava/lang/Throwable;",
5260 "Ljava/lang/ClassNotFoundException;",
5261 "Ljava/lang/StackTraceElement;",
5262 "Z",
5263 "B",
5264 "C",
5265 "D",
5266 "F",
5267 "I",
5268 "J",
5269 "S",
5270 "V",
5271 "[Z",
5272 "[B",
5273 "[C",
5274 "[D",
5275 "[F",
5276 "[I",
5277 "[J",
5278 "[S",
5279 "[Ljava/lang/StackTraceElement;",
5280 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005281 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5282 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005283
5284 const char* descriptor = class_roots_descriptors[class_root];
5285 CHECK(descriptor != nullptr);
5286 return descriptor;
5287}
5288
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005289std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5290 const {
5291 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005292 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005293}
5294
5295bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005296 const GcRoot<mirror::Class>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005297 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5298 return false;
5299 }
5300 std::string temp;
5301 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5302}
5303
5304std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5305 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005306 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005307}
5308
5309bool ClassLinker::ClassDescriptorHashEquals::operator()(
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005310 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005311 if (a.Read()->GetClassLoader() != b.second) {
5312 return false;
5313 }
5314 return a.Read()->DescriptorEquals(b.first);
5315}
5316
5317bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005318 const char* descriptor) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005319 return a.Read()->DescriptorEquals(descriptor);
5320}
5321
5322std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005323 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005324}
5325
Sebastien Hertz6963e442014-11-26 22:11:27 +01005326bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07005327 if (Runtime::Current()->UseJit()) {
5328 // JIT can have direct code pointers from any method to any other method.
5329 return true;
5330 }
Sebastien Hertz6963e442014-11-26 22:11:27 +01005331 // Non-image methods don't use direct code pointer.
5332 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
5333 return false;
5334 }
5335 if (m->IsPrivate()) {
5336 // The method can only be called inside its own oat file. Therefore it won't be called using
5337 // its direct code if the oat file has been compiled in PIC mode.
Sebastien Hertz6963e442014-11-26 22:11:27 +01005338 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
Richard Uhler07b3c232015-03-31 15:57:54 -07005339 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Sebastien Hertz6963e442014-11-26 22:11:27 +01005340 if (oat_dex_file == nullptr) {
5341 // No oat file: the method has not been compiled.
5342 return false;
5343 }
5344 const OatFile* oat_file = oat_dex_file->GetOatFile();
5345 return oat_file != nullptr && !oat_file->IsPic();
5346 } else {
5347 // The method can be called outside its own oat file. Therefore it won't be called using its
5348 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
5349 ReaderMutexLock mu(Thread::Current(), dex_lock_);
5350 for (const OatFile* oat_file : oat_files_) {
5351 if (!oat_file->IsPic()) {
5352 return true;
5353 }
5354 }
5355 return false;
5356 }
5357}
5358
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005359jobject ClassLinker::CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files) {
5360 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
5361 // We could move the jobject to the callers, but all call-sites do this...
5362 ScopedObjectAccessUnchecked soa(self);
5363
5364 // Register the dex files.
5365 for (const DexFile* dex_file : dex_files) {
5366 RegisterDexFile(*dex_file);
5367 }
5368
5369 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005370 StackHandleScope<10> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005371
Mathieu Chartierc7853442015-03-27 14:35:38 -07005372 ArtField* dex_elements_field =
5373 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005374
Mathieu Chartierc7853442015-03-27 14:35:38 -07005375 mirror::Class* dex_elements_class = dex_elements_field->GetType<true>();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005376 DCHECK(dex_elements_class != nullptr);
5377 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005378 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
5379 mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005380 Handle<mirror::Class> h_dex_element_class =
5381 hs.NewHandle(dex_elements_class->GetComponentType());
5382
Mathieu Chartierc7853442015-03-27 14:35:38 -07005383 ArtField* element_file_field =
5384 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
5385 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005386
Mathieu Chartierc7853442015-03-27 14:35:38 -07005387 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
5388 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005389
5390 // Fill the elements array.
5391 int32_t index = 0;
5392 for (const DexFile* dex_file : dex_files) {
5393 StackHandleScope<3> hs2(self);
5394
5395 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(self, 1));
5396 DCHECK(h_long_array.Get() != nullptr);
5397 h_long_array->Set(0, reinterpret_cast<intptr_t>(dex_file));
5398
5399 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07005400 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005401 DCHECK(h_dex_file.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005402 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005403
5404 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
5405 DCHECK(h_element.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005406 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005407
5408 h_dex_elements->Set(index, h_element.Get());
5409 index++;
5410 }
5411 DCHECK_EQ(index, h_dex_elements->GetLength());
5412
5413 // Create DexPathList.
5414 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07005415 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005416 DCHECK(h_dex_path_list.Get() != nullptr);
5417 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005418 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005419
5420 // Create PathClassLoader.
5421 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
5422 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
5423 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
5424 h_path_class_class->AllocObject(self));
5425 DCHECK(h_path_class_loader.Get() != nullptr);
5426 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005427 ArtField* path_list_field =
5428 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList);
5429 DCHECK(path_list_field != nullptr);
5430 path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005431
5432 // Make a pretend boot-classpath.
5433 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07005434 ArtField* const parent_field =
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005435 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07005436 "Ljava/lang/ClassLoader;");
5437 DCHECK(parent_field!= nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005438 mirror::Object* boot_cl =
5439 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005440 parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005441
5442 // Make it a global ref and return.
5443 ScopedLocalRef<jobject> local_ref(
5444 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
5445 return soa.Env()->NewGlobalRef(local_ref.get());
5446}
5447
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005448} // namespace art