blob: a02d1ad770c2957355354415fdb8b6c55509411f [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromdbc05252011-09-09 01:59:59 -070019#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070020#include <iostream>
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070022#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070023#include <string>
Andreas Gampea696c0a2014-12-10 20:51:45 -080024#include <unistd.h>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070027
Elliott Hughes1aa246d2012-12-13 09:29:36 -080028#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080029#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010030#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080031#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080032#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080033#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000034#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080035#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070037#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070038#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/accounting/card_table-inl.h"
40#include "gc/accounting/heap_bitmap.h"
41#include "gc/heap.h"
42#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070043#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070044#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070045#include "interpreter/interpreter.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080046#include "jit/jit.h"
47#include "jit/jit_code_cache.h"
Ian Rogers0571d352011-11-03 19:51:38 -070048#include "leb128.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080049#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070050#include "oat_file.h"
Richard Uhler66d874d2015-01-15 09:37:19 -080051#include "oat_file_assistant.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070052#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070053#include "mirror/art_field-inl.h"
54#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055#include "mirror/class.h"
56#include "mirror/class-inl.h"
57#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070058#include "mirror/dex_cache-inl.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070059#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080060#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/object-inl.h"
62#include "mirror/object_array-inl.h"
63#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070064#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080065#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070066#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080067#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070068#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070069#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070070#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070071#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070072#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070073#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070074#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080075#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070076#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070077
78namespace art {
79
Ian Rogers00f7d0e2012-07-19 15:28:27 -070080static void ThrowNoClassDefFoundError(const char* fmt, ...)
81 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070082 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070083static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070084 va_list args;
85 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080086 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +000087 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080088 va_end(args);
89}
90
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080091static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070092 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070093 // The class failed to initialize on a previous attempt, so we want to throw
94 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
95 // failed in verification, in which case v2 5.4.1 says we need to re-throw
96 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080097 Runtime* const runtime = Runtime::Current();
98 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -070099 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
100 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700101
Elliott Hughes5c599942012-06-13 16:45:05 -0700102 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800103 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800104 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700105 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
106 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000107 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700108 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700109 if (c->GetVerifyErrorClass() != NULL) {
110 // TODO: change the verifier to store an _instance_, with a useful detail message?
111 std::string temp;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000112 self->ThrowNewException(c->GetVerifyErrorClass()->GetDescriptor(&temp),
Ian Rogers7b078e82014-09-10 14:44:24 -0700113 PrettyDescriptor(c).c_str());
114 } else {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000115 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
Ian Rogers7b078e82014-09-10 14:44:24 -0700116 PrettyDescriptor(c).c_str());
117 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700118 }
119}
120
Brian Carlstromb23eab12014-10-08 17:55:21 -0700121static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
122 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
123 if (VLOG_IS_ON(class_linker)) {
124 std::string temp;
125 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000126 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700127 }
128}
129
130static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
131 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700132 Thread* self = Thread::Current();
133 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700134
135 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700136 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700137
138 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700139 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
140 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700141
Elliott Hughesa4f94742012-05-29 16:28:38 -0700142 // We only wrap non-Error exceptions; an Error can just be used as-is.
143 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000144 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700145 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700146 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700147}
148
Fred Shih381e4ca2014-08-25 17:24:27 -0700149// Gap between two fields in object layout.
150struct FieldGap {
151 uint32_t start_offset; // The offset from the start of the object.
152 uint32_t size; // The gap size of 1, 2, or 4 bytes.
153};
154struct FieldGapsComparator {
155 explicit FieldGapsComparator() {
156 }
157 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
158 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800159 // Sort by gap size, largest first. Secondary sort by starting offset.
160 return lhs.size > rhs.size || (lhs.size == rhs.size && lhs.start_offset < rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700161 }
162};
163typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
164
165// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800166static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700167 DCHECK(gaps != nullptr);
168
169 uint32_t current_offset = gap_start;
170 while (current_offset != gap_end) {
171 size_t remaining = gap_end - current_offset;
172 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
173 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
174 current_offset += sizeof(uint32_t);
175 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
176 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
177 current_offset += sizeof(uint16_t);
178 } else {
179 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
180 current_offset += sizeof(uint8_t);
181 }
182 DCHECK_LE(current_offset, gap_end) << "Overran gap";
183 }
184}
185// Shuffle fields forward, making use of gaps whenever possible.
186template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000187static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700188 MemberOffset* field_offset,
Fred Shih381e4ca2014-08-25 17:24:27 -0700189 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
190 FieldGaps* gaps)
191 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
192 DCHECK(current_field_idx != nullptr);
193 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700194 DCHECK(gaps != nullptr);
195 DCHECK(field_offset != nullptr);
196
197 DCHECK(IsPowerOfTwo(n));
198 while (!grouped_and_sorted_fields->empty()) {
199 mirror::ArtField* field = grouped_and_sorted_fields->front();
200 Primitive::Type type = field->GetTypeAsPrimitiveType();
201 if (Primitive::ComponentSize(type) < n) {
202 break;
203 }
204 if (!IsAligned<n>(field_offset->Uint32Value())) {
205 MemberOffset old_offset = *field_offset;
206 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
207 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
208 }
209 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
210 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700211 if (!gaps->empty() && gaps->top().size >= n) {
212 FieldGap gap = gaps->top();
213 gaps->pop();
214 DCHECK(IsAligned<n>(gap.start_offset));
215 field->SetOffset(MemberOffset(gap.start_offset));
216 if (gap.size > n) {
217 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
218 }
219 } else {
220 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
221 field->SetOffset(*field_offset);
222 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
223 }
224 ++(*current_field_idx);
225 }
226}
227
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800228ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700229 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700230 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700231 dex_cache_image_class_lookup_required_(false),
232 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800233 class_roots_(nullptr),
234 array_iftable_(nullptr),
235 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700236 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800237 log_new_dex_caches_roots_(false),
238 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700239 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800240 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800241 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100242 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800243 quick_to_interpreter_bridge_trampoline_(nullptr),
244 image_pointer_size_(sizeof(void*)) {
Ian Rogers98379392014-02-24 16:53:16 -0800245 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700246}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700247
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800248void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800249 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700250 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700251
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700252 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700253
Elliott Hughes30646832011-10-13 16:59:46 -0700254 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700255 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700256 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700257 // 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 -0800258 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700259 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
260 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700261 heap->AllocNonMovableObject<true>(self, nullptr,
262 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700263 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700264 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700265 mirror::Class::SetClassClass(java_lang_Class.Get());
266 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700267 if (kUseBakerOrBrooksReadBarrier) {
268 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800269 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700270 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700271 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800272 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800273 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700274
Elliott Hughes418d20f2011-09-22 14:00:39 -0700275 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700276 Handle<mirror::Class> class_array_class(hs.NewHandle(
277 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700278 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700279
Ian Rogers23435d02012-09-24 11:23:12 -0700280 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700281 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
282 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700283 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700284 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700285 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700286 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700287
Ian Rogers23435d02012-09-24 11:23:12 -0700288 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700289 Handle<mirror::Class> object_array_class(hs.NewHandle(
290 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700291 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700292
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700293 // Setup the char (primitive) class to be used for char[].
294 Handle<mirror::Class> char_class(hs.NewHandle(
295 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700296 // The primitive char class won't be initialized by
297 // InitializePrimitiveClass until line 459, but strings (and
298 // internal char arrays) will be allocated before that and the
299 // component size, which is computed from the primitive type, needs
300 // to be set here.
301 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700302
Ian Rogers23435d02012-09-24 11:23:12 -0700303 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700304 Handle<mirror::Class> char_array_class(hs.NewHandle(
305 AllocClass(self, java_lang_Class.Get(),
306 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700307 char_array_class->SetComponentType(char_class.Get());
308 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700309
Ian Rogers23435d02012-09-24 11:23:12 -0700310 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700311 Handle<mirror::Class> java_lang_String(hs.NewHandle(
312 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700313 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700314 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700315 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400316
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700317 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700318 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
319 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
320 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
321 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700322 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700323
Ian Rogers23435d02012-09-24 11:23:12 -0700324 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700325 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700326 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
327 kClassRootsMax));
328 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700329 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
330 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
331 SetClassRoot(kClassArrayClass, class_array_class.Get());
332 SetClassRoot(kObjectArrayClass, object_array_class.Get());
333 SetClassRoot(kCharArrayClass, char_array_class.Get());
334 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700335 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700336
337 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700338 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
339 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
340 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
341 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
342 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
343 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
344 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
345 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700346
Ian Rogers23435d02012-09-24 11:23:12 -0700347 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700348 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349
Ian Rogers23435d02012-09-24 11:23:12 -0700350 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700351 Handle<mirror::Class> int_array_class(hs.NewHandle(
352 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700353 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700354 mirror::IntArray::SetArrayClass(int_array_class.Get());
355 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700356
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700357 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700358
Ian Rogers52813c92012-10-11 11:50:38 -0700359 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700360 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
361 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700362 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700363 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700364 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700365
Brian Carlstromf3632832014-05-20 15:36:53 -0700366 // Constructor, Field, Method, and AbstractMethod are necessary so
367 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700368 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
369 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700370 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700371 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700372 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700373 mirror::Class::SetStatus(java_lang_reflect_ArtField, mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700374 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700375
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700376 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
377 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700378 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800379 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
380 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700381 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700382 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700383 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700384
385 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700386 Handle<mirror::Class> object_array_string(hs.NewHandle(
387 AllocClass(self, java_lang_Class.Get(),
388 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700389 object_array_string->SetComponentType(java_lang_String.Get());
390 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700391
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700392 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
393 AllocClass(self, java_lang_Class.Get(),
394 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700395 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
396 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700397
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700398 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
399 AllocClass(self, java_lang_Class.Get(),
400 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700401 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
402 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700403
Ian Rogers23435d02012-09-24 11:23:12 -0700404 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
405 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
406 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700407 CHECK_NE(0U, boot_class_path.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800408 for (auto& dex_file : boot_class_path) {
409 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700410 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800411 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700412 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
414 // now we can use FindSystemClass
415
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700416 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700417 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
418 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700419
Jeff Hao88474b42013-10-23 16:24:40 -0700420 // Create runtime resolution and imt conflict methods. Also setup the default imt.
421 Runtime* runtime = Runtime::Current();
422 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
423 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700424 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700425 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
426
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700427 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
428 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700429 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800430 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700431 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700432 quick_resolution_trampoline_ = GetQuickResolutionStub();
433 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
434 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700435 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700436
Mathieu Chartier66f19252012-09-18 08:57:04 -0700437 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700438 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800439 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700440 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700441 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700442 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800443 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700444 std::ostringstream os1, os2;
445 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
446 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
447 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
448 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700449 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800450 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700451 CHECK_EQ(java_lang_String.Get(), String_class);
452 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700453 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454
Ian Rogers23435d02012-09-24 11:23:12 -0700455 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800456 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800457 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700458
Ian Rogers98379392014-02-24 16:53:16 -0800459 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800460 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700461
Ian Rogers98379392014-02-24 16:53:16 -0800462 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700463 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700464
Ian Rogers98379392014-02-24 16:53:16 -0800465 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800466 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700467
Ian Rogers98379392014-02-24 16:53:16 -0800468 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700469 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470
Ian Rogers98379392014-02-24 16:53:16 -0800471 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800472 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700473
Ian Rogers98379392014-02-24 16:53:16 -0800474 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800475 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700476
Ian Rogers98379392014-02-24 16:53:16 -0800477 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800478 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700479
Ian Rogers98379392014-02-24 16:53:16 -0800480 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700481 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700482
Ian Rogers98379392014-02-24 16:53:16 -0800483 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700484 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700485
Ian Rogers23435d02012-09-24 11:23:12 -0700486 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800487 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700488 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800489 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700490 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700491 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
492 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700493 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700494 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700495 array_iftable->SetInterface(0, java_lang_Cloneable);
496 array_iftable->SetInterface(1, java_io_Serializable);
497 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700498
Ian Rogers23435d02012-09-24 11:23:12 -0700499 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700500 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
501 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
502 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
503 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700504 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700505 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800506 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700507 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700508
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700509 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800510 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700511 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700512
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700513 mirror::Class::SetStatus(java_lang_reflect_ArtField, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800514 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700515 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700516
Brian Carlstromf3632832014-05-20 15:36:53 -0700517 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700518 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700519 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700520
Brian Carlstromea46f952013-07-30 01:26:50 -0700521 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700522 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700523 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700524
Brian Carlstromea46f952013-07-30 01:26:50 -0700525 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700526 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700527 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700528
Ian Rogers23435d02012-09-24 11:23:12 -0700529 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700530
Ian Rogers23435d02012-09-24 11:23:12 -0700531 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800532 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700533 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
534
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700535 // Create java.lang.reflect.Field.class root.
536 mirror::Class* java_lang_reflect_Field = FindSystemClass(self, "Ljava/lang/reflect/Field;");
537 CHECK(java_lang_reflect_Field != nullptr);
538 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
539 mirror::Field::SetClass(java_lang_reflect_Field);
540
541 // Create java.lang.reflect.Field array root.
542 mirror::Class* java_lang_reflect_Field_array =
543 FindSystemClass(self, "[Ljava/lang/reflect/Field;");
544 CHECK(java_lang_reflect_Field_array != nullptr);
545 SetClassRoot(kJavaLangReflectFieldArrayClass, java_lang_reflect_Field_array);
546 mirror::Field::SetArrayClass(java_lang_reflect_Field_array);
547
Brian Carlstrom1f870082011-08-23 16:02:11 -0700548 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700549 // finish initializing Reference class
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700550 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700551 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
552 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
553 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
554 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700555 mirror::Class* java_lang_ref_FinalizerReference =
556 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700557 java_lang_ref_FinalizerReference->SetAccessFlags(
558 java_lang_ref_FinalizerReference->GetAccessFlags() |
559 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700560 mirror::Class* java_lang_ref_PhantomReference =
561 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700562 java_lang_ref_PhantomReference->SetAccessFlags(
563 java_lang_ref_PhantomReference->GetAccessFlags() |
564 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700565 mirror::Class* java_lang_ref_SoftReference =
566 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700567 java_lang_ref_SoftReference->SetAccessFlags(
568 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700569 mirror::Class* java_lang_ref_WeakReference =
570 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700571 java_lang_ref_WeakReference->SetAccessFlags(
572 java_lang_ref_WeakReference->GetAccessFlags() |
573 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700574
Ian Rogers23435d02012-09-24 11:23:12 -0700575 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800576 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700577 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700578 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
579
jeffhao8cd6dda2012-02-22 10:15:34 -0800580 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700581 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800582 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800583 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700584 SetClassRoot(kJavaLangClassNotFoundException,
585 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800586 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700587 SetClassRoot(kJavaLangStackTraceElementArrayClass,
588 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800589 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700590
Andreas Gampe76bd8802014-12-10 16:43:58 -0800591 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
592 // initialized.
593 {
594 const DexFile& dex_file = java_lang_Object->GetDexFile();
595 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
596 CHECK(void_string_id != nullptr);
597 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
598 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
599 CHECK(void_type_id != nullptr);
600 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
601 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
602 // as referrer so the used dex cache is core's one.
603 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
604 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
605 self->AssertNoPendingException();
606 }
607
Ian Rogers98379392014-02-24 16:53:16 -0800608 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700609
Brian Carlstroma004aa92012-02-08 18:05:09 -0800610 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700611}
612
Ian Rogers98379392014-02-24 16:53:16 -0800613void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800614 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700615
616 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700617 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700618 // as the types of the field can't be resolved prior to the runtime being
619 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800620 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700621 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800622 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800623
Brian Carlstromea46f952013-07-30 01:26:50 -0700624 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700625 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
626 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700627
Brian Carlstromea46f952013-07-30 01:26:50 -0700628 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700629 CHECK_STREQ(queue->GetName(), "queue");
630 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700631
Brian Carlstromea46f952013-07-30 01:26:50 -0700632 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700633 CHECK_STREQ(queueNext->GetName(), "queueNext");
634 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700635
Brian Carlstromea46f952013-07-30 01:26:50 -0700636 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700637 CHECK_STREQ(referent->GetName(), "referent");
638 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700639
Brian Carlstromea46f952013-07-30 01:26:50 -0700640 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700641 CHECK_STREQ(zombie->GetName(), "zombie");
642 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700643
Brian Carlstroma663ea52011-08-19 23:33:41 -0700644 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700645 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700646 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800647 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700648 CHECK(klass != nullptr);
649 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700650 // note SetClassRoot does additional validation.
651 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700652 }
653
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700654 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700655
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700656 // disable the slow paths in FindClass and CreatePrimitiveClass now
657 // that Object, Class, and Object[] are setup
658 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700659
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800660 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700661}
662
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700663void ClassLinker::RunRootClinits() {
664 Thread* self = Thread::Current();
665 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800666 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700667 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700668 StackHandleScope<1> hs(self);
669 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700670 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700671 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700672 }
673 }
674}
675
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700676const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700677 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800678 if (kIsDebugBuild) {
679 for (size_t i = 0; i < oat_files_.size(); ++i) {
680 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700681 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800682 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700683 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
684 oat_files_.push_back(oat_file);
685 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800686}
687
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700688OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
689 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700690 OatFile* oat_file = space->ReleaseOatFile();
691 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700692 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700693 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700694}
695
Richard Uhler66d874d2015-01-15 09:37:19 -0800696std::vector<std::unique_ptr<const DexFile>> ClassLinker::OpenDexFilesFromOat(
697 const char* dex_location, const char* oat_location,
698 std::vector<std::string>* error_msgs) {
699 CHECK(error_msgs != nullptr);
Calin Juravle621962a2014-09-02 15:53:55 +0100700
Richard Uhler66d874d2015-01-15 09:37:19 -0800701 // Verify we aren't holding the mutator lock, which could starve GC if we
702 // have to generate or relocate an oat file.
703 Locks::mutator_lock_->AssertNotHeld(Thread::Current());
704
705 OatFileAssistant oat_file_assistant(dex_location, oat_location, kRuntimeISA,
706 !Runtime::Current()->IsAotCompiler());
707
708 // Lock the target oat location to avoid races generating and loading the
709 // oat file.
710 std::string error_msg;
711 if (!oat_file_assistant.Lock(&error_msg)) {
712 // Don't worry too much if this fails. If it does fail, it's unlikely we
713 // can generate an oat file anyway.
714 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700715 }
716
Richard Uhler66d874d2015-01-15 09:37:19 -0800717 // Check if we already have an up-to-date oat file open.
718 const OatFile* source_oat_file = nullptr;
719 {
720 ReaderMutexLock mu(Thread::Current(), dex_lock_);
721 for (const OatFile* oat_file : oat_files_) {
722 CHECK(oat_file != nullptr);
723 if (oat_file_assistant.GivenOatFileIsUpToDate(*oat_file)) {
724 source_oat_file = oat_file;
725 break;
Andreas Gampe833a4852014-05-21 18:46:59 -0700726 }
727 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700728 }
729
Richard Uhler66d874d2015-01-15 09:37:19 -0800730 // If we didn't have an up-to-date oat file open, try to load one from disk.
731 if (source_oat_file == nullptr) {
732 // Update the oat file on disk if we can. This may fail, but that's okay.
733 // Best effort is all that matters here.
734 if (!oat_file_assistant.MakeUpToDate(&error_msg)) {
735 LOG(WARNING) << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700736 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700737
Richard Uhler66d874d2015-01-15 09:37:19 -0800738 // Get the oat file on disk.
739 std::unique_ptr<OatFile> oat_file = oat_file_assistant.GetBestOatFile();
740 if (oat_file.get() != nullptr) {
741 source_oat_file = oat_file.release();
742 RegisterOatFile(source_oat_file);
Andreas Gampe833a4852014-05-21 18:46:59 -0700743 }
744 }
745
Richard Uhler66d874d2015-01-15 09:37:19 -0800746 std::vector<std::unique_ptr<const DexFile>> dex_files;
Andreas Gampe833a4852014-05-21 18:46:59 -0700747
Richard Uhler66d874d2015-01-15 09:37:19 -0800748 // Load the dex files from the oat file.
749 if (source_oat_file != nullptr) {
750 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
751 if (dex_files.empty()) {
752 error_msgs->push_back("Failed to open dex files from "
753 + source_oat_file->GetLocation());
Andreas Gampe833a4852014-05-21 18:46:59 -0700754 }
755 }
756
Richard Uhler66d874d2015-01-15 09:37:19 -0800757 // Fall back to running out of the original dex file if we couldn't load any
758 // dex_files from the oat file.
759 if (dex_files.empty()) {
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700760 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800761 if (!DexFile::Open(dex_location, dex_location, &error_msg, &dex_files)) {
762 LOG(WARNING) << error_msg;
763 error_msgs->push_back("Failed to open dex files from "
764 + std::string(dex_location));
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700765 }
766 } else {
767 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
768 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700769 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800770 return dex_files;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700771}
772
Brian Carlstromae826982011-11-09 01:33:42 -0800773const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700774 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700775 for (size_t i = 0; i < oat_files_.size(); i++) {
776 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700777 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -0800778 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700779 return oat_file;
780 }
781 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700782 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -0700783}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700784
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800785void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700786 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700787 DCHECK(obj != nullptr);
788 DCHECK(class_linker != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700789 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700790 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -0700791 if (!method->IsNative()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800792 const size_t pointer_size = class_linker->image_pointer_size_;
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800793 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800794 if (!method->IsRuntimeMethod() && method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800795 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
796 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -0700797 }
798 }
799 }
800}
801
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700802void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800803 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700804 CHECK(!init_done_);
805
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700806 Runtime* const runtime = Runtime::Current();
807 Thread* const self = Thread::Current();
808 gc::Heap* const heap = runtime->GetHeap();
809 gc::space::ImageSpace* const space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700810 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700811 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700812 OatFile& oat_file = GetImageOatFile(space);
813 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
814 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700815 const char* image_file_location = oat_file.GetOatHeader().
816 GetStoreValueByKey(OatHeader::kImageLocationKey);
817 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700818 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -0700819 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -0800820 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +0100821 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800822 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
823 mirror::ObjectArray<mirror::DexCache>* dex_caches =
824 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700825
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700826 StackHandleScope<1> hs(self);
827 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
828 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
829 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700830 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700831
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700832 // Special case of setting up the String class early so that we can test arbitrary objects
833 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700834 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800835
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700836 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700837 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700838 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800839 StackHandleScope<1> hs2(self);
840 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700841 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700842 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
843 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700844 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700845 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800846 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
847 if (dex_file.get() == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700848 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700849 << " from within oat file " << oat_file.GetLocation()
850 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -0800851 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700852 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700853
854 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
855
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800856 AppendToBootClassPath(*dex_file.get(), dex_cache);
857 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700858 }
859
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700860 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
861 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -0700862 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -0800863 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700864 if (!runtime->IsAotCompiler()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800865 // Aot compiler supports having an image with a different pointer size than the runtime. This
Mathieu Chartier2d721012014-11-10 11:08:06 -0800866 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
867 // also use 32 bit dex2oat on a system with 64 bit apps.
868 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
869 << sizeof(void*);
870 }
871 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
872 image_pointer_size_ = 4;
873 } else {
874 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
875 image_pointer_size_ = 8;
876 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700877
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700878 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800879 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700880 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700881 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700882
883 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800884 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700885 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700886
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800887 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700888 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800889 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800890 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700891 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
892 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Fred Shih4ee7a662014-07-11 09:59:27 -0700893 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -0700894 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800895 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
896 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
897 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
898 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
899 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
900 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
901 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
902 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
903 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
904 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700905
Ian Rogers98379392014-02-24 16:53:16 -0800906 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700907
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800908 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700909}
910
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700911void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
912 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
913 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800914 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800915 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800916 }
917 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800918 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700919 }
920 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800921 for (auto& root : new_class_roots_) {
922 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800923 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800924 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700925 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700926 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
927 // corresponding object. This is slow, but luckily for us, this may only happen with a
928 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800929 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800930 DCHECK(it != class_table_.end());
931 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700932 }
933 }
934 }
935 if ((flags & kVisitRootFlagClearRootLog) != 0) {
936 new_class_roots_.clear();
937 }
938 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
939 log_new_class_table_roots_ = true;
940 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
941 log_new_class_table_roots_ = false;
942 }
943 // We deliberately ignore the class roots in the image since we
944 // handle image roots by using the MS/CMS rescanning of dirty cards.
945}
946
Brian Carlstroma663ea52011-08-19 23:33:41 -0700947// Keep in sync with InitCallback. Anything we visit, we need to
948// reinit references to when reinitializing a ClassLinker from a
949// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -0800950void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800951 class_roots_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers50b35e22012-10-04 10:09:15 -0700952 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -0700953 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700954 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800955 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700956 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800957 dex_cache.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -0700958 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800959 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
960 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800961 dex_caches_[index].VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -0700962 }
Elliott Hughesf8349362012-06-18 15:00:06 -0700963 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800964 if ((flags & kVisitRootFlagClearRootLog) != 0) {
965 new_dex_cache_roots_.clear();
966 }
967 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
968 log_new_dex_caches_roots_ = true;
969 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
970 log_new_dex_caches_roots_ = false;
971 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700972 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700973 VisitClassRoots(callback, arg, flags);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800974 array_iftable_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700975 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -0800976 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800977 find_array_class_cache_[i].VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -0800978 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700979}
980
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700981void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
982 if (dex_cache_image_class_lookup_required_) {
983 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -0800984 }
Ian Rogersdbf3be02014-08-29 15:40:08 -0700985 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -0800986 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800987 for (GcRoot<mirror::Class>& root : class_table_) {
988 if (!visitor(root.Read(), arg)) {
989 return;
990 }
991 }
992 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
993 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800994 return;
995 }
996 }
997}
998
Ian Rogersdbf3be02014-08-29 15:40:08 -0700999static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001000 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001001 classes->insert(c);
1002 return true;
1003}
1004
Ian Rogersdbf3be02014-08-29 15:40:08 -07001005struct GetClassesVisitorArrayArg {
1006 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1007 int32_t index;
1008 bool success;
1009};
1010
1011static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1012 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1013 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1014 if (arg->index < (*arg->classes)->GetLength()) {
1015 (*arg->classes)->Set(arg->index, c);
1016 arg->index++;
1017 return true;
1018 } else {
1019 arg->success = false;
1020 return false;
1021 }
1022}
1023
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001024void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001025 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1026 // is avoiding duplicates.
1027 if (!kMovingClasses) {
1028 std::set<mirror::Class*> classes;
1029 VisitClasses(GetClassesVisitorSet, &classes);
1030 for (mirror::Class* klass : classes) {
1031 if (!visitor(klass, arg)) {
1032 return;
1033 }
1034 }
1035 } else {
1036 Thread* self = Thread::Current();
1037 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001038 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001039 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1040 GetClassesVisitorArrayArg local_arg;
1041 local_arg.classes = &classes;
1042 local_arg.success = false;
1043 // We size the array assuming classes won't be added to the class table during the visit.
1044 // If this assumption fails we iterate again.
1045 while (!local_arg.success) {
1046 size_t class_table_size;
1047 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001048 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001049 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001050 }
1051 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1052 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1053 classes.Assign(
1054 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1055 CHECK(classes.Get() != nullptr); // OOME.
1056 local_arg.index = 0;
1057 local_arg.success = true;
1058 VisitClasses(GetClassesVisitorArray, &local_arg);
1059 }
1060 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1061 // If the class table shrank during creation of the clases array we expect null elements. If
1062 // the class table grew then the loop repeats. If classes are created after the loop has
1063 // finished then we don't visit.
1064 mirror::Class* klass = classes->Get(i);
1065 if (klass != nullptr && !visitor(klass, arg)) {
1066 return;
1067 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001068 }
1069 }
1070}
1071
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001072ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001073 mirror::Class::ResetClass();
1074 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001075 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001076 mirror::ArtField::ResetClass();
1077 mirror::ArtMethod::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001078 mirror::Field::ResetClass();
1079 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001080 mirror::BooleanArray::ResetArrayClass();
1081 mirror::ByteArray::ResetArrayClass();
1082 mirror::CharArray::ResetArrayClass();
1083 mirror::DoubleArray::ResetArrayClass();
1084 mirror::FloatArray::ResetArrayClass();
1085 mirror::IntArray::ResetArrayClass();
1086 mirror::LongArray::ResetArrayClass();
1087 mirror::ShortArray::ResetArrayClass();
1088 mirror::Throwable::ResetClass();
1089 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001090 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001091}
1092
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001093mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001094 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001095 StackHandleScope<16> hs(self);
1096 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1097 Handle<mirror::DexCache> dex_cache(
1098 hs.NewHandle(down_cast<mirror::DexCache*>(
1099 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1100 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001101 if (dex_cache.Get() == nullptr) {
1102 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001103 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001104 Handle<mirror::String>
1105 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001106 if (location.Get() == nullptr) {
1107 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001108 }
Ian Rogers700a4022014-05-19 16:49:03 -07001109 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001110 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001111 if (strings.Get() == nullptr) {
1112 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001113 }
Ian Rogers700a4022014-05-19 16:49:03 -07001114 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001115 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001116 if (types.Get() == nullptr) {
1117 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001118 }
Ian Rogers700a4022014-05-19 16:49:03 -07001119 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001120 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001121 if (methods.Get() == nullptr) {
1122 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001123 }
Ian Rogers700a4022014-05-19 16:49:03 -07001124 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001125 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001126 if (fields.Get() == nullptr) {
1127 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001128 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001129 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1130 fields.Get());
1131 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001132}
1133
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001134mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001135 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001136 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001137 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001138 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001139 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001140 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1141 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001142 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001143 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001144 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001145 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001146 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001147}
1148
Ian Rogers6fac4472014-02-25 17:01:10 -08001149mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001150 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001151}
1152
Brian Carlstromea46f952013-07-30 01:26:50 -07001153mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001154 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001155 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001156}
1157
Brian Carlstromea46f952013-07-30 01:26:50 -07001158mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001159 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001160 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001161}
1162
Mathieu Chartier590fee92013-09-13 13:46:47 -07001163mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1164 Thread* self, size_t length) {
1165 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1166 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001167}
1168
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001169mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1170 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001171 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001172
1173 // For temporary classes we must wait for them to be retired.
1174 if (init_done_ && klass->IsTemp()) {
1175 CHECK(!klass->IsResolved());
1176 if (klass->IsErroneous()) {
1177 ThrowEarlierClassFailure(klass);
1178 return nullptr;
1179 }
1180 StackHandleScope<1> hs(self);
1181 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1182 ObjectLock<mirror::Class> lock(self, h_class);
1183 // Loop and wait for the resolving thread to retire this class.
1184 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1185 lock.WaitIgnoringInterrupts();
1186 }
1187 if (h_class->IsErroneous()) {
1188 ThrowEarlierClassFailure(h_class.Get());
1189 return nullptr;
1190 }
1191 CHECK(h_class->IsRetired());
1192 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001193 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
1194 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001195 }
1196
Brian Carlstromaded5f72011-10-07 17:15:04 -07001197 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001198 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001199 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001200 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1201 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001202 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001203 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1204 ThrowClassCircularityError(h_class.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001205 mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001206 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001207 }
1208 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001209 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001210 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001211 }
1212 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001213
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001214 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001215 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001216 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001217 }
1218 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001219 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001220 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001221 return klass;
1222}
1223
Ian Rogers68b56852014-08-29 20:19:11 -07001224typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
1225
1226// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001227ClassPathEntry FindInClassPath(const char* descriptor,
1228 size_t hash, const std::vector<const DexFile*>& class_path) {
1229 for (const DexFile* dex_file : class_path) {
1230 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001231 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07001232 return ClassPathEntry(dex_file, dex_class_def);
1233 }
1234 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001235 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07001236}
1237
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001238mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1239 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001240 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001241 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08001242 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001243 if (class_loader->GetClass() !=
1244 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
1245 class_loader->GetParent()->GetClass() !=
1246 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
1247 return nullptr;
1248 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001249 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001250 // Check if this would be found in the parent boot class loader.
1251 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001252 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001253 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08001254 // May return null if resolution on another thread fails.
1255 klass = EnsureResolved(self, descriptor, klass);
1256 } else {
1257 // May OOME.
1258 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
1259 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001260 }
Ian Rogers32427292014-11-19 14:05:21 -08001261 if (klass == nullptr) {
1262 CHECK(self->IsExceptionPending()) << descriptor;
1263 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001264 }
Ian Rogers32427292014-11-19 14:05:21 -08001265 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001266 } else {
Ian Rogers32427292014-11-19 14:05:21 -08001267 // Handle as if this is the child PathClassLoader.
1268 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001269 StackHandleScope<3> hs(self);
1270 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
1271 // We need to get the DexPathList and loop through it.
1272 Handle<mirror::ArtField> cookie_field =
1273 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
1274 Handle<mirror::ArtField> dex_file_field =
1275 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07001276 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001277 mirror::Object* dex_path_list =
1278 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
1279 GetObject(class_loader.Get());
1280 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
1281 cookie_field.Get() != nullptr) {
1282 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1283 mirror::Object* dex_elements_obj =
1284 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1285 GetObject(dex_path_list);
1286 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1287 // at the mCookie which is a DexFile vector.
1288 if (dex_elements_obj != nullptr) {
1289 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
1290 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
1291 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
1292 mirror::Object* element = dex_elements->GetWithoutChecks(i);
1293 if (element == nullptr) {
1294 // Should never happen, fall back to java code to throw a NPE.
1295 break;
1296 }
1297 mirror::Object* dex_file = dex_file_field->GetObject(element);
1298 if (dex_file != nullptr) {
Andreas Gampe324b9bb2015-02-23 16:33:22 -08001299 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
1300 if (long_array == nullptr) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001301 // This should never happen so log a warning.
1302 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
1303 break;
1304 }
Andreas Gampe324b9bb2015-02-23 16:33:22 -08001305 int32_t long_array_size = long_array->GetLength();
1306 for (int32_t j = 0; j < long_array_size; ++j) {
1307 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
1308 long_array->GetWithoutChecks(j)));
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001309 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001310 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001311 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001312 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
1313 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001314 if (klass == nullptr) {
1315 CHECK(self->IsExceptionPending()) << descriptor;
1316 self->ClearException();
1317 return nullptr;
1318 }
1319 return klass;
1320 }
1321 }
1322 }
1323 }
1324 }
1325 }
Ian Rogers32427292014-11-19 14:05:21 -08001326 self->AssertNoPendingException();
1327 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001328 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001329}
1330
Ian Rogers98379392014-02-24 16:53:16 -08001331mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001332 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001333 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001334 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001335 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001336 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001337 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1338 // for primitive classes that aren't backed by dex files.
1339 return FindPrimitiveClass(descriptor[0]);
1340 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001341 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001342 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001343 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07001344 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001345 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001346 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001347 // Class is not yet loaded.
1348 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001349 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001350 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001351 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001352 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07001353 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001354 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07001355 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07001356 } else {
1357 // The boot class loader is searched ahead of the application class loader, failures are
1358 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
1359 // trigger the chaining with a proper stack trace.
1360 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001361 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07001362 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05001363 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001364 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001365 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001366 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
1367 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001368 if (cp_klass != nullptr) {
1369 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07001370 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001371
1372 if (Runtime::Current()->IsAotCompiler()) {
1373 // Oops, compile-time, can't run actual class-loader code.
1374 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
1375 self->SetException(pre_allocated);
1376 return nullptr;
1377 }
1378
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001379 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001380 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001381 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07001382 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07001383 {
1384 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001385 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1386 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07001387 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001388 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07001389 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07001390 }
Ian Rogers68b56852014-08-29 20:19:11 -07001391 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001392 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1393 WellKnownClasses::java_lang_ClassLoader_loadClass,
1394 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001395 }
Ian Rogers98379392014-02-24 16:53:16 -08001396 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001397 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07001398 return nullptr;
1399 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08001400 // broken loader - throw NPE to be compatible with Dalvik
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001401 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
1402 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07001403 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08001404 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001405 // success, return mirror::Class*
1406 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001407 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001408 }
Ian Rogers07140832014-09-30 15:43:59 -07001409 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001410}
1411
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001412mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001413 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001414 const DexFile& dex_file,
1415 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001416 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001417 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001418
Brian Carlstromaded5f72011-10-07 17:15:04 -07001419 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001420 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001421 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001422 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001423 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001424 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001425 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001426 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001427 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001428 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1429 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001430 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001431 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001432 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001433 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001434 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001435 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001436 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001437 }
1438
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001439 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001440 // Allocate a class with the status of not ready.
1441 // Interface object should get the right size here. Regular class will
1442 // figure out the right size later and be replaced with one of the right
1443 // size when the class becomes resolved.
1444 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001445 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001446 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001447 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07001448 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001449 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001450 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07001451 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001452 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001453 if (self->IsExceptionPending()) {
1454 // An exception occured during load, set status to erroneous while holding klass' lock in case
1455 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001456 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001457 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001458 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001459 return nullptr;
1460 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001461 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001462
Mathieu Chartier590fee92013-09-13 13:46:47 -07001463 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001464 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001465 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001466 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1467 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001468 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001469 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001470
Brian Carlstromaded5f72011-10-07 17:15:04 -07001471 // Finish loading (if necessary) by finding parents
1472 CHECK(!klass->IsLoaded());
1473 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1474 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001475 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001476 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001477 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001478 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001479 }
1480 CHECK(klass->IsLoaded());
1481 // Link the class (if necessary)
1482 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001483 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001484 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001485
1486 mirror::Class* new_class = nullptr;
1487 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001488 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001489 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001490 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001491 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001492 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001493 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07001494 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001495 CHECK(new_class != nullptr) << descriptor;
1496 CHECK(new_class->IsResolved()) << descriptor;
1497
1498 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001499
Sebastien Hertza8a697f2015-01-15 12:28:47 +01001500 // Instrumentation may have updated entrypoints for all methods of all
1501 // classes. However it could not update methods of this class while we
1502 // were loading it. Now the class is resolved, we can update entrypoints
1503 // as required by instrumentation.
1504 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
1505 // We must be in the kRunnable state to prevent instrumentation from
1506 // suspending all threads to update entrypoints while we are doing it
1507 // for this class.
1508 DCHECK_EQ(self->GetState(), kRunnable);
1509 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(new_class_h.Get());
1510 }
1511
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001512 /*
1513 * We send CLASS_PREPARE events to the debugger from here. The
1514 * definition of "preparation" is creating the static fields for a
1515 * class and initializing them to the standard default values, but not
1516 * executing any code (that comes later, during "initialization").
1517 *
1518 * We did the static preparation in LinkClass.
1519 *
1520 * The class has been prepared and resolved but possibly not yet verified
1521 * at this point.
1522 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001523 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001524
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001525 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001526}
1527
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001528uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
1529 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07001530 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001531 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07001532 size_t num_8 = 0;
1533 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001534 size_t num_32 = 0;
1535 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001536 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001537 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1538 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001539 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001540 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07001541 switch (c) {
1542 case 'L':
1543 case '[':
1544 num_ref++;
1545 break;
1546 case 'J':
1547 case 'D':
1548 num_64++;
1549 break;
1550 case 'I':
1551 case 'F':
1552 num_32++;
1553 break;
1554 case 'S':
1555 case 'C':
1556 num_16++;
1557 break;
1558 case 'B':
1559 case 'Z':
1560 num_8++;
1561 break;
1562 default:
1563 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08001564 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001565 }
1566 }
1567 }
Fred Shih37f05ef2014-07-16 18:38:08 -07001568 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001569}
1570
Ian Rogers97b52f82014-08-14 11:34:07 -07001571OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
1572 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001573 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Richard Uhler07b3c232015-03-31 15:57:54 -07001574 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001575 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001576 *found = false;
1577 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001578 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001579 *found = true;
1580 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08001581}
1582
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001583static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
1584 uint32_t method_idx) {
1585 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07001586 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001587 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001588 ClassDataItemIterator it(dex_file, class_data);
1589 // Skip fields
1590 while (it.HasNextStaticField()) {
1591 it.Next();
1592 }
1593 while (it.HasNextInstanceField()) {
1594 it.Next();
1595 }
1596 // Process methods
1597 size_t class_def_method_index = 0;
1598 while (it.HasNextDirectMethod()) {
1599 if (it.GetMemberIndex() == method_idx) {
1600 return class_def_method_index;
1601 }
1602 class_def_method_index++;
1603 it.Next();
1604 }
1605 while (it.HasNextVirtualMethod()) {
1606 if (it.GetMemberIndex() == method_idx) {
1607 return class_def_method_index;
1608 }
1609 class_def_method_index++;
1610 it.Next();
1611 }
1612 DCHECK(!it.HasNext());
1613 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08001614 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001615}
1616
Ian Rogers97b52f82014-08-14 11:34:07 -07001617const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08001618 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001619 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001620 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08001621 size_t oat_method_index;
1622 if (method->IsStatic() || method->IsDirect()) {
1623 // Simple case where the oat method index was stashed at load time.
1624 oat_method_index = method->GetMethodIndex();
1625 } else {
1626 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1627 // by search for its position in the declared virtual methods.
1628 oat_method_index = declaring_class->NumDirectMethods();
1629 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001630 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001631 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07001632 // Check method index instead of identity in case of duplicate method definitions.
1633 if (method->GetDexMethodIndex() ==
1634 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001635 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001636 break;
1637 }
Ian Rogersf320b632012-03-13 18:47:47 -07001638 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001639 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001640 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
1641 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001642 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001643 DCHECK_EQ(oat_method_index,
1644 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001645 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001646 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07001647 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
1648 declaring_class->GetDexClassDefIndex(),
1649 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001650 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001651 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001652 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001653 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07001654}
1655
1656// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001657const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001658 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07001659 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001660 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07001661 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001662 bool found;
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001663 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1664 if (found) {
1665 auto* code = oat_method.GetQuickCode();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001666 if (code != nullptr) {
1667 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08001668 }
1669 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001670 jit::Jit* const jit = Runtime::Current()->GetJit();
1671 if (jit != nullptr) {
1672 auto* code = jit->GetCodeCache()->GetCodeFor(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001673 if (code != nullptr) {
1674 return code;
1675 }
1676 }
1677 if (method->IsNative()) {
1678 // No code and native? Use generic trampoline.
1679 return GetQuickGenericJniStub();
1680 }
1681 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07001682}
1683
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001684const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
1685 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
1686 return nullptr;
1687 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001688 bool found;
1689 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1690 if (found) {
1691 return oat_method.GetQuickCode();
1692 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001693 jit::Jit* jit = Runtime::Current()->GetJit();
1694 if (jit != nullptr) {
1695 auto* code = jit->GetCodeCache()->GetCodeFor(method);
1696 if (code != nullptr) {
1697 return code;
1698 }
1699 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001700 return nullptr;
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001701}
1702
Ian Rogersef7d42f2014-01-06 12:55:46 -08001703const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
1704 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001705 bool found;
1706 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
1707 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001708 return nullptr;
1709 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001710 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001711 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001712}
1713
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001714// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001715static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07001716 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08001717 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001718 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08001719 // May return true for native code, in the case of generic JNI
1720 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001721 return true;
1722 }
1723 // If interpreter mode is enabled, every method (except native and proxy) must
1724 // be run with interpreter.
1725 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
1726 !method->IsNative() && !method->IsProxyMethod();
1727}
1728
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001729void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08001730 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07001731 if (klass->NumDirectMethods() == 0) {
1732 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08001733 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001734 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001735 if (!runtime->IsStarted()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001736 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001737 return; // OAT file unavailable.
1738 }
Ian Rogers19846512012-02-24 11:42:47 -08001739 }
Alex Light64ad14d2014-08-19 14:23:13 -07001740
Mathieu Chartierf8322842014-05-16 10:59:25 -07001741 const DexFile& dex_file = klass->GetDexFile();
1742 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07001743 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07001744 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07001745 // There should always be class data if there were direct methods.
1746 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08001747 ClassDataItemIterator it(dex_file, class_data);
1748 // Skip fields
1749 while (it.HasNextStaticField()) {
1750 it.Next();
1751 }
1752 while (it.HasNextInstanceField()) {
1753 it.Next();
1754 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001755 bool has_oat_class;
1756 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1757 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07001758 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001759 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001760 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001761 if (!method->IsStatic()) {
1762 // Only update static methods.
1763 continue;
Ian Rogers19846512012-02-24 11:42:47 -08001764 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001765 const void* quick_code = nullptr;
1766 if (has_oat_class) {
1767 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001768 quick_code = oat_method.GetQuickCode();
1769 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001770 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001771 if (enter_interpreter) {
1772 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07001773 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001774 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001775 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08001776 } else {
1777 quick_code = GetQuickToInterpreterBridge();
1778 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001779 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001780 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08001781 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001782 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08001783}
1784
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001785void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07001786 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001787 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001788 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001789 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001790 // The following code only applies to a non-compiler runtime.
1791 return;
1792 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001793 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001794 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001795 if (oat_class != nullptr) {
1796 // Every kind of method should at least get an invoke stub from the oat_method.
1797 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001798 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001799 oat_method.LinkMethod(method.Get());
1800 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001801
Jeff Hao16743632013-05-08 10:59:04 -07001802 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001803 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08001804 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001805 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001806 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001807 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07001808 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001809 }
1810
Brian Carlstrom92827a52011-10-10 15:50:01 -07001811 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001812 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001813 return;
1814 }
Ian Rogers19846512012-02-24 11:42:47 -08001815
1816 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001817 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001818 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
1819 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001820 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001821 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001822 if (!method->IsNative()) {
1823 // Set entry point from compiled code if there's no code or in interpreter only mode.
1824 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001825 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001826 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001827 }
Ian Rogers0d6de042012-02-29 08:50:26 -08001828 }
jeffhao26c0a1a2012-01-17 16:28:33 -08001829
Ian Rogers62d6c772013-02-27 08:32:07 -08001830 if (method->IsNative()) {
1831 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001832 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07001833
1834 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001835 // We have a native method here without code. Then it should have either the generic JNI
1836 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
1837 // TODO: this doesn't handle all the cases where trampolines may be installed.
1838 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1839 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07001840 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001841 }
1842}
1843
Fred Shih37f05ef2014-07-16 18:38:08 -07001844
Fred Shih37f05ef2014-07-16 18:38:08 -07001845
Ian Rogers7b078e82014-09-10 14:44:24 -07001846void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07001847 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001848 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001849 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001850 CHECK(klass.Get() != nullptr);
1851 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001852 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001853 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001854 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001855
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001856 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07001857 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07001858 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001859 klass->SetAccessFlags(access_flags);
1860 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001861 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001862 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001863
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001864 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001865 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08001866 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001867
Ian Rogers13735952014-10-08 12:43:28 -07001868 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001869 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001870 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001871 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001872
Ian Rogers97b52f82014-08-14 11:34:07 -07001873
1874 bool has_oat_class = false;
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001875 if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001876 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1877 &has_oat_class);
1878 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001879 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07001880 }
1881 }
1882 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001883 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001884 }
1885}
1886
Ian Rogers7b078e82014-09-10 14:44:24 -07001887void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07001888 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001889 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001890 const OatFile::OatClass* oat_class) {
1891 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07001892 ClassDataItemIterator it(dex_file, class_data);
1893 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001894 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001895 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001896 CHECK(self->IsExceptionPending()); // OOME.
1897 return;
1898 }
1899 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07001900 }
1901 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001902 mirror::ObjectArray<mirror::ArtField>* fields =
1903 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001904 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001905 CHECK(self->IsExceptionPending()); // OOME.
1906 return;
1907 }
1908 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07001909 }
1910 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001911 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001912 StackHandleScope<1> hs(self);
1913 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001914 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001915 CHECK(self->IsExceptionPending()); // OOME.
1916 return;
1917 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001918 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07001919 LoadField(dex_file, it, klass, sfield);
1920 }
1921 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001922 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001923 StackHandleScope<1> hs(self);
1924 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001925 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001926 CHECK(self->IsExceptionPending()); // OOME.
1927 return;
1928 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001929 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07001930 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001931 }
1932
Ian Rogers0571d352011-11-03 19:51:38 -07001933 // Load methods.
1934 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001935 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07001936 mirror::ObjectArray<mirror::ArtMethod>* directs =
1937 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001938 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001939 CHECK(self->IsExceptionPending()); // OOME.
1940 return;
1941 }
1942 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001943 }
Ian Rogers0571d352011-11-03 19:51:38 -07001944 if (it.NumVirtualMethods() != 0) {
1945 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07001946 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
1947 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001948 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001949 CHECK(self->IsExceptionPending()); // OOME.
1950 return;
1951 }
1952 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001953 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001954 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07001955 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
1956 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001957 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001958 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001959 StackHandleScope<1> hs(self);
1960 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001961 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001962 CHECK(self->IsExceptionPending()); // OOME.
1963 return;
1964 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001965 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001966 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07001967 uint32_t it_method_index = it.GetMemberIndex();
1968 if (last_dex_method_index == it_method_index) {
1969 // duplicate case
1970 method->SetMethodIndex(last_class_def_method_index);
1971 } else {
1972 method->SetMethodIndex(class_def_method_index);
1973 last_dex_method_index = it_method_index;
1974 last_class_def_method_index = class_def_method_index;
1975 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001976 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001977 }
1978 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001979 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001980 StackHandleScope<1> hs(self);
1981 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001982 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001983 CHECK(self->IsExceptionPending()); // OOME.
1984 return;
1985 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001986 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08001987 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001988 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001989 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001990 }
1991 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001992}
1993
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001994void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001995 Handle<mirror::Class> klass,
1996 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001997 uint32_t field_idx = it.GetMemberIndex();
1998 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001999 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002000 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002001}
2002
Brian Carlstromea46f952013-07-30 01:26:50 -07002003mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002004 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002005 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002006 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002007 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002008 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002009
Brian Carlstromea46f952013-07-30 01:26:50 -07002010 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002011 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002012 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002013 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002014 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002015 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002016
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002017 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002018 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002019 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002020 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002021
Ian Rogers19846512012-02-24 11:42:47 -08002022 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002023 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002024
Andreas Gampe51829322014-08-25 15:05:04 -07002025 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002026
Ian Rogersdfb325e2013-10-30 01:00:44 -07002027 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002028 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002029 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2030 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002031 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002032 klass->SetFinalizable();
2033 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002034 std::string temp;
2035 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002036 // The Enum class declares a "final" finalize() method to prevent subclasses from
2037 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2038 // subclasses, so we exclude it here.
2039 // We also want to avoid setting the flag on Object, where we know that finalize() is
2040 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002041 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2042 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002043 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002044 }
2045 }
2046 }
2047 } else if (method_name[0] == '<') {
2048 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002049 bool is_init = (strcmp("<init>", method_name) == 0);
2050 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002051 if (UNLIKELY(!is_init && !is_clinit)) {
2052 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2053 } else {
2054 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2055 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002056 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002057 access_flags |= kAccConstructor;
2058 }
2059 }
2060 }
2061 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002062
Mathieu Chartier66f19252012-09-18 08:57:04 -07002063 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002064}
2065
Ian Rogers7b078e82014-09-10 14:44:24 -07002066void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002067 StackHandleScope<1> hs(self);
2068 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002069 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2070 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002071 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002072}
2073
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002074void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002075 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002076 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002077 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002078 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002079}
2080
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002081bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002082 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002083 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002084 mirror::DexCache* dex_cache = GetDexCache(i);
2085 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002086 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002087 }
2088 }
2089 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002090}
2091
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002092bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002093 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002094 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002095}
2096
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002097void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002098 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002099 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002100 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002101 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2102 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002103 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002104 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002105 if (log_new_dex_caches_roots_) {
2106 // TODO: This is not safe if we can remove dex caches.
2107 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2108 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002109}
2110
Brian Carlstromaded5f72011-10-07 17:15:04 -07002111void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002112 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002113 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002114 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002115 if (IsDexFileRegisteredLocked(dex_file)) {
2116 return;
2117 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002118 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002119 // Don't alloc while holding the lock, since allocation may need to
2120 // suspend all threads and another thread may need the dex_lock_ to
2121 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002122 StackHandleScope<1> hs(self);
2123 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002124 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2125 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002126 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002127 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002128 if (IsDexFileRegisteredLocked(dex_file)) {
2129 return;
2130 }
2131 RegisterDexFileLocked(dex_file, dex_cache);
2132 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002133}
2134
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002135void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002136 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002137 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002138 RegisterDexFileLocked(dex_file, dex_cache);
2139}
2140
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002141mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002142 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002143 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002144 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002145 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002146 if (dex_cache->GetDexFile() == &dex_file) {
2147 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002148 }
2149 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002150 // Search matching by location name.
2151 std::string location(dex_file.GetLocation());
2152 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002153 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002154 if (dex_cache->GetDexFile()->GetLocation() == location) {
2155 return dex_cache;
2156 }
2157 }
2158 // Failure, dump diagnostic and abort.
2159 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002160 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002161 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2162 }
2163 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002164 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002165}
2166
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002167void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002168 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08002169 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002170 mirror::DexCache* dex_cache = GetDexCache(i);
2171 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08002172 }
2173}
2174
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002175mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002176 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002177 if (UNLIKELY(klass == nullptr)) {
2178 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002179 }
2180 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002181}
2182
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002183mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2184 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002185 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07002186 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002187 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002188 StackHandleScope<1> hs(self);
2189 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002190 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002191 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
2192 h_class->SetPrimitiveType(type);
2193 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002194 const char* descriptor = Primitive::Descriptor(type);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002195 mirror::Class* existing = InsertClass(descriptor, h_class.Get(),
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002196 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002197 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002198 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07002199}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002200
Brian Carlstrombe977852011-07-19 14:54:54 -07002201// Create an array class (i.e. the class object for the array, not the
2202// array itself). "descriptor" looks like "[C" or "[[[[B" or
2203// "[Ljava/lang/String;".
2204//
2205// If "descriptor" refers to an array of primitives, look up the
2206// primitive type's internally-generated class object.
2207//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002208// "class_loader" is the class loader of the class that's referring to
2209// us. It's used to ensure that we're looking for the element type in
2210// the right context. It does NOT become the class loader for the
2211// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002212//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002213// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002214mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002215 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002216 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002217 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002218 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002219 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
2220 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002221 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002222 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002223 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002224 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
2225 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002226 if (component_type.Get() == nullptr) {
2227 DCHECK(self->IsExceptionPending());
2228 return nullptr;
2229 } else {
2230 self->ClearException();
2231 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002232 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002233 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2234 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2235 return nullptr;
2236 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002237 // See if the component type is already loaded. Array classes are
2238 // always associated with the class loader of their underlying
2239 // element type -- an array of Strings goes with the loader for
2240 // java/lang/String -- so we need to look for it there. (The
2241 // caller should have checked for the existence of the class
2242 // before calling here, but they did so with *their* class loader,
2243 // not the component type's loader.)
2244 //
2245 // If we find it, the caller adds "loader" to the class' initiating
2246 // loader list, which should prevent us from going through this again.
2247 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002248 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002249 // are the same, because our caller (FindClass) just did the
2250 // lookup. (Even if we get this wrong we still have correct behavior,
2251 // because we effectively do this lookup again when we add the new
2252 // class to the hash table --- necessary because of possible races with
2253 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002254 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002255 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002256 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002257 return new_class;
2258 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002259 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002260
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002261 // Fill out the fields in the Class.
2262 //
2263 // It is possible to execute some methods against arrays, because
2264 // all arrays are subclasses of java_lang_Object_, so we need to set
2265 // up a vtable. We can just point at the one in java_lang_Object_.
2266 //
2267 // Array classes are simple enough that we don't need to do a full
2268 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002269 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002270 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002271 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002272 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002273 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002274 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002275 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002276 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002277 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002278 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002279 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002280 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002281 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002282 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002283 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002284 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002285 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002286 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002287 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002288 }
2289 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002290 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002291 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002292 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002293 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002294 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002295 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002296 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002297 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002298 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002299 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002300 new_class->SetSuperClass(java_lang_Object);
2301 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002302 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002303 new_class->SetClassLoader(component_type->GetClassLoader());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002304 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002305 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002306 StackHandleScope<mirror::Class::kImtSize> hs2(self,
2307 Runtime::Current()->GetImtUnimplementedMethod());
2308 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002309 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002310 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002311 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002312 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002313
2314
2315 // All arrays have java/lang/Cloneable and java/io/Serializable as
2316 // interfaces. We need to set that up here, so that stuff like
2317 // "instanceof" works right.
2318 //
2319 // Note: The GC could run during the call to FindSystemClass,
2320 // so we need to make sure the class object is GC-valid while we're in
2321 // there. Do this by clearing the interface list so the GC will just
2322 // think that the entries are null.
2323
2324
2325 // Use the single, global copies of "interfaces" and "iftable"
2326 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002327 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002328 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002329 CHECK(array_iftable != nullptr);
2330 new_class->SetIfTable(array_iftable);
2331 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002332
Elliott Hughes00626c22013-06-14 15:04:14 -07002333 // Inherit access flags from the component type.
2334 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2335 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2336 access_flags &= kAccJavaFlagsMask;
2337 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002338 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002339 access_flags |= kAccAbstract | kAccFinal;
2340 access_flags &= ~kAccInterface;
2341
2342 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002343
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002344 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002345 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002346 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002347 }
2348 // Another thread must have loaded the class after we
2349 // started but before we finished. Abandon what we've
2350 // done.
2351 //
2352 // (Yes, this happens.)
2353
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002354 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002355}
2356
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002357mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002358 switch (type) {
2359 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002360 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002361 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002362 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002363 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002364 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002365 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002366 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002367 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002368 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002369 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002370 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002371 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002372 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002373 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002374 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002375 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002376 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002377 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002378 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002379 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002380 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002381 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002382 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002383}
2384
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002385mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2386 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002387 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002388 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002389 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002390 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08002391 source += " from ";
2392 source += dex_cache->GetLocation()->ToModifiedUtf8();
2393 }
2394 LOG(INFO) << "Loaded class " << descriptor << source;
2395 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002396 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002397 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002398 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002399 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002400 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002401 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002402 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002403 // Check a class loaded with the system class loader matches one in the image if the class
2404 // is in the image.
2405 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002406 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002407 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002408 }
2409 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002410 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002411 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002412 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002413 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002414 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002415 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002416}
2417
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002418mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
2419 size_t hash) {
2420 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002421 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
2422 hash);
2423 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002424 CHECK(klass->IsProxyClass());
2425 return nullptr;
2426 }
2427
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002428 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002429 CHECK_NE(existing, klass) << descriptor;
2430 CHECK(!existing->IsResolved()) << descriptor;
2431 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
2432
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002433 CHECK(!klass->IsTemp()) << descriptor;
2434 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
2435 dex_cache_image_class_lookup_required_) {
2436 // Check a class loaded with the system class loader matches one in the image if the class
2437 // is in the image.
2438 existing = LookupClassFromImage(descriptor);
2439 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002440 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002441 }
2442 }
2443 VerifyObject(klass);
2444
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002445 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002446 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002447 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002448 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002449 }
2450
2451 return existing;
2452}
2453
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002454bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002455 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002456 auto pair = std::make_pair(descriptor, class_loader);
2457 auto it = class_table_.Find(pair);
2458 if (it != class_table_.end()) {
2459 class_table_.Erase(it);
2460 return true;
2461 }
2462 it = pre_zygote_class_table_.Find(pair);
2463 if (it != pre_zygote_class_table_.end()) {
2464 pre_zygote_class_table_.Erase(it);
2465 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08002466 }
2467 return false;
2468}
2469
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002470mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002471 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002472 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002473 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002474 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002475 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002476 return result;
2477 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07002478 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002479 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
2480 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002481 } else {
2482 // Lookup failed but need to search dex_caches_.
2483 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002484 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002485 InsertClass(descriptor, result, hash);
2486 } else {
2487 // Searching the image dex files/caches failed, we don't want to get into this situation
2488 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2489 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07002490 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002491 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2492 MoveImageClassesToClassTable();
2493 }
2494 }
2495 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002496 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002497}
2498
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002499mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002500 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002501 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002502 auto descriptor_pair = std::make_pair(descriptor, class_loader);
2503 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
2504 if (it == pre_zygote_class_table_.end()) {
2505 it = class_table_.FindWithHash(descriptor_pair, hash);
2506 if (it == class_table_.end()) {
2507 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07002508 }
2509 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002510 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002511}
2512
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002513static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
2514 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2515 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002516 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002517 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2518 return root->AsObjectArray<mirror::DexCache>();
2519}
2520
2521void ClassLinker::MoveImageClassesToClassTable() {
2522 Thread* self = Thread::Current();
2523 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2524 if (!dex_cache_image_class_lookup_required_) {
2525 return; // All dex cache classes are already in the class table.
2526 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002527 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002528 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002529 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002530 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2531 mirror::DexCache* dex_cache = dex_caches->Get(i);
2532 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
2533 for (int32_t j = 0; j < types->GetLength(); j++) {
2534 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002535 if (klass != nullptr) {
2536 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002537 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002538 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002539 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
2540 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002541 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002542 << PrettyClassAndClassLoader(klass);
2543 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002544 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002545 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002546 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002547 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002548 }
2549 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002550 }
2551 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002552 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002553}
2554
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002555void ClassLinker::MoveClassTableToPreZygote() {
2556 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2557 DCHECK(pre_zygote_class_table_.Empty());
2558 pre_zygote_class_table_ = std::move(class_table_);
2559 class_table_.Clear();
2560}
2561
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002562mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002563 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002564 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2565 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
2566 mirror::DexCache* dex_cache = dex_caches->Get(i);
2567 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00002568 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002569 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002570 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002571 const DexFile::TypeId* type_id =
2572 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002573 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002574 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
2575 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002576 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002577 return klass;
2578 }
2579 }
2580 }
2581 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002582 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002583}
2584
2585void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
2586 result.clear();
2587 if (dex_cache_image_class_lookup_required_) {
2588 MoveImageClassesToClassTable();
2589 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002590 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2591 while (true) {
2592 auto it = class_table_.Find(descriptor);
2593 if (it == class_table_.end()) {
2594 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002595 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002596 result.push_back(it->Read());
2597 class_table_.Erase(it);
2598 }
2599 for (mirror::Class* k : result) {
2600 class_table_.Insert(GcRoot<mirror::Class>(k));
2601 }
2602 size_t pre_zygote_start = result.size();
2603 // Now handle the pre zygote table.
2604 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
2605 // called from the debugger.
2606 while (true) {
2607 auto it = pre_zygote_class_table_.Find(descriptor);
2608 if (it == pre_zygote_class_table_.end()) {
2609 break;
2610 }
2611 result.push_back(it->Read());
2612 pre_zygote_class_table_.Erase(it);
2613 }
2614 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
2615 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002616 }
2617}
2618
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002619void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002620 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002621 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08002622
Ian Rogers9ffb0392012-09-10 11:56:50 -07002623 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002624 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07002625 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07002626 return;
2627 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002628 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002629 return;
2630 }
jeffhao98eacac2011-09-14 16:11:53 -07002631
Ian Rogers9ffb0392012-09-10 11:56:50 -07002632 // The class might already be erroneous, for example at compile time if we attempted to verify
2633 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002634 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002635 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002636 return;
2637 }
2638
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002639 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002640 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002641 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002642 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002643 << PrettyClass(klass.Get());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002644 CHECK(!Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002645 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002646 }
jeffhao98eacac2011-09-14 16:11:53 -07002647
Jeff Hao4a200f52014-04-01 14:58:49 -07002648 // Skip verification if disabled.
2649 if (!Runtime::Current()->IsVerificationEnabled()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002650 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07002651 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07002652 return;
2653 }
2654
Ian Rogers9ffb0392012-09-10 11:56:50 -07002655 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002656 StackHandleScope<2> hs(self);
2657 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002658 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07002659 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002660 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002661
2662 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002663 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002664 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002665 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07002666 std::string error_msg(
2667 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
2668 PrettyDescriptor(klass.Get()).c_str(),
2669 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08002670 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002671 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002672 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002673 self->ClearException();
2674 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002675 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
2676 if (cause.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002677 self->GetException()->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002678 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08002679 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002680 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00002681 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
2682 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002683 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002684 return;
2685 }
2686 }
2687
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002688 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07002689 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002690 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002691 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002692 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002693 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002694 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002695 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002696 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
2697 PrettyDescriptor(klass.Get()).c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002698 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07002699 return;
2700 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002701 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08002702 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07002703 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002704 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002705 Runtime::Current()->IsAotCompiler(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002706 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002707 }
2708 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07002709 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002710 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07002711 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2712 << " because: " << error_msg;
2713 }
Ian Rogers1f539342012-10-03 21:09:42 -07002714 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002715 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002716 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002717 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002718 // Even though there were no verifier failures we need to respect whether the super-class
2719 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002720 if (super.Get() == nullptr || super->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002721 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002722 } else {
2723 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002724 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002725 // Pretend a soft failure occured so that we don't consider the class verified below.
2726 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002727 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002728 } else {
2729 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
2730 // Soft failures at compile time should be retried at runtime. Soft
2731 // failures at runtime will be handled by slow paths in the generated
2732 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002733 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002734 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002735 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002736 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002737 // As this is a fake verified status, make sure the methods are _not_ marked preverified
2738 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07002739 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002740 }
2741 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07002742 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002743 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08002744 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2745 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002746 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002747 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002748 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002749 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002750 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002751 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002752 // Let the interpreter know it by setting the kAccPreverified flag onto each
2753 // method.
2754 // Note: we're going here during compilation and at runtime. When we set the
2755 // kAccPreverified flag when compiling image classes, the flag is recorded
2756 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07002757 EnsurePreverifiedMethods(klass);
2758 }
2759}
2760
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002761void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002762 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002763 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07002764 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002765 }
jeffhao98eacac2011-09-14 16:11:53 -07002766}
2767
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002768bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
2769 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002770 // If we're compiling, we can only verify the class using the oat file if
2771 // we are not compiling the image or if the class we're verifying is not part of
2772 // the app. In other words, we will only check for preverification of bootclasspath
2773 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002774 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002775 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002776 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002777 return false;
2778 }
2779 // We are compiling an app (not the image).
2780
2781 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002782 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002783 return false;
2784 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002785 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002786
Richard Uhler07b3c232015-03-31 15:57:54 -07002787 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002788 // In case we run without an image there won't be a backing oat file.
2789 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07002790 return false;
2791 }
2792
Andreas Gampe76bd8802014-12-10 16:43:58 -08002793 // We may be running with a preopted oat file but without image. In this case,
2794 // we don't skip verification of preverified classes to ensure we initialize
2795 // dex caches with all types resolved during verification.
2796 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
2797 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
2798 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
2799 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002800 if (!Runtime::Current()->IsAotCompiler() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08002801 !Runtime::Current()->GetHeap()->HasImageSpace() &&
2802 klass->GetClassLoader() != nullptr) {
2803 return false;
2804 }
2805
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002806 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002807 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002808 if (oat_file_class_status == mirror::Class::kStatusVerified ||
2809 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002810 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002811 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002812 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07002813 // Compile time verification failed with a soft error. Compile time verification can fail
2814 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08002815 // class ... {
2816 // Foo x;
2817 // .... () {
2818 // if (...) {
2819 // v1 gets assigned a type of resolved class Foo
2820 // } else {
2821 // v1 gets assigned a type of unresolved class Bar
2822 // }
2823 // iput x = v1
2824 // } }
2825 // when we merge v1 following the if-the-else it results in Conflict
2826 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2827 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2828 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2829 // at compile time).
2830 return false;
2831 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002832 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07002833 // Compile time verification failed with a hard error. This is caused by invalid instructions
2834 // in the class. These errors are unrecoverable.
2835 return false;
2836 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002837 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002838 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2839 // not loading the class.
2840 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2841 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002842 return false;
2843 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002844 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002845 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002846 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07002847 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08002848 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002849}
2850
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002851void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002852 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002853 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2854 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2855 }
2856 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2857 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2858 }
2859}
2860
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002861void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07002862 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002863 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2864 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002865 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002866 return; // native or abstract method
2867 }
2868 if (code_item->tries_size_ == 0) {
2869 return; // nothing to process
2870 }
Ian Rogers13735952014-10-08 12:43:28 -07002871 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002872 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2873 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2874 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2875 CatchHandlerIterator iterator(handlers_ptr);
2876 for (; iterator.HasNext(); iterator.Next()) {
2877 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2878 // unresolved exception types will be ignored by exception delivery
2879 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002880 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002881 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002882 DCHECK(Thread::Current()->IsExceptionPending());
2883 Thread::Current()->ClearException();
2884 }
2885 }
2886 }
2887 handlers_ptr = iterator.EndDataPointer();
2888 }
2889}
2890
Brian Carlstromea46f952013-07-30 01:26:50 -07002891static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002892static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
2893 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08002894
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07002895mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07002896 jobjectArray interfaces, jobject loader,
2897 jobjectArray methods, jobjectArray throws) {
2898 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002899 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002900 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002901 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002902 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002903 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002904 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002905 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002906 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002907 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07002908 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
2909 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002910 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08002911 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002912 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002913 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002914 klass->SetDexCache(proxy_class->GetDexCache());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002915 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08002916
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002917 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07002918 {
2919 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002920 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002921 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002922 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002923 }
2924 klass->SetSFields(sfields);
2925 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002926 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
2927 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002928 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
2929 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002930 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002931 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002932 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002933 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002934 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002935 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002936 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
2937 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002938 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
2939 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002940 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002941 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002942 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002943 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002944 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002945 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002946 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002947
Ian Rogers466bb252011-10-14 03:29:56 -07002948 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07002949 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002950 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002951 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002952 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002953 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002954 }
2955 klass->SetDirectMethods(directs);
2956 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002957 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002958 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002959 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002960 }
2961 klass->SetDirectMethod(0, constructor);
2962 }
Jesse Wilson95caa792011-10-12 18:14:17 -04002963
Mathieu Chartier590fee92013-09-13 13:46:47 -07002964 // Create virtual method using specified prototypes.
2965 size_t num_virtual_methods =
2966 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07002967 {
Brian Carlstromf3632832014-05-20 15:36:53 -07002968 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
2969 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002970 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002971 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002972 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002973 }
2974 klass->SetVirtualMethods(virtuals);
2975 }
Jesse Wilson95caa792011-10-12 18:14:17 -04002976 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002977 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002978 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
2979 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002980 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07002981 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002982 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002983 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002984 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002985 }
2986 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04002987 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002988
2989 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002990 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08002991 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08002992
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002993 std::string descriptor(GetDescriptorForProxy(klass.Get()));
2994 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07002995 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002996 // Must hold lock on object when resolved.
2997 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002998 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002999 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003000 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003001 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003002 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003003 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003004 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003005 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003006
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003007 CHECK(klass->IsRetired());
3008 CHECK_NE(klass.Get(), new_class);
3009 klass.Assign(new_class);
3010
3011 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003012 interfaces_sfield->SetObject<false>(klass.Get(),
3013 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003014 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003015 throws_sfield->SetObject<false>(klass.Get(),
3016 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003017
3018 {
3019 // Lock on klass is released. Lock new class object.
3020 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003021 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003022 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003023
3024 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003025 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003026 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003027 CheckProxyConstructor(klass->GetDirectMethod(0));
3028 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003029 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003030 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3031 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003032 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3033 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003034 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003035 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003036
Mathieu Chartier590fee92013-09-13 13:46:47 -07003037 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003038 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003039 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003040 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3041
3042 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003043 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003044 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003045
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003046 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003047 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003048 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003049 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003050 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003051 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3052 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003053 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003054 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003055}
3056
Ian Rogersef7d42f2014-01-06 12:55:46 -08003057std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003058 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003059 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003060 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003061 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3062}
3063
Ian Rogersef7d42f2014-01-06 12:55:46 -08003064mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3065 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003066 DCHECK(proxy_class->IsProxyClass());
3067 DCHECK(proxy_method->IsProxyMethod());
3068 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003069 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003070 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003071 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003072 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003073 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003074 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003075 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003076 break;
3077 }
3078 }
3079 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003080 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003081 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003082 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003083 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003084 return resolved_method;
3085}
3086
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003087
Brian Carlstromea46f952013-07-30 01:26:50 -07003088mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003089 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003090 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003091 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003092 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003093 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003094 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3095 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003096 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3097 // constructor method.
3098 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3099 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003100 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3101 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003102 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3103 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003104 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003105 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003106 }
Ian Rogers466bb252011-10-14 03:29:56 -07003107 // Make this constructor public and fix the class to be our Proxy version
3108 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003109 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003110 return constructor;
3111}
3112
Brian Carlstromea46f952013-07-30 01:26:50 -07003113static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003114 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003115 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003116 CHECK_STREQ(constructor->GetName(), "<init>");
3117 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3118 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003119 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003120}
3121
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003122mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003123 Handle<mirror::Class> klass,
3124 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003125 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3126 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003127 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003128 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003129 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003130 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003131 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003132 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003133 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003134 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003135 }
Ian Rogers466bb252011-10-14 03:29:56 -07003136
3137 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3138 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003139 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003140 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003141
Ian Rogers466bb252011-10-14 03:29:56 -07003142 // At runtime the method looks like a reference and argument saving method, clone the code
3143 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003144 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003145 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003146
Ian Rogersc2b44472011-12-14 21:17:17 -08003147 return method;
3148}
Jesse Wilson95caa792011-10-12 18:14:17 -04003149
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003150static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3151 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003152 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003153 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003154 CHECK(!prototype->IsFinal());
3155 CHECK(method->IsFinal());
3156 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003157
3158 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3159 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07003160 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
3161 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08003162 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3163
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003164 CHECK_STREQ(method->GetName(), prototype->GetName());
3165 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003166 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07003167 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04003168}
3169
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003170static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3171 bool can_init_parents)
3172 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003173 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003174 return true;
3175 }
3176 if (!can_init_statics) {
3177 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07003178 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003179 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003180 return false;
3181 }
3182 // Check if there are encoded static values needing initialization.
3183 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003184 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003185 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003186 if (dex_class_def->static_values_off_ != 0) {
3187 return false;
3188 }
3189 }
3190 }
3191 if (!klass->IsInterface() && klass->HasSuperClass()) {
3192 mirror::Class* super_class = klass->GetSuperClass();
3193 if (!can_init_parents && !super_class->IsInitialized()) {
3194 return false;
3195 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003196 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003197 return false;
3198 }
3199 }
3200 }
3201 return true;
3202}
3203
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003204bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07003205 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003206 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3207
3208 // Are we already initialized and therefore done?
3209 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3210 // an initialized class will never change its state.
3211 if (klass->IsInitialized()) {
3212 return true;
3213 }
3214
3215 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003216 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003217 return false;
3218 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003219
Ian Rogers7b078e82014-09-10 14:44:24 -07003220 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003221 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003222 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003223 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003224
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003225 // Re-check under the lock in case another thread initialized ahead of us.
3226 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003227 return true;
3228 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003229
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003230 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003231 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003232 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003233 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003234 return false;
3235 }
3236
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003237 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003238
3239 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003240 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003241 if (!klass->IsVerified()) {
3242 // We failed to verify, expect either the klass to be erroneous or verification failed at
3243 // compile time.
3244 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003245 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003246 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003247 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003248 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003249 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003250 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003251 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07003252 } else {
3253 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003254 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003255 }
3256
Brian Carlstromd1422f82011-09-28 11:37:09 -07003257 // If the class is kStatusInitializing, either this thread is
3258 // initializing higher up the stack or another thread has beat us
3259 // to initializing and we need to wait. Either way, this
3260 // invocation of InitializeClass will not be responsible for
3261 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003262 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07003263 // Could have got an exception during verification.
3264 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003265 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003266 return false;
3267 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003268 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003269 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003270 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003271 return true;
3272 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003273 // No. That's fine. Wait for another thread to finish initializing.
3274 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003275 }
3276
3277 if (!ValidateSuperClassDescriptors(klass)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003278 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003279 return false;
3280 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003281 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003282
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003283 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003284
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003285 // From here out other threads may observe that we're initializing and so changes of state
3286 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003287 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003288 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003289
3290 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003291 }
3292
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003293 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003294 if (!klass->IsInterface() && klass->HasSuperClass()) {
3295 mirror::Class* super_class = klass->GetSuperClass();
3296 if (!super_class->IsInitialized()) {
3297 CHECK(!super_class->IsInterface());
3298 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003299 StackHandleScope<1> hs(self);
3300 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07003301 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003302 if (!super_initialized) {
3303 // The super class was verified ahead of entering initializing, we should only be here if
3304 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003305 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003306 << "Super class initialization failed for "
3307 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003308 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003309 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003310 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003311 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003312 // Initialization failed because the super-class is erroneous.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003313 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003314 return false;
3315 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003316 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003317 }
3318
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003319 const size_t num_static_fields = klass->NumStaticFields();
3320 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003321 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003322 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003323 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07003324 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003325 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003326 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003327
3328 // Eagerly fill in static fields so that the we don't have to do as many expensive
3329 // Class::FindStaticField in ResolveField.
3330 for (size_t i = 0; i < num_static_fields; ++i) {
3331 mirror::ArtField* field = klass->GetStaticField(i);
3332 const uint32_t field_idx = field->GetDexFieldIndex();
3333 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
3334 if (resolved_field == nullptr) {
3335 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07003336 } else {
3337 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003338 }
3339 }
3340
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003341 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
3342 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07003343 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003344 ClassDataItemIterator field_it(dex_file, class_data);
3345 if (value_it.HasNext()) {
3346 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003347 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003348 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003349 StackHandleScope<1> hs2(self);
3350 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003351 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003352 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003353 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003354 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003355 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003356 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003357 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003358 }
3359 }
3360 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003361
Ian Rogersd91d6d62013-09-25 20:26:14 -07003362 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003363 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003364 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003365 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003366 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003367 }
3368
Ian Rogers7b078e82014-09-10 14:44:24 -07003369 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003370 uint64_t t1 = NanoTime();
3371
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003372 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003373 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003374 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003375
3376 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003377 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003378 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003379 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003380 } else if (Runtime::Current()->IsTransactionAborted()) {
3381 // The exception thrown when the transaction aborted has been caught and cleared
3382 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01003383 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
3384 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003385 Runtime::Current()->ThrowInternalErrorForAbortedTransaction(self);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003386 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003387 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003388 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003389 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3390 RuntimeStats* thread_stats = self->GetStats();
3391 ++global_stats->class_init_count;
3392 ++thread_stats->class_init_count;
3393 global_stats->class_init_time_ns += (t1 - t0);
3394 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003395 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003396 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003397 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003398 std::string temp;
3399 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003400 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003401 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003402 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003403 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003404 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003405 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003406 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003407}
3408
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003409bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003410 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003411 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003412 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003413 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003414 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08003415 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003416
3417 // When we wake up, repeat the test for init-in-progress. If
3418 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07003419 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003420 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003421 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003422 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003423 return false;
3424 }
3425 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003426 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003427 continue;
3428 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003429 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
3430 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003431 // Compile time initialization failed.
3432 return false;
3433 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003434 if (klass->IsErroneous()) {
3435 // The caller wants an exception, but it was thrown in a
3436 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003437 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003438 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003439 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003440 return false;
3441 }
3442 if (klass->IsInitialized()) {
3443 return true;
3444 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003445 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003446 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003447 }
Ian Rogers07140832014-09-30 15:43:59 -07003448 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003449}
3450
Ian Rogersb5fb2072014-12-02 17:22:02 -08003451static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
3452 Handle<mirror::ArtMethod> method1,
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003453 Handle<mirror::ArtMethod> method2,
3454 std::string* error_msg)
Ian Rogersb5fb2072014-12-02 17:22:02 -08003455 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3456 {
3457 StackHandleScope<1> hs(self);
3458 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
Vladimir Marko862f43c2015-02-10 18:22:57 +00003459 mirror::Class* other_return_type = method2->GetReturnType();
3460 // NOTE: return_type.Get() must be sequenced after method2->GetReturnType().
3461 if (UNLIKELY(other_return_type != return_type.Get())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003462 *error_msg = StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
3463 PrettyClassAndClassLoader(return_type.Get()).c_str(),
3464 return_type.Get(),
3465 PrettyClassAndClassLoader(other_return_type).c_str(),
3466 other_return_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003467 return false;
3468 }
3469 }
3470 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
3471 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
3472 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003473 if (types2 != nullptr && types2->Size() != 0) {
3474 *error_msg = StringPrintf("Type list mismatch with %s",
3475 PrettyMethod(method2.Get(), true).c_str());
3476 return false;
3477 }
3478 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003479 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003480 if (types1->Size() != 0) {
3481 *error_msg = StringPrintf("Type list mismatch with %s",
3482 PrettyMethod(method2.Get(), true).c_str());
3483 return false;
3484 }
3485 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003486 }
3487 uint32_t num_types = types1->Size();
3488 if (UNLIKELY(num_types != types2->Size())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003489 *error_msg = StringPrintf("Type list mismatch with %s",
3490 PrettyMethod(method2.Get(), true).c_str());
Ian Rogersb5fb2072014-12-02 17:22:02 -08003491 return false;
3492 }
3493 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00003494 StackHandleScope<1> hs(self);
3495 Handle<mirror::Class> param_type(hs.NewHandle(
3496 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true)));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003497 mirror::Class* other_param_type =
3498 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
Vladimir Marko862f43c2015-02-10 18:22:57 +00003499 // NOTE: param_type.Get() must be sequenced after method2->GetClassFromTypeIndex(...).
3500 if (UNLIKELY(param_type.Get() != other_param_type)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003501 *error_msg = StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
3502 i,
3503 PrettyClassAndClassLoader(param_type.Get()).c_str(),
3504 param_type.Get(),
3505 PrettyClassAndClassLoader(other_param_type).c_str(),
3506 other_param_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003507 return false;
3508 }
3509 }
3510 return true;
3511}
3512
3513
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003514bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003515 if (klass->IsInterface()) {
3516 return true;
3517 }
Ian Rogers151f2212014-05-06 11:27:27 -07003518 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07003519 Thread* self = Thread::Current();
3520 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003521 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
3522 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003523 if (klass->HasSuperClass() &&
3524 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003525 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003526 h_m.Assign(klass->GetVTableEntry(i));
3527 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003528 if (h_m.Get() != super_h_m.Get()) {
3529 std::string error_msg;
3530 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3531 ThrowLinkageError(klass.Get(),
3532 "Class %s method %s resolves differently in superclass %s: %s",
3533 PrettyDescriptor(klass.Get()).c_str(),
3534 PrettyMethod(h_m.Get()).c_str(),
3535 PrettyDescriptor(klass->GetSuperClass()).c_str(),
3536 error_msg.c_str());
3537 return false;
3538 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003539 }
3540 }
3541 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003542 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07003543 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
3544 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
3545 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003546 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
3547 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003548 if (h_m.Get() != super_h_m.Get()) {
3549 std::string error_msg;
3550 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3551 ThrowLinkageError(klass.Get(),
3552 "Class %s method %s resolves differently in interface %s: %s",
3553 PrettyDescriptor(klass.Get()).c_str(),
3554 PrettyMethod(h_m.Get()).c_str(),
3555 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str(),
3556 error_msg.c_str());
3557 return false;
3558 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003559 }
3560 }
3561 }
3562 }
3563 return true;
3564}
3565
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003566bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
3567 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003568 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003569 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003570 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003571 return true;
3572 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003573 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003574 if (!success) {
3575 if (can_init_fields && can_init_parents) {
3576 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
3577 }
3578 } else {
3579 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08003580 }
3581 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003582}
3583
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003584void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
3585 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
3586 if (fields != nullptr) {
3587 for (int index = 0; index < fields->GetLength(); index ++) {
3588 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
3589 fields->Get(index)->SetDeclaringClass(new_class);
3590 }
3591 }
3592 }
3593
3594 fields = new_class->GetSFields();
3595 if (fields != nullptr) {
3596 for (int index = 0; index < fields->GetLength(); index ++) {
3597 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
3598 fields->Get(index)->SetDeclaringClass(new_class);
3599 }
3600 }
3601 }
3602
3603 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
3604 if (methods != nullptr) {
3605 for (int index = 0; index < methods->GetLength(); index ++) {
3606 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3607 methods->Get(index)->SetDeclaringClass(new_class);
3608 }
3609 }
3610 }
3611
3612 methods = new_class->GetVirtualMethods();
3613 if (methods != nullptr) {
3614 for (int index = 0; index < methods->GetLength(); index ++) {
3615 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3616 methods->Get(index)->SetDeclaringClass(new_class);
3617 }
3618 }
3619 }
3620}
3621
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003622bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
3623 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003624 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003625 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003626
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003627 if (!LinkSuperClass(klass)) {
3628 return false;
3629 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003630 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
3631 self, Runtime::Current()->GetImtUnimplementedMethod());
3632 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003633 return false;
3634 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003635 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003636 return false;
3637 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003638 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07003639 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003640 return false;
3641 }
3642 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003643 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003644
3645 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
3646 // We don't need to retire this class as it has no embedded tables or it was created the
3647 // correct size during class linker initialization.
3648 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
3649
3650 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003651 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003652 }
3653
3654 // This will notify waiters on klass that saw the not yet resolved
3655 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003656 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003657 *new_class = klass.Get();
3658 } else {
3659 CHECK(!klass->IsResolved());
3660 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003661 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003662 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003663 CHECK(self->IsExceptionPending()); // Expect an OOME.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003664 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003665 return false;
3666 }
3667
3668 CHECK_EQ((*new_class)->GetClassSize(), class_size);
3669 StackHandleScope<1> hs(self);
3670 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
3671 ObjectLock<mirror::Class> lock(self, new_class_h);
3672
3673 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
3674
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003675 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
3676 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003677 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003678
3679 // This will notify waiters on temp class that saw the not yet resolved class in the
3680 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003681 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003682
3683 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
3684 // This will notify waiters on new_class that saw the not yet resolved
3685 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003686 mirror::Class::SetStatus(new_class_h, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003687 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003688 return true;
3689}
3690
Andreas Gampefd9eb392014-11-06 16:52:58 -08003691static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
3692 size_t* virtual_methods,
3693 size_t* direct_methods,
3694 size_t* static_fields,
3695 size_t* instance_fields) {
3696 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
3697
3698 while (dex_data.HasNextStaticField()) {
3699 dex_data.Next();
3700 (*static_fields)++;
3701 }
3702 while (dex_data.HasNextInstanceField()) {
3703 dex_data.Next();
3704 (*instance_fields)++;
3705 }
3706 while (dex_data.HasNextDirectMethod()) {
3707 (*direct_methods)++;
3708 dex_data.Next();
3709 }
3710 while (dex_data.HasNextVirtualMethod()) {
3711 (*virtual_methods)++;
3712 dex_data.Next();
3713 }
3714 DCHECK(!dex_data.HasNext());
3715}
3716
3717static void DumpClass(std::ostream& os,
3718 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
3719 const char* suffix) {
3720 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
3721 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
3722 os << " Static fields:\n";
3723 while (dex_data.HasNextStaticField()) {
3724 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3725 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3726 dex_data.Next();
3727 }
3728 os << " Instance fields:\n";
3729 while (dex_data.HasNextInstanceField()) {
3730 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3731 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3732 dex_data.Next();
3733 }
3734 os << " Direct methods:\n";
3735 while (dex_data.HasNextDirectMethod()) {
3736 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3737 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3738 dex_data.Next();
3739 }
3740 os << " Virtual methods:\n";
3741 while (dex_data.HasNextVirtualMethod()) {
3742 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3743 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3744 dex_data.Next();
3745 }
3746}
3747
3748static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3749 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
3750 std::ostringstream os;
3751 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
3752 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
3753 return os.str();
3754}
3755
3756
3757// Very simple structural check on whether the classes match. Only compares the number of
3758// methods and fields.
3759static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3760 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
3761 std::string* error_msg) {
3762 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
3763 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
3764
3765 // Counters for current dex file.
3766 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
3767 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
3768 &dex_instance_fields1);
3769 // Counters for compile-time dex file.
3770 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
3771 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
3772 &dex_instance_fields2);
3773
3774 if (dex_virtual_methods1 != dex_virtual_methods2) {
3775 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3776 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
3777 dex_virtual_methods2, class_dump.c_str());
3778 return false;
3779 }
3780 if (dex_direct_methods1 != dex_direct_methods2) {
3781 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3782 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
3783 dex_direct_methods2, class_dump.c_str());
3784 return false;
3785 }
3786 if (dex_static_fields1 != dex_static_fields2) {
3787 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3788 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
3789 dex_static_fields2, class_dump.c_str());
3790 return false;
3791 }
3792 if (dex_instance_fields1 != dex_instance_fields2) {
3793 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3794 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
3795 dex_instance_fields2, class_dump.c_str());
3796 return false;
3797 }
3798
3799 return true;
3800}
3801
3802// Checks whether a the super-class changed from what we had at compile-time. This would
3803// invalidate quickening.
3804static bool CheckSuperClassChange(Handle<mirror::Class> klass,
3805 const DexFile& dex_file,
3806 const DexFile::ClassDef& class_def,
3807 mirror::Class* super_class)
3808 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3809 // Check for unexpected changes in the superclass.
3810 // Quick check 1) is the super_class class-loader the boot class loader? This always has
3811 // precedence.
3812 if (super_class->GetClassLoader() != nullptr &&
3813 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
3814 // which is implied by different dex cache.
3815 klass->GetDexCache() != super_class->GetDexCache()) {
3816 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
3817 // definition for the super-class, and (b) the files are in separate oat files. The oat files
3818 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
Richard Uhler07b3c232015-03-31 15:57:54 -07003819 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
3820 const OatFile* class_oat_file = nullptr;
3821 if (class_oat_dex_file != nullptr) {
3822 class_oat_file = class_oat_dex_file->GetOatFile();
3823 }
3824
Andreas Gampefd9eb392014-11-06 16:52:58 -08003825 if (class_oat_file != nullptr) {
Richard Uhler07b3c232015-03-31 15:57:54 -07003826 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
3827 const OatFile* loaded_super_oat_file = nullptr;
3828 if (loaded_super_oat_dex_file != nullptr) {
3829 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
3830 }
3831
Andreas Gampefd9eb392014-11-06 16:52:58 -08003832 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
3833 // Now check (a).
3834 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
3835 if (super_class_def != nullptr) {
3836 // Uh-oh, we found something. Do our check.
3837 std::string error_msg;
3838 if (!SimpleStructuralCheck(dex_file, *super_class_def,
3839 super_class->GetDexFile(), *super_class->GetClassDef(),
3840 &error_msg)) {
3841 // Print a warning to the log. This exception might be caught, e.g., as common in test
3842 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
3843 // only save the type of the exception.
3844 LOG(WARNING) << "Incompatible structural change detected: " <<
3845 StringPrintf(
3846 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3847 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3848 class_oat_file->GetLocation().c_str(),
3849 loaded_super_oat_file->GetLocation().c_str(),
3850 error_msg.c_str());
3851 ThrowIncompatibleClassChangeError(klass.Get(),
3852 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3853 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3854 class_oat_file->GetLocation().c_str(),
3855 loaded_super_oat_file->GetLocation().c_str(),
3856 error_msg.c_str());
3857 return false;
3858 }
3859 }
3860 }
3861 }
3862 }
3863 return true;
3864}
3865
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003866bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003867 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003868 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3869 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003870 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003871 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003872 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003873 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003874 return false;
3875 }
Ian Rogersbe125a92012-01-11 15:19:49 -08003876 // Verify
3877 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003878 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003879 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003880 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08003881 return false;
3882 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003883 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003884 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08003885
3886 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
3887 DCHECK(Thread::Current()->IsExceptionPending());
3888 return false;
3889 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003890 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003891 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003892 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003893 for (size_t i = 0; i < interfaces->Size(); i++) {
3894 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003895 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003896 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003897 DCHECK(Thread::Current()->IsExceptionPending());
3898 return false;
3899 }
3900 // Verify
3901 if (!klass->CanAccess(interface)) {
3902 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003903 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003904 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003905 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003906 return false;
3907 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003908 }
3909 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003910 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003911 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003912 return true;
3913}
3914
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003915bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003916 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003917 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003918 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003919 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003920 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003921 return false;
3922 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003923 return true;
3924 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003925 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003926 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
3927 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003928 return false;
3929 }
3930 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003931 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003932 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003933 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003934 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003935 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003936 return false;
3937 }
3938 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003939 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003940 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003941 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003942 return false;
3943 }
Elliott Hughes20cde902011-10-04 17:37:27 -07003944
Brian Carlstromf3632832014-05-20 15:36:53 -07003945 // Inherit kAccClassIsFinalizable from the superclass in case this
3946 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07003947 if (super->IsFinalizable()) {
3948 klass->SetFinalizable();
3949 }
3950
Elliott Hughes2da50362011-10-10 16:57:08 -07003951 // Inherit reference flags (if any) from the superclass.
3952 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
3953 if (reference_flags != 0) {
3954 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
3955 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07003956 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07003957 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003958 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003959 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003960 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07003961 return false;
3962 }
Elliott Hughes2da50362011-10-10 16:57:08 -07003963
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003964 if (kIsDebugBuild) {
3965 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003966 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003967 CHECK(super->IsResolved());
3968 super = super->GetSuperClass();
3969 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003970 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003971 return true;
3972}
3973
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003974// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003975bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003976 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
3977 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003978 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003979 if (klass->IsInterface()) {
3980 // No vtable.
3981 size_t count = klass->NumVirtualMethods();
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08003982 if (!IsUint<16>(count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003983 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003984 return false;
3985 }
Carl Shapiro565f5072011-07-10 13:39:43 -07003986 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003987 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003988 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003989 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
3990 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003991 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003992 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003993}
3994
Ian Rogers03b6eaf2014-10-28 09:34:57 -07003995// Comparator for name and signature of a method, used in finding overriding methods. Implementation
3996// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
3997// caches in the implementation below.
3998class MethodNameAndSignatureComparator FINAL : public ValueObject {
3999 public:
4000 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4001 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4002 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4003 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004004 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4005 }
4006
4007 const char* GetName() {
4008 if (name_ == nullptr) {
4009 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4010 }
4011 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004012 }
4013
4014 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4015 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4016 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4017 const DexFile* other_dex_file = other->GetDexFile();
4018 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4019 if (dex_file_ == other_dex_file) {
4020 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4021 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004022 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004023 uint32_t other_name_len;
4024 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4025 &other_name_len);
4026 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4027 return false;
4028 }
4029 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4030 }
4031
4032 private:
4033 // Dex file for the method to compare against.
4034 const DexFile* const dex_file_;
4035 // MethodId for the method to compare against.
4036 const DexFile::MethodId* const mid_;
4037 // Lazily computed name from the dex file's strings.
4038 const char* name_;
4039 // Lazily computed name length.
4040 uint32_t name_len_;
4041};
4042
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004043class LinkVirtualHashTable {
4044 public:
4045 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4046 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4047 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4048 }
4049 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4050 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4051 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004052 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004053 uint32_t index = hash % hash_size_;
4054 // Linear probe until we have an empty slot.
4055 while (hash_table_[index] != invalid_index_) {
4056 if (++index == hash_size_) {
4057 index = 0;
4058 }
4059 }
4060 hash_table_[index] = virtual_method_index;
4061 }
4062 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4063 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4064 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004065 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004066 size_t index = hash % hash_size_;
4067 while (true) {
4068 const uint32_t value = hash_table_[index];
4069 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4070 // the block and can safely assume not found.
4071 if (value == invalid_index_) {
4072 break;
4073 }
4074 if (value != removed_index_) { // This signifies not already overriden.
4075 mirror::ArtMethod* virtual_method =
4076 klass_->GetVirtualMethodDuringLinking(value);
4077 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4078 hash_table_[index] = removed_index_;
4079 return value;
4080 }
4081 }
4082 if (++index == hash_size_) {
4083 index = 0;
4084 }
4085 }
4086 return GetNotFoundIndex();
4087 }
4088 static uint32_t GetNotFoundIndex() {
4089 return invalid_index_;
4090 }
4091
4092 private:
4093 static const uint32_t invalid_index_;
4094 static const uint32_t removed_index_;
4095
4096 Handle<mirror::Class> klass_;
4097 const size_t hash_size_;
4098 uint32_t* const hash_table_;
4099};
4100
4101const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4102const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4103
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004104bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004105 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004106 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004107 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4108 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004109 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004110 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004111 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004112 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4113 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4114 if (UNLIKELY(vtable.Get() == nullptr)) {
4115 CHECK(self->IsExceptionPending()); // OOME.
4116 return false;
4117 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004118 for (size_t i = 0; i < super_vtable_length; i++) {
4119 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004120 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004121 if (num_virtual_methods == 0) {
4122 klass->SetVTable(vtable.Get());
4123 return true;
4124 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004125 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004126 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4127 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4128 if (num_virtual_methods == 0) {
4129 klass->SetVTable(super_vtable);
4130 return true;
4131 }
4132 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004133 if (UNLIKELY(vtable.Get() == nullptr)) {
4134 CHECK(self->IsExceptionPending()); // OOME.
4135 return false;
4136 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004137 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004138 // How the algorithm works:
4139 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4140 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4141 // method which has not been matched to a vtable method, and j if the virtual method at the
4142 // index overrode the super virtual method at index j.
4143 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4144 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4145 // the need for the initial vtable which we later shrink back down).
4146 // 3. Add non overridden methods to the end of the vtable.
4147 static constexpr size_t kMaxStackHash = 250;
4148 const size_t hash_table_size = num_virtual_methods * 3;
4149 uint32_t* hash_table_ptr;
4150 std::unique_ptr<uint32_t[]> hash_heap_storage;
4151 if (hash_table_size <= kMaxStackHash) {
4152 hash_table_ptr = reinterpret_cast<uint32_t*>(
4153 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4154 } else {
4155 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4156 hash_table_ptr = hash_heap_storage.get();
4157 }
4158 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4159 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004160 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004161 hash_table.Add(i);
4162 }
4163 // Loop through each super vtable method and see if they are overriden by a method we added to
4164 // the hash table.
4165 for (size_t j = 0; j < super_vtable_length; ++j) {
4166 // Search the hash table to see if we are overidden by any method.
4167 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4168 MethodNameAndSignatureComparator super_method_name_comparator(
4169 super_method->GetInterfaceMethodIfProxy());
4170 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4171 if (hash_index != hash_table.GetNotFoundIndex()) {
4172 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4173 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4174 super_method->GetAccessFlags())) {
4175 if (super_method->IsFinal()) {
4176 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4177 PrettyMethod(virtual_method).c_str(),
4178 super_method->GetDeclaringClassDescriptor());
4179 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004180 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004181 vtable->SetWithoutChecks<false>(j, virtual_method);
4182 virtual_method->SetMethodIndex(j);
4183 } else {
4184 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004185 << " would have incorrectly overridden the package-private method in "
4186 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004187 }
4188 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004189 }
4190 // Add the non overridden methods at the end.
4191 size_t actual_count = super_vtable_length;
4192 for (size_t i = 0; i < num_virtual_methods; ++i) {
4193 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4194 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4195 if (method_idx < super_vtable_length &&
4196 local_method == vtable->GetWithoutChecks(method_idx)) {
4197 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004198 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004199 vtable->SetWithoutChecks<false>(actual_count, local_method);
4200 local_method->SetMethodIndex(actual_count);
4201 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004202 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004203 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004204 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004205 return false;
4206 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004207 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004208 CHECK_LE(actual_count, max_count);
4209 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004210 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004211 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004212 CHECK(self->IsExceptionPending()); // OOME.
4213 return false;
4214 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004215 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004216 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004217 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004218 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004219 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004220 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4221 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004222 return false;
4223 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004224 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4225 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004226 CHECK(self->IsExceptionPending()); // OOME.
4227 return false;
4228 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004229 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004230 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004231 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004232 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004233 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004234 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004235 }
4236 return true;
4237}
4238
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004239bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4240 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4241 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004242 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004243 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004244 const bool has_superclass = klass->HasSuperClass();
4245 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4246 const bool have_interfaces = interfaces.Get() != nullptr;
4247 const size_t num_interfaces =
4248 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4249 if (num_interfaces == 0) {
4250 if (super_ifcount == 0) {
4251 // Class implements no interfaces.
4252 DCHECK_EQ(klass->GetIfTableCount(), 0);
4253 DCHECK(klass->GetIfTable() == nullptr);
4254 return true;
4255 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004256 // Class implements same interfaces as parent, are any of these not marker interfaces?
4257 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004258 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004259 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004260 if (super_iftable->GetMethodArrayCount(i) > 0) {
4261 has_non_marker_interface = true;
4262 break;
4263 }
4264 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004265 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004266 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004267 klass->SetIfTable(super_iftable);
4268 return true;
4269 }
4270 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004271 size_t ifcount = super_ifcount + num_interfaces;
4272 for (size_t i = 0; i < num_interfaces; i++) {
4273 mirror::Class* interface = have_interfaces ?
4274 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4275 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004276 if (UNLIKELY(!interface->IsInterface())) {
4277 std::string temp;
4278 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4279 PrettyDescriptor(klass.Get()).c_str(),
4280 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4281 return false;
4282 }
4283 ifcount += interface->GetIfTableCount();
4284 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004285 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004286 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004287 CHECK(self->IsExceptionPending()); // OOME.
4288 return false;
4289 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004290 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004291 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004292 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004293 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004294 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004295 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004296 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004297 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004298 // Flatten the interface inheritance hierarchy.
4299 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004300 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004301 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4302 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004303 // Check if interface is already in iftable
4304 bool duplicate = false;
4305 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004306 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004307 if (existing_interface == interface) {
4308 duplicate = true;
4309 break;
4310 }
4311 }
4312 if (!duplicate) {
4313 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004314 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004315 // Add this interface's non-duplicate super-interfaces.
4316 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004317 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004318 bool super_duplicate = false;
4319 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004320 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004321 if (existing_interface == super_interface) {
4322 super_duplicate = true;
4323 break;
4324 }
4325 }
4326 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004327 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004328 }
4329 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004330 }
4331 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004332 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004333 // Shrink iftable in case duplicates were found
4334 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004335 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004336 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004337 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004338 CHECK(self->IsExceptionPending()); // OOME.
4339 return false;
4340 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004341 ifcount = idx;
4342 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004343 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004344 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004345 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004346 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004347 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004348 return true;
4349 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004350 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004351 size_t max_miranda_methods = 0; // The max size of miranda_list.
4352 for (size_t i = 0; i < ifcount; ++i) {
4353 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4354 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004355 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004356 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004357 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4358 hs.NewHandle(klass->GetVTableDuringLinking()));
4359 // Copy the IMT from the super class if possible.
4360 bool extend_super_iftable = false;
4361 if (has_superclass) {
4362 mirror::Class* super_class = klass->GetSuperClass();
4363 extend_super_iftable = true;
4364 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4365 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4366 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
4367 }
4368 } else {
4369 // No imt in the super class, need to reconstruct from the iftable.
4370 mirror::IfTable* if_table = super_class->GetIfTable();
4371 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4372 const size_t length = super_class->GetIfTableCount();
4373 for (size_t i = 0; i < length; ++i) {
4374 mirror::Class* interface = iftable->GetInterface(i);
4375 const size_t num_virtuals = interface->NumVirtualMethods();
4376 const size_t method_array_count = if_table->GetMethodArrayCount(i);
4377 DCHECK_EQ(num_virtuals, method_array_count);
4378 if (method_array_count == 0) {
4379 continue;
4380 }
4381 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
4382 for (size_t j = 0; j < num_virtuals; ++j) {
4383 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
4384 if (method->IsMiranda()) {
4385 continue;
4386 }
4387 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
4388 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4389 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4390 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4391 out_imt->SetReference(imt_index, method);
4392 } else if (imt_ref != conflict_method) {
4393 out_imt->SetReference(imt_index, conflict_method);
4394 }
4395 }
4396 }
4397 }
4398 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004399 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004400 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004401 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004402 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004403 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004404 const bool is_super = i < super_ifcount;
4405 const bool super_interface = is_super && extend_super_iftable;
4406 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
4407 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
4408 if (super_interface) {
4409 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
4410 DCHECK(if_table != nullptr);
4411 DCHECK(if_table->GetMethodArray(i) != nullptr);
4412 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004413 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004414 AsObjectArray<mirror::ArtMethod>());
4415 // We are overwriting a super class interface, try to only virtual methods instead of the
4416 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004417 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004418 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004419 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004420 // A new interface, we need the whole vtable incase a new interface method is implemented
4421 // in the whole superclass.
4422 input_array = vtable;
4423 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004424 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004425 CHECK(self->IsExceptionPending()); // OOME.
4426 return false;
4427 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004428 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004429 if (input_array.Get() == nullptr) {
4430 // If the added virtual methods is empty, do nothing.
4431 DCHECK(super_interface);
4432 continue;
4433 }
Ian Rogers62d6c772013-02-27 08:32:07 -08004434 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004435 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004436 MethodNameAndSignatureComparator interface_name_comparator(
4437 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07004438 int32_t k;
4439 // For each method listed in the interface's method list, find the
4440 // matching method in our class's method list. We want to favor the
4441 // subclass over the superclass, which just requires walking
4442 // back from the end of the vtable. (This only matters if the
4443 // superclass defines a private method and this class redefines
4444 // it -- otherwise it would use the same vtable slot. In .dex files
4445 // those don't end up in the virtual method table, so it shouldn't
4446 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004447 for (k = input_array->GetLength() - 1; k >= 0; --k) {
4448 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004449 mirror::ArtMethod* vtable_method_for_name_comparison =
4450 vtable_method->GetInterfaceMethodIfProxy();
4451 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004452 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004453 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004454 ThrowIllegalAccessError(
4455 klass.Get(),
4456 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004457 PrettyMethod(vtable_method).c_str(),
4458 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004459 return false;
4460 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004461 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004462 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004463 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4464 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4465 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4466 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4467 out_imt->SetReference(imt_index, vtable_method);
4468 } else if (imt_ref != conflict_method) {
4469 // If we are not a conflict and we have the same signature and name as the imt entry,
4470 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004471 MethodNameAndSignatureComparator imt_ref_name_comparator(
4472 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004473 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004474 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004475 out_imt->SetReference(imt_index, vtable_method);
4476 } else {
4477 out_imt->SetReference(imt_index, conflict_method);
4478 }
Jeff Hao88474b42013-10-23 16:24:40 -07004479 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004480 break;
4481 }
4482 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004483 if (k < 0 && !super_interface) {
4484 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004485 for (size_t l = 0; l < miranda_list_size; ++l) {
4486 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004487 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004488 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07004489 break;
4490 }
4491 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004492 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004493 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004494 miranda_method = interface_method->Clone(self)->AsArtMethod();
4495 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004496 CHECK(self->IsExceptionPending()); // OOME.
4497 return false;
4498 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004499 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004500 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004501 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004502 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004503 }
4504 }
4505 }
4506 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004507 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004508 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004509 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004510 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4511 if (old_method_count == 0) {
4512 virtuals = AllocArtMethodArray(self, new_method_count);
4513 } else {
4514 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4515 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004516 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004517 CHECK(self->IsExceptionPending()); // OOME.
4518 return false;
4519 }
4520 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004521
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004522 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004523 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004524 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004525 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004526 CHECK(self->IsExceptionPending()); // OOME.
4527 return false;
4528 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004529 for (size_t i = 0; i < miranda_list_size; ++i) {
4530 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004531 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004532 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4533 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4534 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004535 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004536 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004537 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004538 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004539 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004540
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004541 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004542 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
4543 for (int i = 0; i < check_vtable->GetLength(); ++i) {
4544 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004545 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004546 }
4547
Ian Rogers7b078e82014-09-10 14:44:24 -07004548 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004549 return true;
4550}
4551
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004552bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004553 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004554 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004555}
4556
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004557bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004558 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004559 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004560}
4561
Brian Carlstromdbc05252011-09-09 01:59:59 -07004562struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004563 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4564 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004565 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004566 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004567 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07004568 // 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 -07004569 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4570 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004571 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00004572 if (type1 == Primitive::kPrimNot) {
4573 // Reference always goes first.
4574 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08004575 }
Vladimir Markod5777482014-11-12 17:02:02 +00004576 if (type2 == Primitive::kPrimNot) {
4577 // Reference always goes first.
4578 return false;
4579 }
4580 size_t size1 = Primitive::ComponentSize(type1);
4581 size_t size2 = Primitive::ComponentSize(type2);
4582 if (size1 != size2) {
4583 // Larger primitive types go first.
4584 return size1 > size2;
4585 }
4586 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
4587 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004588 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004589 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
4590 // by name and for equal names by type id index.
4591 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
4592 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07004593 }
4594};
4595
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004596bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07004597 size_t* class_size) {
4598 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004599 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004600 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004601
Brian Carlstromea46f952013-07-30 01:26:50 -07004602 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004603 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004604
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004605 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07004606 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004607 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00004608 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004609 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004610 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004611 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004612 CHECK(super_class->IsResolved())
4613 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004614 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004615 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004616 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004617
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004618 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004619
Brian Carlstromdbc05252011-09-09 01:59:59 -07004620 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07004621 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07004622 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07004623 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07004624 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07004625 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004626 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004627 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004628 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004629 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004630 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4631 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004632
Fred Shih381e4ca2014-08-25 17:24:27 -07004633 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07004634 size_t current_field = 0;
4635 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07004636 FieldGaps gaps;
4637
Brian Carlstromdbc05252011-09-09 01:59:59 -07004638 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004639 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004640 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004641 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004642 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004643 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004644 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004645 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
4646 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07004647 MemberOffset old_offset = field_offset;
4648 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
4649 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
4650 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004651 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07004652 grouped_and_sorted_fields.pop_front();
4653 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004654 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00004655 field_offset = MemberOffset(field_offset.Uint32Value() +
4656 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004657 }
Fred Shih381e4ca2014-08-25 17:24:27 -07004658 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
4659 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00004660 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4661 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4662 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4663 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07004664 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
4665 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07004666 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004667
Elliott Hughesadb460d2011-10-05 17:02:34 -07004668 // 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 -07004669 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07004670 // We know there are no non-reference fields in the Reference classes, and we know
4671 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07004672 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004673 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07004674 --num_reference_fields;
4675 }
4676
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004677 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004678 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004679 if (is_static) {
4680 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004681 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004682 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004683 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004684 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08004685 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
Jeff Haoc7d11882015-02-03 15:08:39 -08004686 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
4687 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartier2d721012014-11-10 11:08:06 -08004688 } else {
4689 std::string temp;
4690 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
4691 size_t previous_size = klass->GetObjectSize();
4692 if (previous_size != 0) {
4693 // Make sure that we didn't originally have an incorrect size.
4694 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
4695 }
4696 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004697 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004698 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004699 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004700
4701 if (kIsDebugBuild) {
4702 // Make sure that the fields array is ordered by name but all reference
4703 // offsets are at the beginning as far as alignment allows.
4704 MemberOffset start_ref_offset = is_static
4705 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
4706 : klass->GetFirstReferenceInstanceFieldOffset();
4707 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
4708 num_reference_fields *
4709 sizeof(mirror::HeapReference<mirror::Object>));
4710 MemberOffset current_ref_offset = start_ref_offset;
4711 for (size_t i = 0; i < num_fields; i++) {
4712 mirror::ArtField* field = fields->Get(i);
4713 if ((false)) { // enable to debug field layout
4714 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
4715 << " class=" << PrettyClass(klass.Get())
4716 << " field=" << PrettyField(field)
4717 << " offset="
4718 << field->GetField32(mirror::ArtField::OffsetOffset());
4719 }
4720 if (i != 0) {
4721 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004722 // NOTE: The field names can be the same. This is not possible in the Java language
4723 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
4724 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00004725 }
4726 Primitive::Type type = field->GetTypeAsPrimitiveType();
4727 bool is_primitive = type != Primitive::kPrimNot;
4728 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
4729 strcmp("referent", field->GetName()) == 0) {
4730 is_primitive = true; // We lied above, so we have to expect a lie here.
4731 }
4732 MemberOffset offset = field->GetOffsetDuringLinking();
4733 if (is_primitive) {
4734 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
4735 // Shuffled before references.
4736 size_t type_size = Primitive::ComponentSize(type);
4737 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
4738 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
4739 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
4740 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
4741 }
4742 } else {
4743 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
4744 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
4745 sizeof(mirror::HeapReference<mirror::Object>));
4746 }
4747 }
4748 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
4749 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004750 return true;
4751}
4752
Vladimir Marko76649e82014-11-10 18:32:59 +00004753// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004754void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004755 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004756 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004757 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004758 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004759 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004760 // Compute reference offsets unless our superclass overflowed.
4761 if (reference_offsets != mirror::Class::kClassWalkSuper) {
4762 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00004763 if (num_reference_fields != 0u) {
4764 // All of the fields that contain object references are guaranteed be grouped in memory
4765 // starting at an appropriately aligned address after super class object data.
4766 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
4767 sizeof(mirror::HeapReference<mirror::Object>));
4768 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004769 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00004770 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004771 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004772 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00004773 reference_offsets |= (0xffffffffu << start_bit) &
4774 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004775 }
4776 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07004777 }
4778 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07004779 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004780}
4781
Mathieu Chartier590fee92013-09-13 13:46:47 -07004782mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004783 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004784 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004785 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004786 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004787 return resolved;
4788 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07004789 uint32_t utf16_length;
4790 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004791 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004792 dex_cache->SetResolvedString(string_idx, string);
4793 return string;
4794}
4795
Mathieu Chartier590fee92013-09-13 13:46:47 -07004796mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08004797 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004798 StackHandleScope<2> hs(Thread::Current());
4799 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
4800 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07004801 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
4802}
4803
4804mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004805 Handle<mirror::DexCache> dex_cache,
4806 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004807 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004808 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004809 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08004810 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07004811 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08004812 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004813 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05004814 // TODO: we used to throw here if resolved's class loader was not the
4815 // boot class loader. This was to permit different classes with the
4816 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004817 dex_cache->SetResolvedType(type_idx, resolved);
4818 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004819 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08004820 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08004821 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004822 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004823 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004824 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004825 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08004826 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08004827 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004828 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08004829 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004830 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004831 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004832 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07004833 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004834 return resolved;
4835}
4836
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004837mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004838 Handle<mirror::DexCache> dex_cache,
4839 Handle<mirror::ClassLoader> class_loader,
4840 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07004841 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004842 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07004843 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07004844 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004845 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004846 return resolved;
4847 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004848 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004849 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004850 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004851 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07004852 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004853 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004854 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004855 // Scan using method_idx, this saves string compares but will only hit for matching dex
4856 // caches/files.
4857 switch (type) {
4858 case kDirect: // Fall-through.
4859 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004860 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004861 break;
4862 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004863 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004864 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004865 break;
4866 case kSuper: // Fall-through.
4867 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004868 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004869 break;
4870 default:
4871 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07004872 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004873 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004874 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004875 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004876 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07004877 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07004878 switch (type) {
4879 case kDirect: // Fall-through.
4880 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08004881 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004882 break;
4883 case kInterface:
4884 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004885 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004886 break;
4887 case kSuper: // Fall-through.
4888 case kVirtual:
4889 resolved = klass->FindVirtualMethod(name, signature);
4890 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004891 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004892 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004893 // If we found a method, check for incompatible class changes.
4894 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004895 // Be a good citizen and update the dex cache to speed subsequent calls.
4896 dex_cache->SetResolvedMethod(method_idx, resolved);
4897 return resolved;
4898 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004899 // If we had a method, it's an incompatible-class-change error.
4900 if (resolved != nullptr) {
4901 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
4902 } else {
4903 // We failed to find the method which means either an access error, an incompatible class
4904 // change, or no such method. First try to find the method among direct and virtual methods.
4905 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
4906 const Signature signature = dex_file.GetMethodSignature(method_id);
4907 switch (type) {
4908 case kDirect:
4909 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07004910 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004911 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
4912 // have had a resolved method before, which triggers the "true" branch above.
4913 break;
4914 case kInterface:
4915 case kVirtual:
4916 case kSuper:
4917 resolved = klass->FindDirectMethod(name, signature);
4918 break;
4919 }
4920
4921 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08004922 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004923 if (resolved != nullptr && referrer.Get() != nullptr) {
4924 mirror::Class* methods_class = resolved->GetDeclaringClass();
4925 mirror::Class* referring_class = referrer->GetDeclaringClass();
4926 if (!referring_class->CanAccess(methods_class)) {
4927 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
4928 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004929 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004930 } else if (!referring_class->CanAccessMember(methods_class,
4931 resolved->GetAccessFlags())) {
4932 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004933 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004934 }
4935 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004936 if (!exception_generated) {
4937 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
4938 // interface methods and throw if we find the method there. If we find nothing, throw a
4939 // NoSuchMethodError.
4940 switch (type) {
4941 case kDirect:
4942 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004943 if (resolved != nullptr) {
4944 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4945 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004946 resolved = klass->FindInterfaceMethod(name, signature);
4947 if (resolved != nullptr) {
4948 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4949 } else {
4950 ThrowNoSuchMethodError(type, klass, name, signature);
4951 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004952 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004953 break;
4954 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004955 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004956 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
4957 } else {
4958 resolved = klass->FindVirtualMethod(name, signature);
4959 if (resolved != nullptr) {
4960 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4961 } else {
4962 ThrowNoSuchMethodError(type, klass, name, signature);
4963 }
4964 }
4965 break;
4966 case kSuper:
4967 if (resolved != nullptr) {
4968 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004969 } else {
4970 ThrowNoSuchMethodError(type, klass, name, signature);
4971 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004972 break;
4973 case kVirtual:
4974 if (resolved != nullptr) {
4975 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
4976 } else {
4977 resolved = klass->FindInterfaceMethod(name, signature);
4978 if (resolved != nullptr) {
4979 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4980 } else {
4981 ThrowNoSuchMethodError(type, klass, name, signature);
4982 }
4983 }
4984 break;
4985 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004986 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004987 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004988 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004989 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07004990 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004991}
4992
Mathieu Chartier590fee92013-09-13 13:46:47 -07004993mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004994 Handle<mirror::DexCache> dex_cache,
4995 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07004996 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004997 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07004998 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07004999 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005000 return resolved;
5001 }
5002 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005003 Thread* const self = Thread::Current();
5004 StackHandleScope<1> hs(self);
5005 Handle<mirror::Class> klass(
5006 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005007 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005008 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005009 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005010 }
5011
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005012 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005013 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005014 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005015 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005016 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005017
Andreas Gampe58a5af82014-07-31 16:23:49 -07005018 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005019 const char* name = dex_file.GetFieldName(field_id);
5020 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5021 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005022 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005023 } else {
5024 resolved = klass->FindInstanceField(name, type);
5025 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005026 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005027 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005028 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005029 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005030 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005031 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005032 return resolved;
5033}
5034
Brian Carlstromea46f952013-07-30 01:26:50 -07005035mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005036 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005037 Handle<mirror::DexCache> dex_cache,
5038 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005039 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005040 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005041 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005042 return resolved;
5043 }
5044 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005045 Thread* self = Thread::Current();
5046 StackHandleScope<1> hs(self);
5047 Handle<mirror::Class> klass(
5048 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005049 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005050 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005051 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005052 }
5053
Ian Rogersdfb325e2013-10-30 01:00:44 -07005054 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5055 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005056 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005057 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005058 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005059 dex_cache->SetResolvedField(field_idx, resolved);
5060 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005061 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005062 }
5063 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005064}
5065
Brian Carlstromea46f952013-07-30 01:26:50 -07005066const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005067 uint32_t* length) {
5068 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5069 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005070 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005071 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005072 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005073}
5074
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005075void ClassLinker::DumpAllClasses(int flags) {
5076 if (dex_cache_image_class_lookup_required_) {
5077 MoveImageClassesToClassTable();
5078 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005079 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5080 // 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 -08005081 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005082 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005083 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005084 for (GcRoot<mirror::Class>& it : class_table_) {
5085 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005086 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005087 }
5088
5089 for (size_t i = 0; i < all_classes.size(); ++i) {
5090 all_classes[i]->DumpClass(std::cerr, flags);
5091 }
5092}
5093
Elliott Hughes956af0f2014-12-11 14:34:28 -08005094static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005095 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005096 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5097 base -= sizeof(void*); // Move backward so that code_offset != 0.
5098 const uint32_t code_offset = sizeof(void*);
5099 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005100}
5101
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005102bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5103 return (entry_point == GetQuickResolutionStub()) ||
5104 (quick_resolution_trampoline_ == entry_point);
5105}
5106
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005107bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5108 return (entry_point == GetQuickToInterpreterBridge()) ||
5109 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5110}
5111
5112bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5113 return (entry_point == GetQuickGenericJniStub()) ||
5114 (quick_generic_jni_trampoline_ == entry_point);
5115}
5116
5117const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5118 return GetQuickGenericJniStub();
5119}
5120
Elliott Hughes956af0f2014-12-11 14:34:28 -08005121void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5122 const void* method_code) const {
5123 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005124 oat_method.LinkMethod(method);
5125 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005126}
5127
5128void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5129 if (!method->IsNative()) {
5130 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005131 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5132 } else {
5133 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005134 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005135 oat_method.LinkMethod(method);
5136 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005137 }
5138}
5139
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005140void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005141 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005142 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005143 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005144 MoveImageClassesToClassTable();
5145 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005146 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005147 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5148 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005149}
5150
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005151size_t ClassLinker::NumLoadedClasses() {
5152 if (dex_cache_image_class_lookup_required_) {
5153 MoveImageClassesToClassTable();
5154 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005155 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005156 // Only return non zygote classes since these are the ones which apps which care about.
5157 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005158}
5159
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005160pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005161 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005162}
5163
5164pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005165 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005166}
5167
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005168void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005169 DCHECK(!init_done_);
5170
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005171 DCHECK(klass != nullptr);
5172 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005173
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005174 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005175 DCHECK(class_roots != nullptr);
5176 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005177 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005178}
5179
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005180const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5181 static const char* class_roots_descriptors[] = {
5182 "Ljava/lang/Class;",
5183 "Ljava/lang/Object;",
5184 "[Ljava/lang/Class;",
5185 "[Ljava/lang/Object;",
5186 "Ljava/lang/String;",
5187 "Ljava/lang/DexCache;",
5188 "Ljava/lang/ref/Reference;",
5189 "Ljava/lang/reflect/ArtField;",
5190 "Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005191 "Ljava/lang/reflect/Field;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005192 "Ljava/lang/reflect/Proxy;",
5193 "[Ljava/lang/String;",
5194 "[Ljava/lang/reflect/ArtField;",
5195 "[Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005196 "[Ljava/lang/reflect/Field;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005197 "Ljava/lang/ClassLoader;",
5198 "Ljava/lang/Throwable;",
5199 "Ljava/lang/ClassNotFoundException;",
5200 "Ljava/lang/StackTraceElement;",
5201 "Z",
5202 "B",
5203 "C",
5204 "D",
5205 "F",
5206 "I",
5207 "J",
5208 "S",
5209 "V",
5210 "[Z",
5211 "[B",
5212 "[C",
5213 "[D",
5214 "[F",
5215 "[I",
5216 "[J",
5217 "[S",
5218 "[Ljava/lang/StackTraceElement;",
5219 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005220 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5221 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005222
5223 const char* descriptor = class_roots_descriptors[class_root];
5224 CHECK(descriptor != nullptr);
5225 return descriptor;
5226}
5227
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005228std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5229 const {
5230 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005231 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005232}
5233
5234bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005235 const GcRoot<mirror::Class>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005236 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5237 return false;
5238 }
5239 std::string temp;
5240 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5241}
5242
5243std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5244 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005245 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005246}
5247
5248bool ClassLinker::ClassDescriptorHashEquals::operator()(
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005249 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005250 if (a.Read()->GetClassLoader() != b.second) {
5251 return false;
5252 }
5253 return a.Read()->DescriptorEquals(b.first);
5254}
5255
5256bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005257 const char* descriptor) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005258 return a.Read()->DescriptorEquals(descriptor);
5259}
5260
5261std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005262 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005263}
5264
Sebastien Hertz6963e442014-11-26 22:11:27 +01005265bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07005266 if (Runtime::Current()->UseJit()) {
5267 // JIT can have direct code pointers from any method to any other method.
5268 return true;
5269 }
Sebastien Hertz6963e442014-11-26 22:11:27 +01005270 // Non-image methods don't use direct code pointer.
5271 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
5272 return false;
5273 }
5274 if (m->IsPrivate()) {
5275 // The method can only be called inside its own oat file. Therefore it won't be called using
5276 // its direct code if the oat file has been compiled in PIC mode.
Sebastien Hertz6963e442014-11-26 22:11:27 +01005277 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
Richard Uhler07b3c232015-03-31 15:57:54 -07005278 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Sebastien Hertz6963e442014-11-26 22:11:27 +01005279 if (oat_dex_file == nullptr) {
5280 // No oat file: the method has not been compiled.
5281 return false;
5282 }
5283 const OatFile* oat_file = oat_dex_file->GetOatFile();
5284 return oat_file != nullptr && !oat_file->IsPic();
5285 } else {
5286 // The method can be called outside its own oat file. Therefore it won't be called using its
5287 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
5288 ReaderMutexLock mu(Thread::Current(), dex_lock_);
5289 for (const OatFile* oat_file : oat_files_) {
5290 if (!oat_file->IsPic()) {
5291 return true;
5292 }
5293 }
5294 return false;
5295 }
5296}
5297
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005298jobject ClassLinker::CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files) {
5299 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
5300 // We could move the jobject to the callers, but all call-sites do this...
5301 ScopedObjectAccessUnchecked soa(self);
5302
5303 // Register the dex files.
5304 for (const DexFile* dex_file : dex_files) {
5305 RegisterDexFile(*dex_file);
5306 }
5307
5308 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
5309 StackHandleScope<11> hs(self);
5310
5311 Handle<mirror::ArtField> h_dex_elements_field =
5312 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements));
5313
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005314 mirror::Class* dex_elements_class = h_dex_elements_field->GetType<true>();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005315 DCHECK(dex_elements_class != nullptr);
5316 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005317 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
5318 mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005319 Handle<mirror::Class> h_dex_element_class =
5320 hs.NewHandle(dex_elements_class->GetComponentType());
5321
5322 Handle<mirror::ArtField> h_element_file_field =
5323 hs.NewHandle(
5324 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
5325 DCHECK_EQ(h_dex_element_class.Get(), h_element_file_field->GetDeclaringClass());
5326
5327 Handle<mirror::ArtField> h_cookie_field =
5328 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005329 DCHECK_EQ(h_cookie_field->GetDeclaringClass(), h_element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005330
5331 // Fill the elements array.
5332 int32_t index = 0;
5333 for (const DexFile* dex_file : dex_files) {
5334 StackHandleScope<3> hs2(self);
5335
5336 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(self, 1));
5337 DCHECK(h_long_array.Get() != nullptr);
5338 h_long_array->Set(0, reinterpret_cast<intptr_t>(dex_file));
5339
5340 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
5341 h_cookie_field->GetDeclaringClass()->AllocObject(self));
5342 DCHECK(h_dex_file.Get() != nullptr);
5343 h_cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
5344
5345 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
5346 DCHECK(h_element.Get() != nullptr);
5347 h_element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
5348
5349 h_dex_elements->Set(index, h_element.Get());
5350 index++;
5351 }
5352 DCHECK_EQ(index, h_dex_elements->GetLength());
5353
5354 // Create DexPathList.
5355 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
5356 h_dex_elements_field->GetDeclaringClass()->AllocObject(self));
5357 DCHECK(h_dex_path_list.Get() != nullptr);
5358 // Set elements.
5359 h_dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
5360
5361 // Create PathClassLoader.
5362 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
5363 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
5364 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
5365 h_path_class_class->AllocObject(self));
5366 DCHECK(h_path_class_loader.Get() != nullptr);
5367 // Set DexPathList.
5368 Handle<mirror::ArtField> h_path_list_field = hs.NewHandle(
5369 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList));
5370 DCHECK(h_path_list_field.Get() != nullptr);
5371 h_path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
5372
5373 // Make a pretend boot-classpath.
5374 // TODO: Should we scan the image?
5375 Handle<mirror::ArtField> h_parent_field = hs.NewHandle(
5376 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent",
5377 "Ljava/lang/ClassLoader;"));
5378 DCHECK(h_parent_field.Get() != nullptr);
5379 mirror::Object* boot_cl =
5380 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
5381 h_parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
5382
5383 // Make it a global ref and return.
5384 ScopedLocalRef<jobject> local_ref(
5385 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
5386 return soa.Env()->NewGlobalRef(local_ref.get());
5387}
5388
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005389} // namespace art