blob: 33d75d2e26fb86e608d9ded13d5052dd506a482e [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*)) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700245 CHECK(intern_table_ != nullptr);
246 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
247 find_array_class_cache_[i] = GcRoot<mirror::Class>(nullptr);
248 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700249}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700250
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800251void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800252 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700253 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700254
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700255 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700256
Elliott Hughes30646832011-10-13 16:59:46 -0700257 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700258 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700259 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700260 // The GC can't handle an object with a null class since we can't get the size of this object.
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800261 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700262 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
263 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700264 heap->AllocNonMovableObject<true>(self, nullptr,
265 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700266 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700267 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700268 mirror::Class::SetClassClass(java_lang_Class.Get());
269 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700270 if (kUseBakerOrBrooksReadBarrier) {
271 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800272 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700273 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700274 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800275 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800276 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700277
Elliott Hughes418d20f2011-09-22 14:00:39 -0700278 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700279 Handle<mirror::Class> class_array_class(hs.NewHandle(
280 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700281 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700282
Ian Rogers23435d02012-09-24 11:23:12 -0700283 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700284 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
285 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700286 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700287 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700288 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700289 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700290
Ian Rogers23435d02012-09-24 11:23:12 -0700291 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700292 Handle<mirror::Class> object_array_class(hs.NewHandle(
293 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700294 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700295
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700296 // Setup the char (primitive) class to be used for char[].
297 Handle<mirror::Class> char_class(hs.NewHandle(
298 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700299 // The primitive char class won't be initialized by
300 // InitializePrimitiveClass until line 459, but strings (and
301 // internal char arrays) will be allocated before that and the
302 // component size, which is computed from the primitive type, needs
303 // to be set here.
304 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700305
Ian Rogers23435d02012-09-24 11:23:12 -0700306 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700307 Handle<mirror::Class> char_array_class(hs.NewHandle(
308 AllocClass(self, java_lang_Class.Get(),
309 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700310 char_array_class->SetComponentType(char_class.Get());
311 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700312
Ian Rogers23435d02012-09-24 11:23:12 -0700313 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700314 Handle<mirror::Class> java_lang_String(hs.NewHandle(
315 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700316 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700317 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700318 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400319
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700320 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700321 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
322 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
323 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
324 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700325 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700326
Ian Rogers23435d02012-09-24 11:23:12 -0700327 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700328 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700329 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
330 kClassRootsMax));
331 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700332 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
333 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
334 SetClassRoot(kClassArrayClass, class_array_class.Get());
335 SetClassRoot(kObjectArrayClass, object_array_class.Get());
336 SetClassRoot(kCharArrayClass, char_array_class.Get());
337 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700338 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700339
340 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700341 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
342 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
343 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
344 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
345 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
346 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
347 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
348 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349
Ian Rogers23435d02012-09-24 11:23:12 -0700350 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700351 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700352
Ian Rogers23435d02012-09-24 11:23:12 -0700353 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700354 Handle<mirror::Class> int_array_class(hs.NewHandle(
355 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700356 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700357 mirror::IntArray::SetArrayClass(int_array_class.Get());
358 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700360 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700361
Ian Rogers52813c92012-10-11 11:50:38 -0700362 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700363 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
364 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700365 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700366 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700367 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700368
Brian Carlstromf3632832014-05-20 15:36:53 -0700369 // Constructor, Field, Method, and AbstractMethod are necessary so
370 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700371 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
372 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700373 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700374 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700375 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700376 mirror::Class::SetStatus(java_lang_reflect_ArtField, mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700377 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700378
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700379 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
380 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700381 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800382 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
383 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700384 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700385 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700386 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700387
388 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700389 Handle<mirror::Class> object_array_string(hs.NewHandle(
390 AllocClass(self, java_lang_Class.Get(),
391 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700392 object_array_string->SetComponentType(java_lang_String.Get());
393 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700394
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700395 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
396 AllocClass(self, java_lang_Class.Get(),
397 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700398 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
399 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700400
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700401 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
402 AllocClass(self, java_lang_Class.Get(),
403 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700404 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
405 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700406
Ian Rogers23435d02012-09-24 11:23:12 -0700407 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
408 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
409 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700410 CHECK_NE(0U, boot_class_path.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800411 for (auto& dex_file : boot_class_path) {
412 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700413 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800414 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700415 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700416
417 // now we can use FindSystemClass
418
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700419 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700420 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
421 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700422
Jeff Hao88474b42013-10-23 16:24:40 -0700423 // Create runtime resolution and imt conflict methods. Also setup the default imt.
424 Runtime* runtime = Runtime::Current();
425 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
426 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700427 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700428 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
429
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700430 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
431 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700432 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800433 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700434 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700435 quick_resolution_trampoline_ = GetQuickResolutionStub();
436 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
437 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700438 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700439
Mathieu Chartier66f19252012-09-18 08:57:04 -0700440 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700441 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800442 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700443 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700444 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700445 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800446 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700447 std::ostringstream os1, os2;
448 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
449 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
450 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
451 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700452 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800453 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700454 CHECK_EQ(java_lang_String.Get(), String_class);
455 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700456 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700457
Ian Rogers23435d02012-09-24 11:23:12 -0700458 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800459 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800460 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700461
Ian Rogers98379392014-02-24 16:53:16 -0800462 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800463 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700464
Ian Rogers98379392014-02-24 16:53:16 -0800465 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700466 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700467
Ian Rogers98379392014-02-24 16:53:16 -0800468 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800469 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470
Ian Rogers98379392014-02-24 16:53:16 -0800471 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700472 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700473
Ian Rogers98379392014-02-24 16:53:16 -0800474 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800475 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700476
Ian Rogers98379392014-02-24 16:53:16 -0800477 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800478 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700479
Ian Rogers98379392014-02-24 16:53:16 -0800480 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800481 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700482
Ian Rogers98379392014-02-24 16:53:16 -0800483 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700484 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700485
Ian Rogers98379392014-02-24 16:53:16 -0800486 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700487 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700488
Ian Rogers23435d02012-09-24 11:23:12 -0700489 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800490 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700491 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800492 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700493 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700494 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
495 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700496 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700497 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700498 array_iftable->SetInterface(0, java_lang_Cloneable);
499 array_iftable->SetInterface(1, java_io_Serializable);
500 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700501
Ian Rogers23435d02012-09-24 11:23:12 -0700502 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700503 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
504 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
505 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
506 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700507 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700508 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800509 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700510 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700511
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700512 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800513 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700514 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700515
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700516 mirror::Class::SetStatus(java_lang_reflect_ArtField, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800517 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700518 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700519
Brian Carlstromf3632832014-05-20 15:36:53 -0700520 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700521 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700522 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700523
Brian Carlstromea46f952013-07-30 01:26:50 -0700524 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700525 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700526 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700527
Brian Carlstromea46f952013-07-30 01:26:50 -0700528 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700529 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700530 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700531
Ian Rogers23435d02012-09-24 11:23:12 -0700532 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700533
Ian Rogers23435d02012-09-24 11:23:12 -0700534 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800535 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700536 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
537
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700538 // Create java.lang.reflect.Field.class root.
539 mirror::Class* java_lang_reflect_Field = FindSystemClass(self, "Ljava/lang/reflect/Field;");
540 CHECK(java_lang_reflect_Field != nullptr);
541 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
542 mirror::Field::SetClass(java_lang_reflect_Field);
543
544 // Create java.lang.reflect.Field array root.
545 mirror::Class* java_lang_reflect_Field_array =
546 FindSystemClass(self, "[Ljava/lang/reflect/Field;");
547 CHECK(java_lang_reflect_Field_array != nullptr);
548 SetClassRoot(kJavaLangReflectFieldArrayClass, java_lang_reflect_Field_array);
549 mirror::Field::SetArrayClass(java_lang_reflect_Field_array);
550
Brian Carlstrom1f870082011-08-23 16:02:11 -0700551 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700552 // finish initializing Reference class
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700553 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700554 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
555 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
556 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
557 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700558 mirror::Class* java_lang_ref_FinalizerReference =
559 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700560 java_lang_ref_FinalizerReference->SetAccessFlags(
561 java_lang_ref_FinalizerReference->GetAccessFlags() |
562 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700563 mirror::Class* java_lang_ref_PhantomReference =
564 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700565 java_lang_ref_PhantomReference->SetAccessFlags(
566 java_lang_ref_PhantomReference->GetAccessFlags() |
567 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700568 mirror::Class* java_lang_ref_SoftReference =
569 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700570 java_lang_ref_SoftReference->SetAccessFlags(
571 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700572 mirror::Class* java_lang_ref_WeakReference =
573 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700574 java_lang_ref_WeakReference->SetAccessFlags(
575 java_lang_ref_WeakReference->GetAccessFlags() |
576 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700577
Ian Rogers23435d02012-09-24 11:23:12 -0700578 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800579 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700580 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700581 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
582
jeffhao8cd6dda2012-02-22 10:15:34 -0800583 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700584 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800585 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800586 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700587 SetClassRoot(kJavaLangClassNotFoundException,
588 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800589 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700590 SetClassRoot(kJavaLangStackTraceElementArrayClass,
591 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800592 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700593
Andreas Gampe76bd8802014-12-10 16:43:58 -0800594 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
595 // initialized.
596 {
597 const DexFile& dex_file = java_lang_Object->GetDexFile();
598 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
599 CHECK(void_string_id != nullptr);
600 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
601 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
602 CHECK(void_type_id != nullptr);
603 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
604 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
605 // as referrer so the used dex cache is core's one.
606 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
607 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
608 self->AssertNoPendingException();
609 }
610
Ian Rogers98379392014-02-24 16:53:16 -0800611 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700612
Brian Carlstroma004aa92012-02-08 18:05:09 -0800613 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700614}
615
Ian Rogers98379392014-02-24 16:53:16 -0800616void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800617 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700618
619 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700620 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700621 // as the types of the field can't be resolved prior to the runtime being
622 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800623 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700624 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800625 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800626
Brian Carlstromea46f952013-07-30 01:26:50 -0700627 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700628 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
629 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700630
Brian Carlstromea46f952013-07-30 01:26:50 -0700631 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700632 CHECK_STREQ(queue->GetName(), "queue");
633 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700634
Brian Carlstromea46f952013-07-30 01:26:50 -0700635 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700636 CHECK_STREQ(queueNext->GetName(), "queueNext");
637 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700638
Brian Carlstromea46f952013-07-30 01:26:50 -0700639 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700640 CHECK_STREQ(referent->GetName(), "referent");
641 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700642
Brian Carlstromea46f952013-07-30 01:26:50 -0700643 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700644 CHECK_STREQ(zombie->GetName(), "zombie");
645 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700646
Brian Carlstroma663ea52011-08-19 23:33:41 -0700647 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700648 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700649 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800650 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700651 CHECK(klass != nullptr);
652 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700653 // note SetClassRoot does additional validation.
654 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700655 }
656
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700657 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700658
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700659 // disable the slow paths in FindClass and CreatePrimitiveClass now
660 // that Object, Class, and Object[] are setup
661 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700662
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800663 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700664}
665
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700666void ClassLinker::RunRootClinits() {
667 Thread* self = Thread::Current();
668 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800669 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700670 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700671 StackHandleScope<1> hs(self);
672 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700673 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700674 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700675 }
676 }
677}
678
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700679const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700680 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800681 if (kIsDebugBuild) {
682 for (size_t i = 0; i < oat_files_.size(); ++i) {
683 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700684 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800685 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700686 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
687 oat_files_.push_back(oat_file);
688 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800689}
690
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700691OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
692 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700693 OatFile* oat_file = space->ReleaseOatFile();
694 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700695 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700696 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700697}
698
Richard Uhler66d874d2015-01-15 09:37:19 -0800699std::vector<std::unique_ptr<const DexFile>> ClassLinker::OpenDexFilesFromOat(
700 const char* dex_location, const char* oat_location,
701 std::vector<std::string>* error_msgs) {
702 CHECK(error_msgs != nullptr);
Calin Juravle621962a2014-09-02 15:53:55 +0100703
Richard Uhler66d874d2015-01-15 09:37:19 -0800704 // Verify we aren't holding the mutator lock, which could starve GC if we
705 // have to generate or relocate an oat file.
706 Locks::mutator_lock_->AssertNotHeld(Thread::Current());
707
708 OatFileAssistant oat_file_assistant(dex_location, oat_location, kRuntimeISA,
709 !Runtime::Current()->IsAotCompiler());
710
711 // Lock the target oat location to avoid races generating and loading the
712 // oat file.
713 std::string error_msg;
714 if (!oat_file_assistant.Lock(&error_msg)) {
715 // Don't worry too much if this fails. If it does fail, it's unlikely we
716 // can generate an oat file anyway.
717 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700718 }
719
Richard Uhler66d874d2015-01-15 09:37:19 -0800720 // Check if we already have an up-to-date oat file open.
721 const OatFile* source_oat_file = nullptr;
722 {
723 ReaderMutexLock mu(Thread::Current(), dex_lock_);
724 for (const OatFile* oat_file : oat_files_) {
725 CHECK(oat_file != nullptr);
726 if (oat_file_assistant.GivenOatFileIsUpToDate(*oat_file)) {
727 source_oat_file = oat_file;
728 break;
Andreas Gampe833a4852014-05-21 18:46:59 -0700729 }
730 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700731 }
732
Richard Uhler66d874d2015-01-15 09:37:19 -0800733 // If we didn't have an up-to-date oat file open, try to load one from disk.
734 if (source_oat_file == nullptr) {
735 // Update the oat file on disk if we can. This may fail, but that's okay.
736 // Best effort is all that matters here.
737 if (!oat_file_assistant.MakeUpToDate(&error_msg)) {
738 LOG(WARNING) << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700739 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700740
Richard Uhler66d874d2015-01-15 09:37:19 -0800741 // Get the oat file on disk.
742 std::unique_ptr<OatFile> oat_file = oat_file_assistant.GetBestOatFile();
743 if (oat_file.get() != nullptr) {
744 source_oat_file = oat_file.release();
745 RegisterOatFile(source_oat_file);
Andreas Gampe833a4852014-05-21 18:46:59 -0700746 }
747 }
748
Richard Uhler66d874d2015-01-15 09:37:19 -0800749 std::vector<std::unique_ptr<const DexFile>> dex_files;
Andreas Gampe833a4852014-05-21 18:46:59 -0700750
Richard Uhler66d874d2015-01-15 09:37:19 -0800751 // Load the dex files from the oat file.
752 if (source_oat_file != nullptr) {
753 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
754 if (dex_files.empty()) {
755 error_msgs->push_back("Failed to open dex files from "
756 + source_oat_file->GetLocation());
Andreas Gampe833a4852014-05-21 18:46:59 -0700757 }
758 }
759
Richard Uhler66d874d2015-01-15 09:37:19 -0800760 // Fall back to running out of the original dex file if we couldn't load any
761 // dex_files from the oat file.
762 if (dex_files.empty()) {
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700763 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800764 if (!DexFile::Open(dex_location, dex_location, &error_msg, &dex_files)) {
765 LOG(WARNING) << error_msg;
766 error_msgs->push_back("Failed to open dex files from "
767 + std::string(dex_location));
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700768 }
769 } else {
770 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
771 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700772 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800773 return dex_files;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700774}
775
Brian Carlstromae826982011-11-09 01:33:42 -0800776const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700777 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700778 for (size_t i = 0; i < oat_files_.size(); i++) {
779 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700780 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -0800781 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700782 return oat_file;
783 }
784 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700785 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -0700786}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700787
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800788void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700789 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700790 DCHECK(obj != nullptr);
791 DCHECK(class_linker != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700792 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700793 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -0700794 if (!method->IsNative()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800795 const size_t pointer_size = class_linker->image_pointer_size_;
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800796 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800797 if (!method->IsRuntimeMethod() && method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800798 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
799 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -0700800 }
801 }
802 }
803}
804
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700805void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800806 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700807 CHECK(!init_done_);
808
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700809 Runtime* const runtime = Runtime::Current();
810 Thread* const self = Thread::Current();
811 gc::Heap* const heap = runtime->GetHeap();
812 gc::space::ImageSpace* const space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700813 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700814 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700815 OatFile& oat_file = GetImageOatFile(space);
816 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
817 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700818 const char* image_file_location = oat_file.GetOatHeader().
819 GetStoreValueByKey(OatHeader::kImageLocationKey);
820 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700821 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -0700822 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -0800823 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +0100824 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800825 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
826 mirror::ObjectArray<mirror::DexCache>* dex_caches =
827 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700828
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700829 StackHandleScope<1> hs(self);
830 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
831 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
832 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700833 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700834
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700835 // Special case of setting up the String class early so that we can test arbitrary objects
836 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700837 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800838
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700839 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700840 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700841 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800842 StackHandleScope<1> hs2(self);
843 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700844 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700845 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
846 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700847 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700848 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800849 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
850 if (dex_file.get() == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700851 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700852 << " from within oat file " << oat_file.GetLocation()
853 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -0800854 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700855 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700856
857 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
858
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800859 AppendToBootClassPath(*dex_file.get(), dex_cache);
860 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700861 }
862
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700863 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
864 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -0700865 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -0800866 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700867 if (!runtime->IsAotCompiler()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800868 // Aot compiler supports having an image with a different pointer size than the runtime. This
Mathieu Chartier2d721012014-11-10 11:08:06 -0800869 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
870 // also use 32 bit dex2oat on a system with 64 bit apps.
871 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
872 << sizeof(void*);
873 }
874 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
875 image_pointer_size_ = 4;
876 } else {
877 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
878 image_pointer_size_ = 8;
879 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700880
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700881 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800882 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700883 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700884 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700885
886 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800887 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700888 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700889
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800890 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700891 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800892 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800893 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700894 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
895 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Fred Shih4ee7a662014-07-11 09:59:27 -0700896 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -0700897 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800898 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
899 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
900 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
901 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
902 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
903 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
904 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
905 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
906 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
907 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700908
Ian Rogers98379392014-02-24 16:53:16 -0800909 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700910
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800911 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700912}
913
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700914void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700915 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
916 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700917 BufferedRootVisitor<128> buffered_visitor(visitor, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800918 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700919 buffered_visitor.VisitRoot(root);
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800920 }
921 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700922 buffered_visitor.VisitRoot(root);
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700923 }
924 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800925 for (auto& root : new_class_roots_) {
926 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700927 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800928 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700929 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700930 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
931 // corresponding object. This is slow, but luckily for us, this may only happen with a
932 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800933 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800934 DCHECK(it != class_table_.end());
935 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700936 }
937 }
938 }
939 if ((flags & kVisitRootFlagClearRootLog) != 0) {
940 new_class_roots_.clear();
941 }
942 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
943 log_new_class_table_roots_ = true;
944 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
945 log_new_class_table_roots_ = false;
946 }
947 // We deliberately ignore the class roots in the image since we
948 // handle image roots by using the MS/CMS rescanning of dirty cards.
949}
950
Brian Carlstroma663ea52011-08-19 23:33:41 -0700951// Keep in sync with InitCallback. Anything we visit, we need to
952// reinit references to when reinitializing a ClassLinker from a
953// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700954void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
955 class_roots_.VisitRoot(visitor, RootInfo(kRootVMInternal));
956 Thread* const self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -0700957 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700958 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800959 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700960 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700961 dex_cache.VisitRoot(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -0700962 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800963 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
964 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700965 dex_caches_[index].VisitRoot(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -0700966 }
Elliott Hughesf8349362012-06-18 15:00:06 -0700967 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800968 if ((flags & kVisitRootFlagClearRootLog) != 0) {
969 new_dex_cache_roots_.clear();
970 }
971 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
972 log_new_dex_caches_roots_ = true;
973 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
974 log_new_dex_caches_roots_ = false;
975 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700976 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700977 VisitClassRoots(visitor, flags);
978 array_iftable_.VisitRoot(visitor, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -0800979 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700980 find_array_class_cache_[i].VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -0800981 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700982}
983
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700984void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
985 if (dex_cache_image_class_lookup_required_) {
986 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -0800987 }
Ian Rogersdbf3be02014-08-29 15:40:08 -0700988 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -0800989 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800990 for (GcRoot<mirror::Class>& root : class_table_) {
991 if (!visitor(root.Read(), arg)) {
992 return;
993 }
994 }
995 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
996 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -0800997 return;
998 }
999 }
1000}
1001
Ian Rogersdbf3be02014-08-29 15:40:08 -07001002static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001003 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001004 classes->insert(c);
1005 return true;
1006}
1007
Ian Rogersdbf3be02014-08-29 15:40:08 -07001008struct GetClassesVisitorArrayArg {
1009 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1010 int32_t index;
1011 bool success;
1012};
1013
1014static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1015 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1016 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1017 if (arg->index < (*arg->classes)->GetLength()) {
1018 (*arg->classes)->Set(arg->index, c);
1019 arg->index++;
1020 return true;
1021 } else {
1022 arg->success = false;
1023 return false;
1024 }
1025}
1026
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001027void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001028 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1029 // is avoiding duplicates.
1030 if (!kMovingClasses) {
1031 std::set<mirror::Class*> classes;
1032 VisitClasses(GetClassesVisitorSet, &classes);
1033 for (mirror::Class* klass : classes) {
1034 if (!visitor(klass, arg)) {
1035 return;
1036 }
1037 }
1038 } else {
1039 Thread* self = Thread::Current();
1040 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001041 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001042 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1043 GetClassesVisitorArrayArg local_arg;
1044 local_arg.classes = &classes;
1045 local_arg.success = false;
1046 // We size the array assuming classes won't be added to the class table during the visit.
1047 // If this assumption fails we iterate again.
1048 while (!local_arg.success) {
1049 size_t class_table_size;
1050 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001051 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001052 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001053 }
1054 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1055 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1056 classes.Assign(
1057 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1058 CHECK(classes.Get() != nullptr); // OOME.
1059 local_arg.index = 0;
1060 local_arg.success = true;
1061 VisitClasses(GetClassesVisitorArray, &local_arg);
1062 }
1063 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1064 // If the class table shrank during creation of the clases array we expect null elements. If
1065 // the class table grew then the loop repeats. If classes are created after the loop has
1066 // finished then we don't visit.
1067 mirror::Class* klass = classes->Get(i);
1068 if (klass != nullptr && !visitor(klass, arg)) {
1069 return;
1070 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001071 }
1072 }
1073}
1074
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001075ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001076 mirror::Class::ResetClass();
1077 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001078 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001079 mirror::ArtField::ResetClass();
1080 mirror::ArtMethod::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001081 mirror::Field::ResetClass();
1082 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001083 mirror::BooleanArray::ResetArrayClass();
1084 mirror::ByteArray::ResetArrayClass();
1085 mirror::CharArray::ResetArrayClass();
1086 mirror::DoubleArray::ResetArrayClass();
1087 mirror::FloatArray::ResetArrayClass();
1088 mirror::IntArray::ResetArrayClass();
1089 mirror::LongArray::ResetArrayClass();
1090 mirror::ShortArray::ResetArrayClass();
1091 mirror::Throwable::ResetClass();
1092 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001093 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001094}
1095
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001096mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001097 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001098 StackHandleScope<16> hs(self);
1099 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1100 Handle<mirror::DexCache> dex_cache(
1101 hs.NewHandle(down_cast<mirror::DexCache*>(
1102 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1103 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001104 if (dex_cache.Get() == nullptr) {
1105 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001106 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001107 Handle<mirror::String>
1108 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001109 if (location.Get() == nullptr) {
1110 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001111 }
Ian Rogers700a4022014-05-19 16:49:03 -07001112 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001113 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001114 if (strings.Get() == nullptr) {
1115 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001116 }
Ian Rogers700a4022014-05-19 16:49:03 -07001117 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001118 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001119 if (types.Get() == nullptr) {
1120 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001121 }
Ian Rogers700a4022014-05-19 16:49:03 -07001122 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001123 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001124 if (methods.Get() == nullptr) {
1125 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001126 }
Ian Rogers700a4022014-05-19 16:49:03 -07001127 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001128 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001129 if (fields.Get() == nullptr) {
1130 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001131 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001132 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1133 fields.Get());
1134 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001135}
1136
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001137mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001138 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001139 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001140 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001141 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001142 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001143 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1144 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001145 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001146 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001147 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001148 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001149 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001150}
1151
Ian Rogers6fac4472014-02-25 17:01:10 -08001152mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001153 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001154}
1155
Brian Carlstromea46f952013-07-30 01:26:50 -07001156mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001157 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001158 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001159}
1160
Brian Carlstromea46f952013-07-30 01:26:50 -07001161mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001162 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001163 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001164}
1165
Mathieu Chartier590fee92013-09-13 13:46:47 -07001166mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1167 Thread* self, size_t length) {
1168 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1169 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001170}
1171
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001172mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1173 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001174 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001175
1176 // For temporary classes we must wait for them to be retired.
1177 if (init_done_ && klass->IsTemp()) {
1178 CHECK(!klass->IsResolved());
1179 if (klass->IsErroneous()) {
1180 ThrowEarlierClassFailure(klass);
1181 return nullptr;
1182 }
1183 StackHandleScope<1> hs(self);
1184 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1185 ObjectLock<mirror::Class> lock(self, h_class);
1186 // Loop and wait for the resolving thread to retire this class.
1187 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1188 lock.WaitIgnoringInterrupts();
1189 }
1190 if (h_class->IsErroneous()) {
1191 ThrowEarlierClassFailure(h_class.Get());
1192 return nullptr;
1193 }
1194 CHECK(h_class->IsRetired());
1195 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001196 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
1197 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001198 }
1199
Brian Carlstromaded5f72011-10-07 17:15:04 -07001200 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001201 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001202 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001203 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1204 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001205 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001206 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1207 ThrowClassCircularityError(h_class.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001208 mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001209 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001210 }
1211 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001212 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001213 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001214 }
1215 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001216
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001217 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001218 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001219 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001220 }
1221 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001222 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001223 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001224 return klass;
1225}
1226
Ian Rogers68b56852014-08-29 20:19:11 -07001227typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
1228
1229// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001230ClassPathEntry FindInClassPath(const char* descriptor,
1231 size_t hash, const std::vector<const DexFile*>& class_path) {
1232 for (const DexFile* dex_file : class_path) {
1233 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001234 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07001235 return ClassPathEntry(dex_file, dex_class_def);
1236 }
1237 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001238 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07001239}
1240
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001241mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1242 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001243 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001244 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08001245 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001246 if (class_loader->GetClass() !=
1247 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
1248 class_loader->GetParent()->GetClass() !=
1249 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
1250 return nullptr;
1251 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001252 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001253 // Check if this would be found in the parent boot class loader.
1254 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001255 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001256 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08001257 // May return null if resolution on another thread fails.
1258 klass = EnsureResolved(self, descriptor, klass);
1259 } else {
1260 // May OOME.
1261 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
1262 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001263 }
Ian Rogers32427292014-11-19 14:05:21 -08001264 if (klass == nullptr) {
1265 CHECK(self->IsExceptionPending()) << descriptor;
1266 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001267 }
Ian Rogers32427292014-11-19 14:05:21 -08001268 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001269 } else {
Ian Rogers32427292014-11-19 14:05:21 -08001270 // Handle as if this is the child PathClassLoader.
1271 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001272 StackHandleScope<3> hs(self);
1273 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
1274 // We need to get the DexPathList and loop through it.
1275 Handle<mirror::ArtField> cookie_field =
1276 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
1277 Handle<mirror::ArtField> dex_file_field =
1278 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07001279 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001280 mirror::Object* dex_path_list =
1281 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
1282 GetObject(class_loader.Get());
1283 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
1284 cookie_field.Get() != nullptr) {
1285 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1286 mirror::Object* dex_elements_obj =
1287 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1288 GetObject(dex_path_list);
1289 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1290 // at the mCookie which is a DexFile vector.
1291 if (dex_elements_obj != nullptr) {
1292 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
1293 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
1294 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
1295 mirror::Object* element = dex_elements->GetWithoutChecks(i);
1296 if (element == nullptr) {
1297 // Should never happen, fall back to java code to throw a NPE.
1298 break;
1299 }
1300 mirror::Object* dex_file = dex_file_field->GetObject(element);
1301 if (dex_file != nullptr) {
Andreas Gampe324b9bb2015-02-23 16:33:22 -08001302 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
1303 if (long_array == nullptr) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001304 // This should never happen so log a warning.
1305 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
1306 break;
1307 }
Andreas Gampe324b9bb2015-02-23 16:33:22 -08001308 int32_t long_array_size = long_array->GetLength();
1309 for (int32_t j = 0; j < long_array_size; ++j) {
1310 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
1311 long_array->GetWithoutChecks(j)));
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001312 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001313 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001314 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001315 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
1316 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001317 if (klass == nullptr) {
1318 CHECK(self->IsExceptionPending()) << descriptor;
1319 self->ClearException();
1320 return nullptr;
1321 }
1322 return klass;
1323 }
1324 }
1325 }
1326 }
1327 }
1328 }
Ian Rogers32427292014-11-19 14:05:21 -08001329 self->AssertNoPendingException();
1330 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001331 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001332}
1333
Ian Rogers98379392014-02-24 16:53:16 -08001334mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001335 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001336 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001337 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001338 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001339 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001340 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1341 // for primitive classes that aren't backed by dex files.
1342 return FindPrimitiveClass(descriptor[0]);
1343 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001344 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001345 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001346 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07001347 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001348 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001349 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001350 // Class is not yet loaded.
1351 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001352 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001353 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001354 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001355 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07001356 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001357 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07001358 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07001359 } else {
1360 // The boot class loader is searched ahead of the application class loader, failures are
1361 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
1362 // trigger the chaining with a proper stack trace.
1363 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001364 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07001365 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05001366 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001367 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001368 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001369 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
1370 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001371 if (cp_klass != nullptr) {
1372 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07001373 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001374
1375 if (Runtime::Current()->IsAotCompiler()) {
1376 // Oops, compile-time, can't run actual class-loader code.
1377 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
1378 self->SetException(pre_allocated);
1379 return nullptr;
1380 }
1381
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001382 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001383 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001384 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07001385 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07001386 {
1387 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001388 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1389 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07001390 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001391 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07001392 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07001393 }
Ian Rogers68b56852014-08-29 20:19:11 -07001394 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001395 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1396 WellKnownClasses::java_lang_ClassLoader_loadClass,
1397 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001398 }
Ian Rogers98379392014-02-24 16:53:16 -08001399 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001400 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07001401 return nullptr;
1402 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08001403 // broken loader - throw NPE to be compatible with Dalvik
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001404 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
1405 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07001406 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08001407 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001408 // success, return mirror::Class*
1409 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001410 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001411 }
Ian Rogers07140832014-09-30 15:43:59 -07001412 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001413}
1414
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001415mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001416 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001417 const DexFile& dex_file,
1418 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001419 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001420 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001421
Brian Carlstromaded5f72011-10-07 17:15:04 -07001422 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001423 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001424 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001425 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001426 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001427 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001428 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001429 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001430 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001431 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1432 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001433 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001434 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001435 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001436 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001437 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001438 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001439 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001440 }
1441
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001442 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001443 // Allocate a class with the status of not ready.
1444 // Interface object should get the right size here. Regular class will
1445 // figure out the right size later and be replaced with one of the right
1446 // size when the class becomes resolved.
1447 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001448 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001449 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001450 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07001451 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001452 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001453 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07001454 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001455 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001456 if (self->IsExceptionPending()) {
1457 // An exception occured during load, set status to erroneous while holding klass' lock in case
1458 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001459 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001460 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001461 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001462 return nullptr;
1463 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001464 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001465
Mathieu Chartier590fee92013-09-13 13:46:47 -07001466 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001467 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001468 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001469 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1470 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001471 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001472 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001473
Brian Carlstromaded5f72011-10-07 17:15:04 -07001474 // Finish loading (if necessary) by finding parents
1475 CHECK(!klass->IsLoaded());
1476 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1477 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001478 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001479 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001480 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001481 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001482 }
1483 CHECK(klass->IsLoaded());
1484 // Link the class (if necessary)
1485 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001486 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001487 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001488
1489 mirror::Class* new_class = nullptr;
1490 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001491 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001492 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001493 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001494 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001495 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001496 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07001497 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001498 CHECK(new_class != nullptr) << descriptor;
1499 CHECK(new_class->IsResolved()) << descriptor;
1500
1501 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001502
Sebastien Hertza8a697f2015-01-15 12:28:47 +01001503 // Instrumentation may have updated entrypoints for all methods of all
1504 // classes. However it could not update methods of this class while we
1505 // were loading it. Now the class is resolved, we can update entrypoints
1506 // as required by instrumentation.
1507 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
1508 // We must be in the kRunnable state to prevent instrumentation from
1509 // suspending all threads to update entrypoints while we are doing it
1510 // for this class.
1511 DCHECK_EQ(self->GetState(), kRunnable);
1512 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(new_class_h.Get());
1513 }
1514
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001515 /*
1516 * We send CLASS_PREPARE events to the debugger from here. The
1517 * definition of "preparation" is creating the static fields for a
1518 * class and initializing them to the standard default values, but not
1519 * executing any code (that comes later, during "initialization").
1520 *
1521 * We did the static preparation in LinkClass.
1522 *
1523 * The class has been prepared and resolved but possibly not yet verified
1524 * at this point.
1525 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001526 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001527
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001528 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001529}
1530
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001531uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
1532 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07001533 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001534 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07001535 size_t num_8 = 0;
1536 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001537 size_t num_32 = 0;
1538 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001539 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001540 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1541 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001542 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001543 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07001544 switch (c) {
1545 case 'L':
1546 case '[':
1547 num_ref++;
1548 break;
1549 case 'J':
1550 case 'D':
1551 num_64++;
1552 break;
1553 case 'I':
1554 case 'F':
1555 num_32++;
1556 break;
1557 case 'S':
1558 case 'C':
1559 num_16++;
1560 break;
1561 case 'B':
1562 case 'Z':
1563 num_8++;
1564 break;
1565 default:
1566 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08001567 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001568 }
1569 }
1570 }
Fred Shih37f05ef2014-07-16 18:38:08 -07001571 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001572}
1573
Ian Rogers97b52f82014-08-14 11:34:07 -07001574OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
1575 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001576 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Richard Uhler07b3c232015-03-31 15:57:54 -07001577 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001578 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001579 *found = false;
1580 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001581 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001582 *found = true;
1583 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08001584}
1585
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001586static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
1587 uint32_t method_idx) {
1588 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07001589 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001590 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001591 ClassDataItemIterator it(dex_file, class_data);
1592 // Skip fields
1593 while (it.HasNextStaticField()) {
1594 it.Next();
1595 }
1596 while (it.HasNextInstanceField()) {
1597 it.Next();
1598 }
1599 // Process methods
1600 size_t class_def_method_index = 0;
1601 while (it.HasNextDirectMethod()) {
1602 if (it.GetMemberIndex() == method_idx) {
1603 return class_def_method_index;
1604 }
1605 class_def_method_index++;
1606 it.Next();
1607 }
1608 while (it.HasNextVirtualMethod()) {
1609 if (it.GetMemberIndex() == method_idx) {
1610 return class_def_method_index;
1611 }
1612 class_def_method_index++;
1613 it.Next();
1614 }
1615 DCHECK(!it.HasNext());
1616 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08001617 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001618}
1619
Ian Rogers97b52f82014-08-14 11:34:07 -07001620const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08001621 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001622 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001623 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08001624 size_t oat_method_index;
1625 if (method->IsStatic() || method->IsDirect()) {
1626 // Simple case where the oat method index was stashed at load time.
1627 oat_method_index = method->GetMethodIndex();
1628 } else {
1629 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1630 // by search for its position in the declared virtual methods.
1631 oat_method_index = declaring_class->NumDirectMethods();
1632 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001633 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001634 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07001635 // Check method index instead of identity in case of duplicate method definitions.
1636 if (method->GetDexMethodIndex() ==
1637 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001638 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001639 break;
1640 }
Ian Rogersf320b632012-03-13 18:47:47 -07001641 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001642 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001643 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
1644 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001645 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001646 DCHECK_EQ(oat_method_index,
1647 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001648 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001649 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07001650 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
1651 declaring_class->GetDexClassDefIndex(),
1652 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001653 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001654 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001655 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001656 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07001657}
1658
1659// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001660const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001661 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07001662 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001663 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07001664 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001665 bool found;
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001666 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1667 if (found) {
1668 auto* code = oat_method.GetQuickCode();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001669 if (code != nullptr) {
1670 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08001671 }
1672 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001673 jit::Jit* const jit = Runtime::Current()->GetJit();
1674 if (jit != nullptr) {
1675 auto* code = jit->GetCodeCache()->GetCodeFor(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001676 if (code != nullptr) {
1677 return code;
1678 }
1679 }
1680 if (method->IsNative()) {
1681 // No code and native? Use generic trampoline.
1682 return GetQuickGenericJniStub();
1683 }
1684 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07001685}
1686
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001687const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
1688 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
1689 return nullptr;
1690 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001691 bool found;
1692 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1693 if (found) {
1694 return oat_method.GetQuickCode();
1695 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001696 jit::Jit* jit = Runtime::Current()->GetJit();
1697 if (jit != nullptr) {
1698 auto* code = jit->GetCodeCache()->GetCodeFor(method);
1699 if (code != nullptr) {
1700 return code;
1701 }
1702 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001703 return nullptr;
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001704}
1705
Ian Rogersef7d42f2014-01-06 12:55:46 -08001706const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
1707 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001708 bool found;
1709 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
1710 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001711 return nullptr;
1712 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001713 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001714 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001715}
1716
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001717// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001718static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07001719 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08001720 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001721 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08001722 // May return true for native code, in the case of generic JNI
1723 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001724 return true;
1725 }
1726 // If interpreter mode is enabled, every method (except native and proxy) must
1727 // be run with interpreter.
1728 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
1729 !method->IsNative() && !method->IsProxyMethod();
1730}
1731
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001732void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08001733 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07001734 if (klass->NumDirectMethods() == 0) {
1735 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08001736 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001737 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001738 if (!runtime->IsStarted()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001739 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001740 return; // OAT file unavailable.
1741 }
Ian Rogers19846512012-02-24 11:42:47 -08001742 }
Alex Light64ad14d2014-08-19 14:23:13 -07001743
Mathieu Chartierf8322842014-05-16 10:59:25 -07001744 const DexFile& dex_file = klass->GetDexFile();
1745 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07001746 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07001747 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07001748 // There should always be class data if there were direct methods.
1749 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08001750 ClassDataItemIterator it(dex_file, class_data);
1751 // Skip fields
1752 while (it.HasNextStaticField()) {
1753 it.Next();
1754 }
1755 while (it.HasNextInstanceField()) {
1756 it.Next();
1757 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001758 bool has_oat_class;
1759 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1760 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07001761 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001762 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001763 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001764 if (!method->IsStatic()) {
1765 // Only update static methods.
1766 continue;
Ian Rogers19846512012-02-24 11:42:47 -08001767 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001768 const void* quick_code = nullptr;
1769 if (has_oat_class) {
1770 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001771 quick_code = oat_method.GetQuickCode();
1772 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001773 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001774 if (enter_interpreter) {
1775 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07001776 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001777 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001778 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08001779 } else {
1780 quick_code = GetQuickToInterpreterBridge();
1781 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001782 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001783 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08001784 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001785 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08001786}
1787
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001788void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07001789 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001790 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001791 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001792 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001793 // The following code only applies to a non-compiler runtime.
1794 return;
1795 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001796 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001797 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001798 if (oat_class != nullptr) {
1799 // Every kind of method should at least get an invoke stub from the oat_method.
1800 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001801 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001802 oat_method.LinkMethod(method.Get());
1803 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001804
Jeff Hao16743632013-05-08 10:59:04 -07001805 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001806 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08001807 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001808 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001809 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001810 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07001811 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001812 }
1813
Brian Carlstrom92827a52011-10-10 15:50:01 -07001814 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001815 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001816 return;
1817 }
Ian Rogers19846512012-02-24 11:42:47 -08001818
1819 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001820 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001821 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
1822 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001823 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001824 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001825 if (!method->IsNative()) {
1826 // Set entry point from compiled code if there's no code or in interpreter only mode.
1827 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001828 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001829 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001830 }
Ian Rogers0d6de042012-02-29 08:50:26 -08001831 }
jeffhao26c0a1a2012-01-17 16:28:33 -08001832
Ian Rogers62d6c772013-02-27 08:32:07 -08001833 if (method->IsNative()) {
1834 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001835 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07001836
1837 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001838 // We have a native method here without code. Then it should have either the generic JNI
1839 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
1840 // TODO: this doesn't handle all the cases where trampolines may be installed.
1841 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1842 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07001843 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001844 }
1845}
1846
Fred Shih37f05ef2014-07-16 18:38:08 -07001847
Fred Shih37f05ef2014-07-16 18:38:08 -07001848
Ian Rogers7b078e82014-09-10 14:44:24 -07001849void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07001850 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001851 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001852 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001853 CHECK(klass.Get() != nullptr);
1854 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001855 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001856 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001857 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001858
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001859 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07001860 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07001861 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001862 klass->SetAccessFlags(access_flags);
1863 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001864 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001865 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001866
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001867 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001868 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08001869 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001870
Ian Rogers13735952014-10-08 12:43:28 -07001871 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001872 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001873 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001874 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001875
Ian Rogers97b52f82014-08-14 11:34:07 -07001876
1877 bool has_oat_class = false;
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001878 if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001879 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1880 &has_oat_class);
1881 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001882 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07001883 }
1884 }
1885 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001886 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001887 }
1888}
1889
Ian Rogers7b078e82014-09-10 14:44:24 -07001890void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07001891 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001892 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001893 const OatFile::OatClass* oat_class) {
1894 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07001895 ClassDataItemIterator it(dex_file, class_data);
1896 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001897 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001898 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001899 CHECK(self->IsExceptionPending()); // OOME.
1900 return;
1901 }
1902 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07001903 }
1904 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001905 mirror::ObjectArray<mirror::ArtField>* fields =
1906 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001907 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001908 CHECK(self->IsExceptionPending()); // OOME.
1909 return;
1910 }
1911 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07001912 }
1913 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001914 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001915 StackHandleScope<1> hs(self);
1916 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001917 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001918 CHECK(self->IsExceptionPending()); // OOME.
1919 return;
1920 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001921 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07001922 LoadField(dex_file, it, klass, sfield);
1923 }
1924 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001925 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001926 StackHandleScope<1> hs(self);
1927 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001928 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001929 CHECK(self->IsExceptionPending()); // OOME.
1930 return;
1931 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001932 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07001933 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001934 }
1935
Ian Rogers0571d352011-11-03 19:51:38 -07001936 // Load methods.
1937 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001938 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07001939 mirror::ObjectArray<mirror::ArtMethod>* directs =
1940 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001941 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001942 CHECK(self->IsExceptionPending()); // OOME.
1943 return;
1944 }
1945 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001946 }
Ian Rogers0571d352011-11-03 19:51:38 -07001947 if (it.NumVirtualMethods() != 0) {
1948 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07001949 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
1950 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001951 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001952 CHECK(self->IsExceptionPending()); // OOME.
1953 return;
1954 }
1955 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001956 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001957 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07001958 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
1959 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001960 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001961 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001962 StackHandleScope<1> hs(self);
1963 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001964 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001965 CHECK(self->IsExceptionPending()); // OOME.
1966 return;
1967 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001968 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001969 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07001970 uint32_t it_method_index = it.GetMemberIndex();
1971 if (last_dex_method_index == it_method_index) {
1972 // duplicate case
1973 method->SetMethodIndex(last_class_def_method_index);
1974 } else {
1975 method->SetMethodIndex(class_def_method_index);
1976 last_dex_method_index = it_method_index;
1977 last_class_def_method_index = class_def_method_index;
1978 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001979 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001980 }
1981 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001982 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001983 StackHandleScope<1> hs(self);
1984 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001985 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001986 CHECK(self->IsExceptionPending()); // OOME.
1987 return;
1988 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001989 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08001990 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001991 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001992 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001993 }
1994 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001995}
1996
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001997void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001998 Handle<mirror::Class> klass,
1999 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002000 uint32_t field_idx = it.GetMemberIndex();
2001 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002002 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002003 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002004}
2005
Brian Carlstromea46f952013-07-30 01:26:50 -07002006mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002007 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002008 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002009 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002010 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002011 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002012
Brian Carlstromea46f952013-07-30 01:26:50 -07002013 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002014 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002015 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002016 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002017 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002018 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002019
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002020 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002021 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002022 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002023 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002024
Ian Rogers19846512012-02-24 11:42:47 -08002025 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002026 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002027
Andreas Gampe51829322014-08-25 15:05:04 -07002028 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002029
Ian Rogersdfb325e2013-10-30 01:00:44 -07002030 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002031 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002032 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2033 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002034 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002035 klass->SetFinalizable();
2036 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002037 std::string temp;
2038 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002039 // The Enum class declares a "final" finalize() method to prevent subclasses from
2040 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2041 // subclasses, so we exclude it here.
2042 // We also want to avoid setting the flag on Object, where we know that finalize() is
2043 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002044 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2045 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002046 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002047 }
2048 }
2049 }
2050 } else if (method_name[0] == '<') {
2051 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002052 bool is_init = (strcmp("<init>", method_name) == 0);
2053 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002054 if (UNLIKELY(!is_init && !is_clinit)) {
2055 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2056 } else {
2057 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2058 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002059 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002060 access_flags |= kAccConstructor;
2061 }
2062 }
2063 }
2064 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002065
Mathieu Chartier66f19252012-09-18 08:57:04 -07002066 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002067}
2068
Ian Rogers7b078e82014-09-10 14:44:24 -07002069void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002070 StackHandleScope<1> hs(self);
2071 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002072 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2073 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002074 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002075}
2076
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002077void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002078 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002079 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002080 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002081 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002082}
2083
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002084bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002085 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002086 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002087 mirror::DexCache* dex_cache = GetDexCache(i);
2088 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002089 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002090 }
2091 }
2092 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002093}
2094
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002095bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002096 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002097 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002098}
2099
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002100void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002101 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002102 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002103 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002104 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2105 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002106 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002107 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002108 if (log_new_dex_caches_roots_) {
2109 // TODO: This is not safe if we can remove dex caches.
2110 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2111 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002112}
2113
Brian Carlstromaded5f72011-10-07 17:15:04 -07002114void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002115 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002116 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002117 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002118 if (IsDexFileRegisteredLocked(dex_file)) {
2119 return;
2120 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002121 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002122 // Don't alloc while holding the lock, since allocation may need to
2123 // suspend all threads and another thread may need the dex_lock_ to
2124 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002125 StackHandleScope<1> hs(self);
2126 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002127 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2128 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002129 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002130 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002131 if (IsDexFileRegisteredLocked(dex_file)) {
2132 return;
2133 }
2134 RegisterDexFileLocked(dex_file, dex_cache);
2135 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002136}
2137
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002138void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002139 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002140 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002141 RegisterDexFileLocked(dex_file, dex_cache);
2142}
2143
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002144mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002145 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002146 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002147 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002148 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002149 if (dex_cache->GetDexFile() == &dex_file) {
2150 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002151 }
2152 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002153 // Search matching by location name.
2154 std::string location(dex_file.GetLocation());
2155 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002156 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002157 if (dex_cache->GetDexFile()->GetLocation() == location) {
2158 return dex_cache;
2159 }
2160 }
2161 // Failure, dump diagnostic and abort.
2162 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002163 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002164 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2165 }
2166 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002167 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002168}
2169
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002170void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002171 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08002172 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002173 mirror::DexCache* dex_cache = GetDexCache(i);
2174 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08002175 }
2176}
2177
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002178mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002179 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002180 if (UNLIKELY(klass == nullptr)) {
2181 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002182 }
2183 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002184}
2185
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002186mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2187 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002188 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07002189 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002190 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002191 StackHandleScope<1> hs(self);
2192 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002193 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002194 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
2195 h_class->SetPrimitiveType(type);
2196 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002197 const char* descriptor = Primitive::Descriptor(type);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002198 mirror::Class* existing = InsertClass(descriptor, h_class.Get(),
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002199 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002200 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002201 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07002202}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002203
Brian Carlstrombe977852011-07-19 14:54:54 -07002204// Create an array class (i.e. the class object for the array, not the
2205// array itself). "descriptor" looks like "[C" or "[[[[B" or
2206// "[Ljava/lang/String;".
2207//
2208// If "descriptor" refers to an array of primitives, look up the
2209// primitive type's internally-generated class object.
2210//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002211// "class_loader" is the class loader of the class that's referring to
2212// us. It's used to ensure that we're looking for the element type in
2213// the right context. It does NOT become the class loader for the
2214// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002215//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002216// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002217mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002218 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002219 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002220 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002221 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002222 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
2223 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002224 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002225 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002226 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002227 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
2228 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002229 if (component_type.Get() == nullptr) {
2230 DCHECK(self->IsExceptionPending());
2231 return nullptr;
2232 } else {
2233 self->ClearException();
2234 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002235 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002236 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2237 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2238 return nullptr;
2239 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002240 // See if the component type is already loaded. Array classes are
2241 // always associated with the class loader of their underlying
2242 // element type -- an array of Strings goes with the loader for
2243 // java/lang/String -- so we need to look for it there. (The
2244 // caller should have checked for the existence of the class
2245 // before calling here, but they did so with *their* class loader,
2246 // not the component type's loader.)
2247 //
2248 // If we find it, the caller adds "loader" to the class' initiating
2249 // loader list, which should prevent us from going through this again.
2250 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002251 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002252 // are the same, because our caller (FindClass) just did the
2253 // lookup. (Even if we get this wrong we still have correct behavior,
2254 // because we effectively do this lookup again when we add the new
2255 // class to the hash table --- necessary because of possible races with
2256 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002257 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002258 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002259 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002260 return new_class;
2261 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002262 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002263
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002264 // Fill out the fields in the Class.
2265 //
2266 // It is possible to execute some methods against arrays, because
2267 // all arrays are subclasses of java_lang_Object_, so we need to set
2268 // up a vtable. We can just point at the one in java_lang_Object_.
2269 //
2270 // Array classes are simple enough that we don't need to do a full
2271 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002272 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002273 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002274 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002275 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002276 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002277 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002278 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002279 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002280 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002281 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002282 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002283 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002284 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002285 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002286 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002287 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002288 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002289 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002290 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002291 }
2292 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002293 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002294 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002295 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002296 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002297 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002298 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002299 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002300 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002301 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002302 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002303 new_class->SetSuperClass(java_lang_Object);
2304 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002305 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002306 new_class->SetClassLoader(component_type->GetClassLoader());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002307 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002308 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002309 StackHandleScope<mirror::Class::kImtSize> hs2(self,
2310 Runtime::Current()->GetImtUnimplementedMethod());
2311 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002312 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002313 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002314 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002315 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002316
2317
2318 // All arrays have java/lang/Cloneable and java/io/Serializable as
2319 // interfaces. We need to set that up here, so that stuff like
2320 // "instanceof" works right.
2321 //
2322 // Note: The GC could run during the call to FindSystemClass,
2323 // so we need to make sure the class object is GC-valid while we're in
2324 // there. Do this by clearing the interface list so the GC will just
2325 // think that the entries are null.
2326
2327
2328 // Use the single, global copies of "interfaces" and "iftable"
2329 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002330 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002331 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002332 CHECK(array_iftable != nullptr);
2333 new_class->SetIfTable(array_iftable);
2334 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002335
Elliott Hughes00626c22013-06-14 15:04:14 -07002336 // Inherit access flags from the component type.
2337 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2338 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2339 access_flags &= kAccJavaFlagsMask;
2340 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002341 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002342 access_flags |= kAccAbstract | kAccFinal;
2343 access_flags &= ~kAccInterface;
2344
2345 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002346
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002347 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002348 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002349 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002350 }
2351 // Another thread must have loaded the class after we
2352 // started but before we finished. Abandon what we've
2353 // done.
2354 //
2355 // (Yes, this happens.)
2356
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002357 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002358}
2359
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002360mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002361 switch (type) {
2362 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002363 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002364 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002365 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002366 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002367 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002368 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002369 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002370 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002371 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002372 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002373 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002374 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002375 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002376 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002377 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002378 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002379 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002380 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002381 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002382 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002383 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002384 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002385 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002386}
2387
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002388mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2389 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002390 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002391 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002392 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002393 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08002394 source += " from ";
2395 source += dex_cache->GetLocation()->ToModifiedUtf8();
2396 }
2397 LOG(INFO) << "Loaded class " << descriptor << source;
2398 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002399 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002400 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002401 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002402 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002403 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002404 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002405 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002406 // Check a class loaded with the system class loader matches one in the image if the class
2407 // is in the image.
2408 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002409 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002410 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002411 }
2412 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002413 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002414 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002415 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002416 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002417 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002418 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002419}
2420
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002421mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
2422 size_t hash) {
2423 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002424 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
2425 hash);
2426 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002427 CHECK(klass->IsProxyClass());
2428 return nullptr;
2429 }
2430
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002431 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002432 CHECK_NE(existing, klass) << descriptor;
2433 CHECK(!existing->IsResolved()) << descriptor;
2434 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
2435
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002436 CHECK(!klass->IsTemp()) << descriptor;
2437 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
2438 dex_cache_image_class_lookup_required_) {
2439 // Check a class loaded with the system class loader matches one in the image if the class
2440 // is in the image.
2441 existing = LookupClassFromImage(descriptor);
2442 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002443 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002444 }
2445 }
2446 VerifyObject(klass);
2447
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002448 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002449 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002450 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002451 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002452 }
2453
2454 return existing;
2455}
2456
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002457bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002458 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002459 auto pair = std::make_pair(descriptor, class_loader);
2460 auto it = class_table_.Find(pair);
2461 if (it != class_table_.end()) {
2462 class_table_.Erase(it);
2463 return true;
2464 }
2465 it = pre_zygote_class_table_.Find(pair);
2466 if (it != pre_zygote_class_table_.end()) {
2467 pre_zygote_class_table_.Erase(it);
2468 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08002469 }
2470 return false;
2471}
2472
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002473mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002474 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002475 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002476 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002477 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002478 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002479 return result;
2480 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07002481 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002482 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
2483 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002484 } else {
2485 // Lookup failed but need to search dex_caches_.
2486 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002487 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002488 InsertClass(descriptor, result, hash);
2489 } else {
2490 // Searching the image dex files/caches failed, we don't want to get into this situation
2491 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2492 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07002493 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002494 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2495 MoveImageClassesToClassTable();
2496 }
2497 }
2498 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002499 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002500}
2501
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002502mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002503 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002504 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002505 auto descriptor_pair = std::make_pair(descriptor, class_loader);
2506 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
2507 if (it == pre_zygote_class_table_.end()) {
2508 it = class_table_.FindWithHash(descriptor_pair, hash);
2509 if (it == class_table_.end()) {
2510 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07002511 }
2512 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002513 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002514}
2515
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002516static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
2517 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2518 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002519 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002520 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2521 return root->AsObjectArray<mirror::DexCache>();
2522}
2523
2524void ClassLinker::MoveImageClassesToClassTable() {
2525 Thread* self = Thread::Current();
2526 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2527 if (!dex_cache_image_class_lookup_required_) {
2528 return; // All dex cache classes are already in the class table.
2529 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002530 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002531 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002532 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002533 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2534 mirror::DexCache* dex_cache = dex_caches->Get(i);
2535 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
2536 for (int32_t j = 0; j < types->GetLength(); j++) {
2537 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002538 if (klass != nullptr) {
2539 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002540 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002541 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002542 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
2543 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002544 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002545 << PrettyClassAndClassLoader(klass);
2546 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002547 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002548 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002549 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002550 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002551 }
2552 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002553 }
2554 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002555 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002556}
2557
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002558void ClassLinker::MoveClassTableToPreZygote() {
2559 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2560 DCHECK(pre_zygote_class_table_.Empty());
2561 pre_zygote_class_table_ = std::move(class_table_);
2562 class_table_.Clear();
2563}
2564
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002565mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002566 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002567 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2568 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
2569 mirror::DexCache* dex_cache = dex_caches->Get(i);
2570 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00002571 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002572 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002573 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002574 const DexFile::TypeId* type_id =
2575 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002576 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002577 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
2578 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002579 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002580 return klass;
2581 }
2582 }
2583 }
2584 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002585 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002586}
2587
2588void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
2589 result.clear();
2590 if (dex_cache_image_class_lookup_required_) {
2591 MoveImageClassesToClassTable();
2592 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002593 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2594 while (true) {
2595 auto it = class_table_.Find(descriptor);
2596 if (it == class_table_.end()) {
2597 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002598 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002599 result.push_back(it->Read());
2600 class_table_.Erase(it);
2601 }
2602 for (mirror::Class* k : result) {
2603 class_table_.Insert(GcRoot<mirror::Class>(k));
2604 }
2605 size_t pre_zygote_start = result.size();
2606 // Now handle the pre zygote table.
2607 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
2608 // called from the debugger.
2609 while (true) {
2610 auto it = pre_zygote_class_table_.Find(descriptor);
2611 if (it == pre_zygote_class_table_.end()) {
2612 break;
2613 }
2614 result.push_back(it->Read());
2615 pre_zygote_class_table_.Erase(it);
2616 }
2617 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
2618 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002619 }
2620}
2621
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002622void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002623 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002624 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08002625
Ian Rogers9ffb0392012-09-10 11:56:50 -07002626 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002627 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07002628 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07002629 return;
2630 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002631 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002632 return;
2633 }
jeffhao98eacac2011-09-14 16:11:53 -07002634
Ian Rogers9ffb0392012-09-10 11:56:50 -07002635 // The class might already be erroneous, for example at compile time if we attempted to verify
2636 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002637 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002638 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002639 return;
2640 }
2641
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002642 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002643 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002644 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002645 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002646 << PrettyClass(klass.Get());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002647 CHECK(!Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002648 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002649 }
jeffhao98eacac2011-09-14 16:11:53 -07002650
Jeff Hao4a200f52014-04-01 14:58:49 -07002651 // Skip verification if disabled.
2652 if (!Runtime::Current()->IsVerificationEnabled()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002653 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07002654 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07002655 return;
2656 }
2657
Ian Rogers9ffb0392012-09-10 11:56:50 -07002658 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002659 StackHandleScope<2> hs(self);
2660 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002661 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07002662 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002663 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002664
2665 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002666 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002667 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002668 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07002669 std::string error_msg(
2670 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
2671 PrettyDescriptor(klass.Get()).c_str(),
2672 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08002673 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002674 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002675 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002676 self->ClearException();
2677 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002678 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
2679 if (cause.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002680 self->GetException()->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002681 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08002682 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002683 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00002684 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
2685 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002686 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002687 return;
2688 }
2689 }
2690
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002691 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07002692 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002693 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002694 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002695 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002696 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002697 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002698 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002699 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
2700 PrettyDescriptor(klass.Get()).c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002701 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07002702 return;
2703 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002704 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08002705 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07002706 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002707 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002708 Runtime::Current()->IsAotCompiler(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002709 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002710 }
2711 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07002712 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002713 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07002714 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2715 << " because: " << error_msg;
2716 }
Ian Rogers1f539342012-10-03 21:09:42 -07002717 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002718 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002719 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002720 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002721 // Even though there were no verifier failures we need to respect whether the super-class
2722 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002723 if (super.Get() == nullptr || super->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002724 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002725 } else {
2726 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002727 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002728 // Pretend a soft failure occured so that we don't consider the class verified below.
2729 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002730 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002731 } else {
2732 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
2733 // Soft failures at compile time should be retried at runtime. Soft
2734 // failures at runtime will be handled by slow paths in the generated
2735 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002736 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002737 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002738 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002739 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002740 // As this is a fake verified status, make sure the methods are _not_ marked preverified
2741 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07002742 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002743 }
2744 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07002745 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002746 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08002747 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2748 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002749 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002750 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002751 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002752 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002753 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002754 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002755 // Let the interpreter know it by setting the kAccPreverified flag onto each
2756 // method.
2757 // Note: we're going here during compilation and at runtime. When we set the
2758 // kAccPreverified flag when compiling image classes, the flag is recorded
2759 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07002760 EnsurePreverifiedMethods(klass);
2761 }
2762}
2763
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002764void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002765 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002766 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07002767 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002768 }
jeffhao98eacac2011-09-14 16:11:53 -07002769}
2770
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002771bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
2772 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002773 // If we're compiling, we can only verify the class using the oat file if
2774 // we are not compiling the image or if the class we're verifying is not part of
2775 // the app. In other words, we will only check for preverification of bootclasspath
2776 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002777 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002778 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002779 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002780 return false;
2781 }
2782 // We are compiling an app (not the image).
2783
2784 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002785 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002786 return false;
2787 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002788 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002789
Richard Uhler07b3c232015-03-31 15:57:54 -07002790 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002791 // In case we run without an image there won't be a backing oat file.
2792 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07002793 return false;
2794 }
2795
Andreas Gampe76bd8802014-12-10 16:43:58 -08002796 // We may be running with a preopted oat file but without image. In this case,
2797 // we don't skip verification of preverified classes to ensure we initialize
2798 // dex caches with all types resolved during verification.
2799 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
2800 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
2801 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
2802 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002803 if (!Runtime::Current()->IsAotCompiler() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08002804 !Runtime::Current()->GetHeap()->HasImageSpace() &&
2805 klass->GetClassLoader() != nullptr) {
2806 return false;
2807 }
2808
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002809 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002810 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002811 if (oat_file_class_status == mirror::Class::kStatusVerified ||
2812 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002813 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002814 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002815 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07002816 // Compile time verification failed with a soft error. Compile time verification can fail
2817 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08002818 // class ... {
2819 // Foo x;
2820 // .... () {
2821 // if (...) {
2822 // v1 gets assigned a type of resolved class Foo
2823 // } else {
2824 // v1 gets assigned a type of unresolved class Bar
2825 // }
2826 // iput x = v1
2827 // } }
2828 // when we merge v1 following the if-the-else it results in Conflict
2829 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2830 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2831 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2832 // at compile time).
2833 return false;
2834 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002835 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07002836 // Compile time verification failed with a hard error. This is caused by invalid instructions
2837 // in the class. These errors are unrecoverable.
2838 return false;
2839 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002840 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002841 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2842 // not loading the class.
2843 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2844 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002845 return false;
2846 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002847 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002848 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002849 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07002850 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08002851 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002852}
2853
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002854void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002855 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002856 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2857 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2858 }
2859 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2860 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2861 }
2862}
2863
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002864void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07002865 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002866 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2867 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002868 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002869 return; // native or abstract method
2870 }
2871 if (code_item->tries_size_ == 0) {
2872 return; // nothing to process
2873 }
Ian Rogers13735952014-10-08 12:43:28 -07002874 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002875 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2876 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2877 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2878 CatchHandlerIterator iterator(handlers_ptr);
2879 for (; iterator.HasNext(); iterator.Next()) {
2880 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2881 // unresolved exception types will be ignored by exception delivery
2882 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002883 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002884 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002885 DCHECK(Thread::Current()->IsExceptionPending());
2886 Thread::Current()->ClearException();
2887 }
2888 }
2889 }
2890 handlers_ptr = iterator.EndDataPointer();
2891 }
2892}
2893
Brian Carlstromea46f952013-07-30 01:26:50 -07002894static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002895static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
2896 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08002897
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07002898mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07002899 jobjectArray interfaces, jobject loader,
2900 jobjectArray methods, jobjectArray throws) {
2901 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002902 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002903 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002904 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002905 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002906 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002907 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002908 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002909 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002910 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07002911 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
2912 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002913 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08002914 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002915 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002916 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002917 klass->SetDexCache(proxy_class->GetDexCache());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002918 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08002919
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002920 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07002921 {
2922 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002923 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002924 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002925 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002926 }
2927 klass->SetSFields(sfields);
2928 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002929 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
2930 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002931 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
2932 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002933 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002934 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002935 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002936 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002937 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002938 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002939 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
2940 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002941 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
2942 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002943 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002944 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002945 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002946 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002947 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002948 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002949 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002950
Ian Rogers466bb252011-10-14 03:29:56 -07002951 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07002952 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002953 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002954 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002955 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002956 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002957 }
2958 klass->SetDirectMethods(directs);
2959 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002960 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002961 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002962 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002963 }
2964 klass->SetDirectMethod(0, constructor);
2965 }
Jesse Wilson95caa792011-10-12 18:14:17 -04002966
Mathieu Chartier590fee92013-09-13 13:46:47 -07002967 // Create virtual method using specified prototypes.
2968 size_t num_virtual_methods =
2969 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07002970 {
Brian Carlstromf3632832014-05-20 15:36:53 -07002971 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
2972 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002973 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002974 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002975 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002976 }
2977 klass->SetVirtualMethods(virtuals);
2978 }
Jesse Wilson95caa792011-10-12 18:14:17 -04002979 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002980 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002981 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
2982 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002983 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07002984 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002985 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002986 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002987 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002988 }
2989 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04002990 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002991
2992 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002993 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08002994 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08002995
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002996 std::string descriptor(GetDescriptorForProxy(klass.Get()));
2997 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07002998 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002999 // Must hold lock on object when resolved.
3000 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003001 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003002 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003003 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003004 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003005 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003006 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003007 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003008 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003009
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003010 CHECK(klass->IsRetired());
3011 CHECK_NE(klass.Get(), new_class);
3012 klass.Assign(new_class);
3013
3014 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003015 interfaces_sfield->SetObject<false>(klass.Get(),
3016 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003017 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003018 throws_sfield->SetObject<false>(klass.Get(),
3019 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003020
3021 {
3022 // Lock on klass is released. Lock new class object.
3023 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003024 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003025 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003026
3027 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003028 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003029 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003030 CheckProxyConstructor(klass->GetDirectMethod(0));
3031 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003032 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003033 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3034 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003035 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3036 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003037 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003038 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003039
Mathieu Chartier590fee92013-09-13 13:46:47 -07003040 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003041 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003042 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003043 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3044
3045 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003046 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003047 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003048
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003049 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003050 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003051 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003052 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003053 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003054 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3055 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003056 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003057 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003058}
3059
Ian Rogersef7d42f2014-01-06 12:55:46 -08003060std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003061 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003062 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003063 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003064 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3065}
3066
Ian Rogersef7d42f2014-01-06 12:55:46 -08003067mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3068 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003069 DCHECK(proxy_class->IsProxyClass());
3070 DCHECK(proxy_method->IsProxyMethod());
3071 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003072 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003073 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003074 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003075 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003076 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003077 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003078 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003079 break;
3080 }
3081 }
3082 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003083 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003084 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003085 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003086 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003087 return resolved_method;
3088}
3089
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003090
Brian Carlstromea46f952013-07-30 01:26:50 -07003091mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003092 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003093 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003094 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003095 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003096 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003097 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3098 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003099 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3100 // constructor method.
3101 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3102 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003103 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3104 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003105 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3106 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003107 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003108 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003109 }
Ian Rogers466bb252011-10-14 03:29:56 -07003110 // Make this constructor public and fix the class to be our Proxy version
3111 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003112 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003113 return constructor;
3114}
3115
Brian Carlstromea46f952013-07-30 01:26:50 -07003116static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003117 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003118 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003119 CHECK_STREQ(constructor->GetName(), "<init>");
3120 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3121 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003122 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003123}
3124
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003125mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003126 Handle<mirror::Class> klass,
3127 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003128 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3129 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003130 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003131 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003132 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003133 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003134 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003135 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003136 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003137 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003138 }
Ian Rogers466bb252011-10-14 03:29:56 -07003139
3140 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3141 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003142 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003143 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003144
Ian Rogers466bb252011-10-14 03:29:56 -07003145 // At runtime the method looks like a reference and argument saving method, clone the code
3146 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003147 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003148 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003149
Ian Rogersc2b44472011-12-14 21:17:17 -08003150 return method;
3151}
Jesse Wilson95caa792011-10-12 18:14:17 -04003152
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003153static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3154 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003155 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003156 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003157 CHECK(!prototype->IsFinal());
3158 CHECK(method->IsFinal());
3159 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003160
3161 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3162 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07003163 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
3164 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08003165 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3166
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003167 CHECK_STREQ(method->GetName(), prototype->GetName());
3168 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003169 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07003170 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04003171}
3172
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003173static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3174 bool can_init_parents)
3175 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003176 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003177 return true;
3178 }
3179 if (!can_init_statics) {
3180 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07003181 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003182 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003183 return false;
3184 }
3185 // Check if there are encoded static values needing initialization.
3186 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003187 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003188 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003189 if (dex_class_def->static_values_off_ != 0) {
3190 return false;
3191 }
3192 }
3193 }
3194 if (!klass->IsInterface() && klass->HasSuperClass()) {
3195 mirror::Class* super_class = klass->GetSuperClass();
3196 if (!can_init_parents && !super_class->IsInitialized()) {
3197 return false;
3198 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003199 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003200 return false;
3201 }
3202 }
3203 }
3204 return true;
3205}
3206
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003207bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07003208 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003209 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3210
3211 // Are we already initialized and therefore done?
3212 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3213 // an initialized class will never change its state.
3214 if (klass->IsInitialized()) {
3215 return true;
3216 }
3217
3218 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003219 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003220 return false;
3221 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003222
Ian Rogers7b078e82014-09-10 14:44:24 -07003223 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003224 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003225 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003226 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003227
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003228 // Re-check under the lock in case another thread initialized ahead of us.
3229 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003230 return true;
3231 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003232
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003233 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003234 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003235 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003236 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003237 return false;
3238 }
3239
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003240 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003241
3242 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003243 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003244 if (!klass->IsVerified()) {
3245 // We failed to verify, expect either the klass to be erroneous or verification failed at
3246 // compile time.
3247 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003248 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003249 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003250 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003251 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003252 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003253 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003254 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07003255 } else {
3256 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003257 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003258 }
3259
Brian Carlstromd1422f82011-09-28 11:37:09 -07003260 // If the class is kStatusInitializing, either this thread is
3261 // initializing higher up the stack or another thread has beat us
3262 // to initializing and we need to wait. Either way, this
3263 // invocation of InitializeClass will not be responsible for
3264 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003265 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07003266 // Could have got an exception during verification.
3267 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003268 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003269 return false;
3270 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003271 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003272 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003273 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003274 return true;
3275 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003276 // No. That's fine. Wait for another thread to finish initializing.
3277 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003278 }
3279
3280 if (!ValidateSuperClassDescriptors(klass)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003281 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003282 return false;
3283 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003284 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003285
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003286 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003287
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003288 // From here out other threads may observe that we're initializing and so changes of state
3289 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003290 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003291 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003292
3293 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003294 }
3295
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003296 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003297 if (!klass->IsInterface() && klass->HasSuperClass()) {
3298 mirror::Class* super_class = klass->GetSuperClass();
3299 if (!super_class->IsInitialized()) {
3300 CHECK(!super_class->IsInterface());
3301 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003302 StackHandleScope<1> hs(self);
3303 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07003304 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003305 if (!super_initialized) {
3306 // The super class was verified ahead of entering initializing, we should only be here if
3307 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003308 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003309 << "Super class initialization failed for "
3310 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003311 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003312 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003313 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003314 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003315 // Initialization failed because the super-class is erroneous.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003316 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003317 return false;
3318 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003319 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003320 }
3321
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003322 const size_t num_static_fields = klass->NumStaticFields();
3323 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003324 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003325 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003326 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07003327 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003328 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003329 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003330
3331 // Eagerly fill in static fields so that the we don't have to do as many expensive
3332 // Class::FindStaticField in ResolveField.
3333 for (size_t i = 0; i < num_static_fields; ++i) {
3334 mirror::ArtField* field = klass->GetStaticField(i);
3335 const uint32_t field_idx = field->GetDexFieldIndex();
3336 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
3337 if (resolved_field == nullptr) {
3338 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07003339 } else {
3340 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003341 }
3342 }
3343
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003344 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
3345 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07003346 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003347 ClassDataItemIterator field_it(dex_file, class_data);
3348 if (value_it.HasNext()) {
3349 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003350 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003351 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003352 StackHandleScope<1> hs2(self);
3353 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003354 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003355 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003356 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003357 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003358 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003359 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003360 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003361 }
3362 }
3363 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003364
Ian Rogersd91d6d62013-09-25 20:26:14 -07003365 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003366 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003367 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003368 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003369 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003370 }
3371
Ian Rogers7b078e82014-09-10 14:44:24 -07003372 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003373 uint64_t t1 = NanoTime();
3374
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003375 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003376 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003377 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003378
3379 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003380 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003381 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003382 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003383 } else if (Runtime::Current()->IsTransactionAborted()) {
3384 // The exception thrown when the transaction aborted has been caught and cleared
3385 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01003386 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
3387 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02003388 Runtime::Current()->ThrowTransactionAbortError(self);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003389 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003390 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003391 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003392 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3393 RuntimeStats* thread_stats = self->GetStats();
3394 ++global_stats->class_init_count;
3395 ++thread_stats->class_init_count;
3396 global_stats->class_init_time_ns += (t1 - t0);
3397 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003398 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003399 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003400 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003401 std::string temp;
3402 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003403 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003404 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003405 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003406 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003407 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003408 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003409 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003410}
3411
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003412bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003413 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003414 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003415 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003416 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003417 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08003418 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003419
3420 // When we wake up, repeat the test for init-in-progress. If
3421 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07003422 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003423 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003424 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003425 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003426 return false;
3427 }
3428 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003429 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003430 continue;
3431 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003432 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
3433 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003434 // Compile time initialization failed.
3435 return false;
3436 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003437 if (klass->IsErroneous()) {
3438 // The caller wants an exception, but it was thrown in a
3439 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003440 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003441 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003442 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003443 return false;
3444 }
3445 if (klass->IsInitialized()) {
3446 return true;
3447 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003448 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003449 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003450 }
Ian Rogers07140832014-09-30 15:43:59 -07003451 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003452}
3453
Ian Rogersb5fb2072014-12-02 17:22:02 -08003454static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
3455 Handle<mirror::ArtMethod> method1,
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003456 Handle<mirror::ArtMethod> method2,
3457 std::string* error_msg)
Ian Rogersb5fb2072014-12-02 17:22:02 -08003458 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3459 {
3460 StackHandleScope<1> hs(self);
3461 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
Vladimir Marko862f43c2015-02-10 18:22:57 +00003462 mirror::Class* other_return_type = method2->GetReturnType();
3463 // NOTE: return_type.Get() must be sequenced after method2->GetReturnType().
3464 if (UNLIKELY(other_return_type != return_type.Get())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003465 *error_msg = StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
3466 PrettyClassAndClassLoader(return_type.Get()).c_str(),
3467 return_type.Get(),
3468 PrettyClassAndClassLoader(other_return_type).c_str(),
3469 other_return_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003470 return false;
3471 }
3472 }
3473 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
3474 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
3475 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003476 if (types2 != nullptr && types2->Size() != 0) {
3477 *error_msg = StringPrintf("Type list mismatch with %s",
3478 PrettyMethod(method2.Get(), true).c_str());
3479 return false;
3480 }
3481 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003482 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003483 if (types1->Size() != 0) {
3484 *error_msg = StringPrintf("Type list mismatch with %s",
3485 PrettyMethod(method2.Get(), true).c_str());
3486 return false;
3487 }
3488 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003489 }
3490 uint32_t num_types = types1->Size();
3491 if (UNLIKELY(num_types != types2->Size())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003492 *error_msg = StringPrintf("Type list mismatch with %s",
3493 PrettyMethod(method2.Get(), true).c_str());
Ian Rogersb5fb2072014-12-02 17:22:02 -08003494 return false;
3495 }
3496 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00003497 StackHandleScope<1> hs(self);
3498 Handle<mirror::Class> param_type(hs.NewHandle(
3499 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true)));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003500 mirror::Class* other_param_type =
3501 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
Vladimir Marko862f43c2015-02-10 18:22:57 +00003502 // NOTE: param_type.Get() must be sequenced after method2->GetClassFromTypeIndex(...).
3503 if (UNLIKELY(param_type.Get() != other_param_type)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003504 *error_msg = StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
3505 i,
3506 PrettyClassAndClassLoader(param_type.Get()).c_str(),
3507 param_type.Get(),
3508 PrettyClassAndClassLoader(other_param_type).c_str(),
3509 other_param_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003510 return false;
3511 }
3512 }
3513 return true;
3514}
3515
3516
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003517bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003518 if (klass->IsInterface()) {
3519 return true;
3520 }
Ian Rogers151f2212014-05-06 11:27:27 -07003521 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07003522 Thread* self = Thread::Current();
3523 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003524 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
3525 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003526 if (klass->HasSuperClass() &&
3527 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003528 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003529 h_m.Assign(klass->GetVTableEntry(i));
3530 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003531 if (h_m.Get() != super_h_m.Get()) {
3532 std::string error_msg;
3533 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3534 ThrowLinkageError(klass.Get(),
3535 "Class %s method %s resolves differently in superclass %s: %s",
3536 PrettyDescriptor(klass.Get()).c_str(),
3537 PrettyMethod(h_m.Get()).c_str(),
3538 PrettyDescriptor(klass->GetSuperClass()).c_str(),
3539 error_msg.c_str());
3540 return false;
3541 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003542 }
3543 }
3544 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003545 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07003546 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
3547 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
3548 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003549 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
3550 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003551 if (h_m.Get() != super_h_m.Get()) {
3552 std::string error_msg;
3553 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3554 ThrowLinkageError(klass.Get(),
3555 "Class %s method %s resolves differently in interface %s: %s",
3556 PrettyDescriptor(klass.Get()).c_str(),
3557 PrettyMethod(h_m.Get()).c_str(),
3558 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str(),
3559 error_msg.c_str());
3560 return false;
3561 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003562 }
3563 }
3564 }
3565 }
3566 return true;
3567}
3568
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003569bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
3570 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003571 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003572 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003573 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003574 return true;
3575 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003576 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003577 if (!success) {
3578 if (can_init_fields && can_init_parents) {
3579 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
3580 }
3581 } else {
3582 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08003583 }
3584 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003585}
3586
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003587void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
3588 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
3589 if (fields != nullptr) {
3590 for (int index = 0; index < fields->GetLength(); index ++) {
3591 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
3592 fields->Get(index)->SetDeclaringClass(new_class);
3593 }
3594 }
3595 }
3596
3597 fields = new_class->GetSFields();
3598 if (fields != nullptr) {
3599 for (int index = 0; index < fields->GetLength(); index ++) {
3600 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
3601 fields->Get(index)->SetDeclaringClass(new_class);
3602 }
3603 }
3604 }
3605
3606 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
3607 if (methods != nullptr) {
3608 for (int index = 0; index < methods->GetLength(); index ++) {
3609 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3610 methods->Get(index)->SetDeclaringClass(new_class);
3611 }
3612 }
3613 }
3614
3615 methods = new_class->GetVirtualMethods();
3616 if (methods != nullptr) {
3617 for (int index = 0; index < methods->GetLength(); index ++) {
3618 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3619 methods->Get(index)->SetDeclaringClass(new_class);
3620 }
3621 }
3622 }
3623}
3624
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003625bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
3626 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003627 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003628 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003629
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003630 if (!LinkSuperClass(klass)) {
3631 return false;
3632 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003633 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
3634 self, Runtime::Current()->GetImtUnimplementedMethod());
3635 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003636 return false;
3637 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003638 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003639 return false;
3640 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003641 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07003642 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003643 return false;
3644 }
3645 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003646 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003647
3648 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
3649 // We don't need to retire this class as it has no embedded tables or it was created the
3650 // correct size during class linker initialization.
3651 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
3652
3653 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003654 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003655 }
3656
3657 // This will notify waiters on klass that saw the not yet resolved
3658 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003659 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003660 *new_class = klass.Get();
3661 } else {
3662 CHECK(!klass->IsResolved());
3663 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003664 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003665 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003666 CHECK(self->IsExceptionPending()); // Expect an OOME.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003667 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003668 return false;
3669 }
3670
3671 CHECK_EQ((*new_class)->GetClassSize(), class_size);
3672 StackHandleScope<1> hs(self);
3673 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
3674 ObjectLock<mirror::Class> lock(self, new_class_h);
3675
3676 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
3677
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003678 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
3679 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003680 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003681
3682 // This will notify waiters on temp class that saw the not yet resolved class in the
3683 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003684 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003685
3686 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
3687 // This will notify waiters on new_class that saw the not yet resolved
3688 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003689 mirror::Class::SetStatus(new_class_h, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003690 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003691 return true;
3692}
3693
Andreas Gampefd9eb392014-11-06 16:52:58 -08003694static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
3695 size_t* virtual_methods,
3696 size_t* direct_methods,
3697 size_t* static_fields,
3698 size_t* instance_fields) {
3699 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
3700
3701 while (dex_data.HasNextStaticField()) {
3702 dex_data.Next();
3703 (*static_fields)++;
3704 }
3705 while (dex_data.HasNextInstanceField()) {
3706 dex_data.Next();
3707 (*instance_fields)++;
3708 }
3709 while (dex_data.HasNextDirectMethod()) {
3710 (*direct_methods)++;
3711 dex_data.Next();
3712 }
3713 while (dex_data.HasNextVirtualMethod()) {
3714 (*virtual_methods)++;
3715 dex_data.Next();
3716 }
3717 DCHECK(!dex_data.HasNext());
3718}
3719
3720static void DumpClass(std::ostream& os,
3721 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
3722 const char* suffix) {
3723 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
3724 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
3725 os << " Static fields:\n";
3726 while (dex_data.HasNextStaticField()) {
3727 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3728 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3729 dex_data.Next();
3730 }
3731 os << " Instance fields:\n";
3732 while (dex_data.HasNextInstanceField()) {
3733 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3734 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3735 dex_data.Next();
3736 }
3737 os << " Direct methods:\n";
3738 while (dex_data.HasNextDirectMethod()) {
3739 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3740 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3741 dex_data.Next();
3742 }
3743 os << " Virtual methods:\n";
3744 while (dex_data.HasNextVirtualMethod()) {
3745 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3746 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3747 dex_data.Next();
3748 }
3749}
3750
3751static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3752 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
3753 std::ostringstream os;
3754 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
3755 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
3756 return os.str();
3757}
3758
3759
3760// Very simple structural check on whether the classes match. Only compares the number of
3761// methods and fields.
3762static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3763 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
3764 std::string* error_msg) {
3765 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
3766 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
3767
3768 // Counters for current dex file.
3769 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
3770 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
3771 &dex_instance_fields1);
3772 // Counters for compile-time dex file.
3773 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
3774 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
3775 &dex_instance_fields2);
3776
3777 if (dex_virtual_methods1 != dex_virtual_methods2) {
3778 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3779 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
3780 dex_virtual_methods2, class_dump.c_str());
3781 return false;
3782 }
3783 if (dex_direct_methods1 != dex_direct_methods2) {
3784 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3785 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
3786 dex_direct_methods2, class_dump.c_str());
3787 return false;
3788 }
3789 if (dex_static_fields1 != dex_static_fields2) {
3790 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3791 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
3792 dex_static_fields2, class_dump.c_str());
3793 return false;
3794 }
3795 if (dex_instance_fields1 != dex_instance_fields2) {
3796 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3797 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
3798 dex_instance_fields2, class_dump.c_str());
3799 return false;
3800 }
3801
3802 return true;
3803}
3804
3805// Checks whether a the super-class changed from what we had at compile-time. This would
3806// invalidate quickening.
3807static bool CheckSuperClassChange(Handle<mirror::Class> klass,
3808 const DexFile& dex_file,
3809 const DexFile::ClassDef& class_def,
3810 mirror::Class* super_class)
3811 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3812 // Check for unexpected changes in the superclass.
3813 // Quick check 1) is the super_class class-loader the boot class loader? This always has
3814 // precedence.
3815 if (super_class->GetClassLoader() != nullptr &&
3816 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
3817 // which is implied by different dex cache.
3818 klass->GetDexCache() != super_class->GetDexCache()) {
3819 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
3820 // definition for the super-class, and (b) the files are in separate oat files. The oat files
3821 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
Richard Uhler07b3c232015-03-31 15:57:54 -07003822 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
3823 const OatFile* class_oat_file = nullptr;
3824 if (class_oat_dex_file != nullptr) {
3825 class_oat_file = class_oat_dex_file->GetOatFile();
3826 }
3827
Andreas Gampefd9eb392014-11-06 16:52:58 -08003828 if (class_oat_file != nullptr) {
Richard Uhler07b3c232015-03-31 15:57:54 -07003829 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
3830 const OatFile* loaded_super_oat_file = nullptr;
3831 if (loaded_super_oat_dex_file != nullptr) {
3832 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
3833 }
3834
Andreas Gampefd9eb392014-11-06 16:52:58 -08003835 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
3836 // Now check (a).
3837 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
3838 if (super_class_def != nullptr) {
3839 // Uh-oh, we found something. Do our check.
3840 std::string error_msg;
3841 if (!SimpleStructuralCheck(dex_file, *super_class_def,
3842 super_class->GetDexFile(), *super_class->GetClassDef(),
3843 &error_msg)) {
3844 // Print a warning to the log. This exception might be caught, e.g., as common in test
3845 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
3846 // only save the type of the exception.
3847 LOG(WARNING) << "Incompatible structural change detected: " <<
3848 StringPrintf(
3849 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3850 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3851 class_oat_file->GetLocation().c_str(),
3852 loaded_super_oat_file->GetLocation().c_str(),
3853 error_msg.c_str());
3854 ThrowIncompatibleClassChangeError(klass.Get(),
3855 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3856 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3857 class_oat_file->GetLocation().c_str(),
3858 loaded_super_oat_file->GetLocation().c_str(),
3859 error_msg.c_str());
3860 return false;
3861 }
3862 }
3863 }
3864 }
3865 }
3866 return true;
3867}
3868
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003869bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003870 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003871 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3872 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003873 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003874 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003875 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003876 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003877 return false;
3878 }
Ian Rogersbe125a92012-01-11 15:19:49 -08003879 // Verify
3880 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003881 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003882 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003883 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08003884 return false;
3885 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003886 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003887 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08003888
3889 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
3890 DCHECK(Thread::Current()->IsExceptionPending());
3891 return false;
3892 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003893 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003894 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003895 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003896 for (size_t i = 0; i < interfaces->Size(); i++) {
3897 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003898 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003899 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003900 DCHECK(Thread::Current()->IsExceptionPending());
3901 return false;
3902 }
3903 // Verify
3904 if (!klass->CanAccess(interface)) {
3905 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003906 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003907 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003908 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003909 return false;
3910 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003911 }
3912 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003913 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003914 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003915 return true;
3916}
3917
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003918bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003919 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003920 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003921 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003922 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003923 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003924 return false;
3925 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003926 return true;
3927 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003928 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003929 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
3930 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003931 return false;
3932 }
3933 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003934 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003935 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003936 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003937 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003938 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003939 return false;
3940 }
3941 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003942 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003943 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003944 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003945 return false;
3946 }
Elliott Hughes20cde902011-10-04 17:37:27 -07003947
Brian Carlstromf3632832014-05-20 15:36:53 -07003948 // Inherit kAccClassIsFinalizable from the superclass in case this
3949 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07003950 if (super->IsFinalizable()) {
3951 klass->SetFinalizable();
3952 }
3953
Elliott Hughes2da50362011-10-10 16:57:08 -07003954 // Inherit reference flags (if any) from the superclass.
3955 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
3956 if (reference_flags != 0) {
3957 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
3958 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07003959 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07003960 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003961 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003962 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003963 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07003964 return false;
3965 }
Elliott Hughes2da50362011-10-10 16:57:08 -07003966
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003967 if (kIsDebugBuild) {
3968 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003969 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003970 CHECK(super->IsResolved());
3971 super = super->GetSuperClass();
3972 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003973 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003974 return true;
3975}
3976
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003977// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003978bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003979 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
3980 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003981 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003982 if (klass->IsInterface()) {
3983 // No vtable.
3984 size_t count = klass->NumVirtualMethods();
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08003985 if (!IsUint<16>(count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003986 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003987 return false;
3988 }
Carl Shapiro565f5072011-07-10 13:39:43 -07003989 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003990 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003991 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003992 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
3993 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003994 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003995 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003996}
3997
Ian Rogers03b6eaf2014-10-28 09:34:57 -07003998// Comparator for name and signature of a method, used in finding overriding methods. Implementation
3999// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4000// caches in the implementation below.
4001class MethodNameAndSignatureComparator FINAL : public ValueObject {
4002 public:
4003 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4004 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4005 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4006 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004007 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4008 }
4009
4010 const char* GetName() {
4011 if (name_ == nullptr) {
4012 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4013 }
4014 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004015 }
4016
4017 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4018 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4019 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4020 const DexFile* other_dex_file = other->GetDexFile();
4021 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4022 if (dex_file_ == other_dex_file) {
4023 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4024 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004025 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004026 uint32_t other_name_len;
4027 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4028 &other_name_len);
4029 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4030 return false;
4031 }
4032 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4033 }
4034
4035 private:
4036 // Dex file for the method to compare against.
4037 const DexFile* const dex_file_;
4038 // MethodId for the method to compare against.
4039 const DexFile::MethodId* const mid_;
4040 // Lazily computed name from the dex file's strings.
4041 const char* name_;
4042 // Lazily computed name length.
4043 uint32_t name_len_;
4044};
4045
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004046class LinkVirtualHashTable {
4047 public:
4048 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4049 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4050 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4051 }
4052 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4053 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4054 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004055 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004056 uint32_t index = hash % hash_size_;
4057 // Linear probe until we have an empty slot.
4058 while (hash_table_[index] != invalid_index_) {
4059 if (++index == hash_size_) {
4060 index = 0;
4061 }
4062 }
4063 hash_table_[index] = virtual_method_index;
4064 }
4065 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4066 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4067 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004068 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004069 size_t index = hash % hash_size_;
4070 while (true) {
4071 const uint32_t value = hash_table_[index];
4072 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4073 // the block and can safely assume not found.
4074 if (value == invalid_index_) {
4075 break;
4076 }
4077 if (value != removed_index_) { // This signifies not already overriden.
4078 mirror::ArtMethod* virtual_method =
4079 klass_->GetVirtualMethodDuringLinking(value);
4080 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4081 hash_table_[index] = removed_index_;
4082 return value;
4083 }
4084 }
4085 if (++index == hash_size_) {
4086 index = 0;
4087 }
4088 }
4089 return GetNotFoundIndex();
4090 }
4091 static uint32_t GetNotFoundIndex() {
4092 return invalid_index_;
4093 }
4094
4095 private:
4096 static const uint32_t invalid_index_;
4097 static const uint32_t removed_index_;
4098
4099 Handle<mirror::Class> klass_;
4100 const size_t hash_size_;
4101 uint32_t* const hash_table_;
4102};
4103
4104const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4105const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4106
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004107bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004108 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004109 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004110 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4111 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004112 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004113 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004114 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004115 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4116 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4117 if (UNLIKELY(vtable.Get() == nullptr)) {
4118 CHECK(self->IsExceptionPending()); // OOME.
4119 return false;
4120 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004121 for (size_t i = 0; i < super_vtable_length; i++) {
4122 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004123 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004124 if (num_virtual_methods == 0) {
4125 klass->SetVTable(vtable.Get());
4126 return true;
4127 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004128 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004129 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4130 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4131 if (num_virtual_methods == 0) {
4132 klass->SetVTable(super_vtable);
4133 return true;
4134 }
4135 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004136 if (UNLIKELY(vtable.Get() == nullptr)) {
4137 CHECK(self->IsExceptionPending()); // OOME.
4138 return false;
4139 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004140 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004141 // How the algorithm works:
4142 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4143 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4144 // method which has not been matched to a vtable method, and j if the virtual method at the
4145 // index overrode the super virtual method at index j.
4146 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4147 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4148 // the need for the initial vtable which we later shrink back down).
4149 // 3. Add non overridden methods to the end of the vtable.
4150 static constexpr size_t kMaxStackHash = 250;
4151 const size_t hash_table_size = num_virtual_methods * 3;
4152 uint32_t* hash_table_ptr;
4153 std::unique_ptr<uint32_t[]> hash_heap_storage;
4154 if (hash_table_size <= kMaxStackHash) {
4155 hash_table_ptr = reinterpret_cast<uint32_t*>(
4156 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4157 } else {
4158 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4159 hash_table_ptr = hash_heap_storage.get();
4160 }
4161 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4162 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004163 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004164 hash_table.Add(i);
4165 }
4166 // Loop through each super vtable method and see if they are overriden by a method we added to
4167 // the hash table.
4168 for (size_t j = 0; j < super_vtable_length; ++j) {
4169 // Search the hash table to see if we are overidden by any method.
4170 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4171 MethodNameAndSignatureComparator super_method_name_comparator(
4172 super_method->GetInterfaceMethodIfProxy());
4173 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4174 if (hash_index != hash_table.GetNotFoundIndex()) {
4175 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4176 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4177 super_method->GetAccessFlags())) {
4178 if (super_method->IsFinal()) {
4179 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4180 PrettyMethod(virtual_method).c_str(),
4181 super_method->GetDeclaringClassDescriptor());
4182 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004183 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004184 vtable->SetWithoutChecks<false>(j, virtual_method);
4185 virtual_method->SetMethodIndex(j);
4186 } else {
4187 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004188 << " would have incorrectly overridden the package-private method in "
4189 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004190 }
4191 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004192 }
4193 // Add the non overridden methods at the end.
4194 size_t actual_count = super_vtable_length;
4195 for (size_t i = 0; i < num_virtual_methods; ++i) {
4196 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4197 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4198 if (method_idx < super_vtable_length &&
4199 local_method == vtable->GetWithoutChecks(method_idx)) {
4200 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004201 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004202 vtable->SetWithoutChecks<false>(actual_count, local_method);
4203 local_method->SetMethodIndex(actual_count);
4204 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004205 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004206 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004207 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004208 return false;
4209 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004210 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004211 CHECK_LE(actual_count, max_count);
4212 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004213 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004214 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004215 CHECK(self->IsExceptionPending()); // OOME.
4216 return false;
4217 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004218 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004219 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004220 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004221 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004222 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004223 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4224 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004225 return false;
4226 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004227 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4228 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004229 CHECK(self->IsExceptionPending()); // OOME.
4230 return false;
4231 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004232 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004233 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004234 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004235 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004236 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004237 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004238 }
4239 return true;
4240}
4241
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004242bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4243 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4244 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004245 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004246 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004247 const bool has_superclass = klass->HasSuperClass();
4248 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4249 const bool have_interfaces = interfaces.Get() != nullptr;
4250 const size_t num_interfaces =
4251 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4252 if (num_interfaces == 0) {
4253 if (super_ifcount == 0) {
4254 // Class implements no interfaces.
4255 DCHECK_EQ(klass->GetIfTableCount(), 0);
4256 DCHECK(klass->GetIfTable() == nullptr);
4257 return true;
4258 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004259 // Class implements same interfaces as parent, are any of these not marker interfaces?
4260 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004261 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004262 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004263 if (super_iftable->GetMethodArrayCount(i) > 0) {
4264 has_non_marker_interface = true;
4265 break;
4266 }
4267 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004268 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004269 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004270 klass->SetIfTable(super_iftable);
4271 return true;
4272 }
4273 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004274 size_t ifcount = super_ifcount + num_interfaces;
4275 for (size_t i = 0; i < num_interfaces; i++) {
4276 mirror::Class* interface = have_interfaces ?
4277 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4278 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004279 if (UNLIKELY(!interface->IsInterface())) {
4280 std::string temp;
4281 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4282 PrettyDescriptor(klass.Get()).c_str(),
4283 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4284 return false;
4285 }
4286 ifcount += interface->GetIfTableCount();
4287 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004288 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004289 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004290 CHECK(self->IsExceptionPending()); // OOME.
4291 return false;
4292 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004293 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004294 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004295 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004296 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004297 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004298 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004299 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004300 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004301 // Flatten the interface inheritance hierarchy.
4302 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004303 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004304 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4305 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004306 // Check if interface is already in iftable
4307 bool duplicate = false;
4308 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004309 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004310 if (existing_interface == interface) {
4311 duplicate = true;
4312 break;
4313 }
4314 }
4315 if (!duplicate) {
4316 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004317 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004318 // Add this interface's non-duplicate super-interfaces.
4319 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004320 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004321 bool super_duplicate = false;
4322 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004323 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004324 if (existing_interface == super_interface) {
4325 super_duplicate = true;
4326 break;
4327 }
4328 }
4329 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004330 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004331 }
4332 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004333 }
4334 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004335 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004336 // Shrink iftable in case duplicates were found
4337 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004338 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004339 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004340 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004341 CHECK(self->IsExceptionPending()); // OOME.
4342 return false;
4343 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004344 ifcount = idx;
4345 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004346 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004347 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004348 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004349 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004350 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004351 return true;
4352 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004353 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004354 size_t max_miranda_methods = 0; // The max size of miranda_list.
4355 for (size_t i = 0; i < ifcount; ++i) {
4356 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4357 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004358 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004359 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004360 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4361 hs.NewHandle(klass->GetVTableDuringLinking()));
4362 // Copy the IMT from the super class if possible.
4363 bool extend_super_iftable = false;
4364 if (has_superclass) {
4365 mirror::Class* super_class = klass->GetSuperClass();
4366 extend_super_iftable = true;
4367 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4368 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4369 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
4370 }
4371 } else {
4372 // No imt in the super class, need to reconstruct from the iftable.
4373 mirror::IfTable* if_table = super_class->GetIfTable();
4374 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4375 const size_t length = super_class->GetIfTableCount();
4376 for (size_t i = 0; i < length; ++i) {
4377 mirror::Class* interface = iftable->GetInterface(i);
4378 const size_t num_virtuals = interface->NumVirtualMethods();
4379 const size_t method_array_count = if_table->GetMethodArrayCount(i);
4380 DCHECK_EQ(num_virtuals, method_array_count);
4381 if (method_array_count == 0) {
4382 continue;
4383 }
4384 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
4385 for (size_t j = 0; j < num_virtuals; ++j) {
4386 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
4387 if (method->IsMiranda()) {
4388 continue;
4389 }
4390 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
4391 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4392 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4393 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4394 out_imt->SetReference(imt_index, method);
4395 } else if (imt_ref != conflict_method) {
4396 out_imt->SetReference(imt_index, conflict_method);
4397 }
4398 }
4399 }
4400 }
4401 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004402 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004403 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004404 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004405 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004406 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004407 const bool is_super = i < super_ifcount;
4408 const bool super_interface = is_super && extend_super_iftable;
4409 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
4410 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
4411 if (super_interface) {
4412 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
4413 DCHECK(if_table != nullptr);
4414 DCHECK(if_table->GetMethodArray(i) != nullptr);
4415 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004416 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004417 AsObjectArray<mirror::ArtMethod>());
4418 // We are overwriting a super class interface, try to only virtual methods instead of the
4419 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004420 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004421 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004422 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004423 // A new interface, we need the whole vtable incase a new interface method is implemented
4424 // in the whole superclass.
4425 input_array = vtable;
4426 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004427 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004428 CHECK(self->IsExceptionPending()); // OOME.
4429 return false;
4430 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004431 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004432 if (input_array.Get() == nullptr) {
4433 // If the added virtual methods is empty, do nothing.
4434 DCHECK(super_interface);
4435 continue;
4436 }
Ian Rogers62d6c772013-02-27 08:32:07 -08004437 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004438 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004439 MethodNameAndSignatureComparator interface_name_comparator(
4440 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07004441 int32_t k;
4442 // For each method listed in the interface's method list, find the
4443 // matching method in our class's method list. We want to favor the
4444 // subclass over the superclass, which just requires walking
4445 // back from the end of the vtable. (This only matters if the
4446 // superclass defines a private method and this class redefines
4447 // it -- otherwise it would use the same vtable slot. In .dex files
4448 // those don't end up in the virtual method table, so it shouldn't
4449 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004450 for (k = input_array->GetLength() - 1; k >= 0; --k) {
4451 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004452 mirror::ArtMethod* vtable_method_for_name_comparison =
4453 vtable_method->GetInterfaceMethodIfProxy();
4454 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004455 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004456 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004457 ThrowIllegalAccessError(
4458 klass.Get(),
4459 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004460 PrettyMethod(vtable_method).c_str(),
4461 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004462 return false;
4463 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004464 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004465 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004466 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4467 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4468 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4469 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4470 out_imt->SetReference(imt_index, vtable_method);
4471 } else if (imt_ref != conflict_method) {
4472 // If we are not a conflict and we have the same signature and name as the imt entry,
4473 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004474 MethodNameAndSignatureComparator imt_ref_name_comparator(
4475 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004476 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004477 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004478 out_imt->SetReference(imt_index, vtable_method);
4479 } else {
4480 out_imt->SetReference(imt_index, conflict_method);
4481 }
Jeff Hao88474b42013-10-23 16:24:40 -07004482 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004483 break;
4484 }
4485 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004486 if (k < 0 && !super_interface) {
4487 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004488 for (size_t l = 0; l < miranda_list_size; ++l) {
4489 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004490 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004491 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07004492 break;
4493 }
4494 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004495 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004496 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004497 miranda_method = interface_method->Clone(self)->AsArtMethod();
4498 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004499 CHECK(self->IsExceptionPending()); // OOME.
4500 return false;
4501 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004502 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004503 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004504 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004505 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004506 }
4507 }
4508 }
4509 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004510 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004511 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004512 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004513 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4514 if (old_method_count == 0) {
4515 virtuals = AllocArtMethodArray(self, new_method_count);
4516 } else {
4517 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4518 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004519 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004520 CHECK(self->IsExceptionPending()); // OOME.
4521 return false;
4522 }
4523 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004524
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004525 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004526 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004527 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004528 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004529 CHECK(self->IsExceptionPending()); // OOME.
4530 return false;
4531 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004532 for (size_t i = 0; i < miranda_list_size; ++i) {
4533 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004534 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004535 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4536 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4537 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004538 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004539 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004540 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004541 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004542 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004543
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004544 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004545 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
4546 for (int i = 0; i < check_vtable->GetLength(); ++i) {
4547 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004548 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004549 }
4550
Ian Rogers7b078e82014-09-10 14:44:24 -07004551 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004552 return true;
4553}
4554
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004555bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004556 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004557 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004558}
4559
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004560bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004561 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004562 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004563}
4564
Brian Carlstromdbc05252011-09-09 01:59:59 -07004565struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004566 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4567 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004568 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004569 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004570 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07004571 // 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 -07004572 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4573 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004574 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00004575 if (type1 == Primitive::kPrimNot) {
4576 // Reference always goes first.
4577 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08004578 }
Vladimir Markod5777482014-11-12 17:02:02 +00004579 if (type2 == Primitive::kPrimNot) {
4580 // Reference always goes first.
4581 return false;
4582 }
4583 size_t size1 = Primitive::ComponentSize(type1);
4584 size_t size2 = Primitive::ComponentSize(type2);
4585 if (size1 != size2) {
4586 // Larger primitive types go first.
4587 return size1 > size2;
4588 }
4589 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
4590 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004591 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004592 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
4593 // by name and for equal names by type id index.
4594 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
4595 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07004596 }
4597};
4598
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004599bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07004600 size_t* class_size) {
4601 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004602 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004603 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004604
Brian Carlstromea46f952013-07-30 01:26:50 -07004605 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004606 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004607
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004608 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07004609 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004610 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00004611 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004612 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004613 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004614 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004615 CHECK(super_class->IsResolved())
4616 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004617 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004618 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004619 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004620
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004621 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004622
Brian Carlstromdbc05252011-09-09 01:59:59 -07004623 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07004624 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07004625 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07004626 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07004627 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07004628 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004629 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004630 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004631 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004632 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004633 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4634 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004635
Fred Shih381e4ca2014-08-25 17:24:27 -07004636 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07004637 size_t current_field = 0;
4638 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07004639 FieldGaps gaps;
4640
Brian Carlstromdbc05252011-09-09 01:59:59 -07004641 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004642 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004643 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004644 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004645 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004646 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004647 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004648 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
4649 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07004650 MemberOffset old_offset = field_offset;
4651 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
4652 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
4653 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004654 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07004655 grouped_and_sorted_fields.pop_front();
4656 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004657 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00004658 field_offset = MemberOffset(field_offset.Uint32Value() +
4659 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004660 }
Fred Shih381e4ca2014-08-25 17:24:27 -07004661 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
4662 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00004663 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4664 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4665 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4666 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07004667 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
4668 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07004669 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004670
Elliott Hughesadb460d2011-10-05 17:02:34 -07004671 // 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 -07004672 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07004673 // We know there are no non-reference fields in the Reference classes, and we know
4674 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07004675 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004676 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07004677 --num_reference_fields;
4678 }
4679
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004680 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004681 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004682 if (is_static) {
4683 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004684 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004685 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004686 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004687 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08004688 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
Jeff Haoc7d11882015-02-03 15:08:39 -08004689 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
4690 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartier2d721012014-11-10 11:08:06 -08004691 } else {
4692 std::string temp;
4693 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
4694 size_t previous_size = klass->GetObjectSize();
4695 if (previous_size != 0) {
4696 // Make sure that we didn't originally have an incorrect size.
4697 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
4698 }
4699 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004700 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004701 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004702 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004703
4704 if (kIsDebugBuild) {
4705 // Make sure that the fields array is ordered by name but all reference
4706 // offsets are at the beginning as far as alignment allows.
4707 MemberOffset start_ref_offset = is_static
4708 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
4709 : klass->GetFirstReferenceInstanceFieldOffset();
4710 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
4711 num_reference_fields *
4712 sizeof(mirror::HeapReference<mirror::Object>));
4713 MemberOffset current_ref_offset = start_ref_offset;
4714 for (size_t i = 0; i < num_fields; i++) {
4715 mirror::ArtField* field = fields->Get(i);
4716 if ((false)) { // enable to debug field layout
4717 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
4718 << " class=" << PrettyClass(klass.Get())
4719 << " field=" << PrettyField(field)
4720 << " offset="
4721 << field->GetField32(mirror::ArtField::OffsetOffset());
4722 }
4723 if (i != 0) {
4724 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004725 // NOTE: The field names can be the same. This is not possible in the Java language
4726 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
4727 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00004728 }
4729 Primitive::Type type = field->GetTypeAsPrimitiveType();
4730 bool is_primitive = type != Primitive::kPrimNot;
4731 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
4732 strcmp("referent", field->GetName()) == 0) {
4733 is_primitive = true; // We lied above, so we have to expect a lie here.
4734 }
4735 MemberOffset offset = field->GetOffsetDuringLinking();
4736 if (is_primitive) {
4737 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
4738 // Shuffled before references.
4739 size_t type_size = Primitive::ComponentSize(type);
4740 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
4741 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
4742 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
4743 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
4744 }
4745 } else {
4746 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
4747 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
4748 sizeof(mirror::HeapReference<mirror::Object>));
4749 }
4750 }
4751 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
4752 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004753 return true;
4754}
4755
Vladimir Marko76649e82014-11-10 18:32:59 +00004756// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004757void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004758 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004759 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004760 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004761 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004762 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004763 // Compute reference offsets unless our superclass overflowed.
4764 if (reference_offsets != mirror::Class::kClassWalkSuper) {
4765 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00004766 if (num_reference_fields != 0u) {
4767 // All of the fields that contain object references are guaranteed be grouped in memory
4768 // starting at an appropriately aligned address after super class object data.
4769 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
4770 sizeof(mirror::HeapReference<mirror::Object>));
4771 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004772 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00004773 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004774 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004775 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00004776 reference_offsets |= (0xffffffffu << start_bit) &
4777 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004778 }
4779 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07004780 }
4781 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07004782 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004783}
4784
Mathieu Chartier590fee92013-09-13 13:46:47 -07004785mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004786 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004787 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004788 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004789 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004790 return resolved;
4791 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07004792 uint32_t utf16_length;
4793 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004794 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004795 dex_cache->SetResolvedString(string_idx, string);
4796 return string;
4797}
4798
Mathieu Chartier590fee92013-09-13 13:46:47 -07004799mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08004800 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004801 StackHandleScope<2> hs(Thread::Current());
4802 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
4803 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07004804 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
4805}
4806
4807mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004808 Handle<mirror::DexCache> dex_cache,
4809 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004810 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004811 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004812 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08004813 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07004814 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08004815 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004816 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05004817 // TODO: we used to throw here if resolved's class loader was not the
4818 // boot class loader. This was to permit different classes with the
4819 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004820 dex_cache->SetResolvedType(type_idx, resolved);
4821 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004822 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08004823 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08004824 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004825 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004826 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004827 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004828 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08004829 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08004830 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004831 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08004832 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004833 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004834 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004835 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07004836 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004837 return resolved;
4838}
4839
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004840mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004841 Handle<mirror::DexCache> dex_cache,
4842 Handle<mirror::ClassLoader> class_loader,
4843 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07004844 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004845 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07004846 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07004847 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004848 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004849 return resolved;
4850 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004851 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004852 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004853 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004854 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07004855 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004856 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004857 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004858 // Scan using method_idx, this saves string compares but will only hit for matching dex
4859 // caches/files.
4860 switch (type) {
4861 case kDirect: // Fall-through.
4862 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004863 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004864 break;
4865 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004866 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004867 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004868 break;
4869 case kSuper: // Fall-through.
4870 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004871 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004872 break;
4873 default:
4874 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07004875 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004876 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004877 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004878 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004879 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07004880 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07004881 switch (type) {
4882 case kDirect: // Fall-through.
4883 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08004884 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004885 break;
4886 case kInterface:
4887 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004888 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004889 break;
4890 case kSuper: // Fall-through.
4891 case kVirtual:
4892 resolved = klass->FindVirtualMethod(name, signature);
4893 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004894 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004895 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004896 // If we found a method, check for incompatible class changes.
4897 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004898 // Be a good citizen and update the dex cache to speed subsequent calls.
4899 dex_cache->SetResolvedMethod(method_idx, resolved);
4900 return resolved;
4901 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004902 // If we had a method, it's an incompatible-class-change error.
4903 if (resolved != nullptr) {
4904 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
4905 } else {
4906 // We failed to find the method which means either an access error, an incompatible class
4907 // change, or no such method. First try to find the method among direct and virtual methods.
4908 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
4909 const Signature signature = dex_file.GetMethodSignature(method_id);
4910 switch (type) {
4911 case kDirect:
4912 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07004913 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004914 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
4915 // have had a resolved method before, which triggers the "true" branch above.
4916 break;
4917 case kInterface:
4918 case kVirtual:
4919 case kSuper:
4920 resolved = klass->FindDirectMethod(name, signature);
4921 break;
4922 }
4923
4924 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08004925 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004926 if (resolved != nullptr && referrer.Get() != nullptr) {
4927 mirror::Class* methods_class = resolved->GetDeclaringClass();
4928 mirror::Class* referring_class = referrer->GetDeclaringClass();
4929 if (!referring_class->CanAccess(methods_class)) {
4930 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
4931 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004932 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004933 } else if (!referring_class->CanAccessMember(methods_class,
4934 resolved->GetAccessFlags())) {
4935 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004936 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004937 }
4938 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004939 if (!exception_generated) {
4940 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
4941 // interface methods and throw if we find the method there. If we find nothing, throw a
4942 // NoSuchMethodError.
4943 switch (type) {
4944 case kDirect:
4945 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004946 if (resolved != nullptr) {
4947 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4948 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004949 resolved = klass->FindInterfaceMethod(name, signature);
4950 if (resolved != nullptr) {
4951 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4952 } else {
4953 ThrowNoSuchMethodError(type, klass, name, signature);
4954 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004955 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004956 break;
4957 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004958 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004959 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
4960 } else {
4961 resolved = klass->FindVirtualMethod(name, signature);
4962 if (resolved != nullptr) {
4963 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4964 } else {
4965 ThrowNoSuchMethodError(type, klass, name, signature);
4966 }
4967 }
4968 break;
4969 case kSuper:
4970 if (resolved != nullptr) {
4971 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004972 } else {
4973 ThrowNoSuchMethodError(type, klass, name, signature);
4974 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004975 break;
4976 case kVirtual:
4977 if (resolved != nullptr) {
4978 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
4979 } else {
4980 resolved = klass->FindInterfaceMethod(name, signature);
4981 if (resolved != nullptr) {
4982 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4983 } else {
4984 ThrowNoSuchMethodError(type, klass, name, signature);
4985 }
4986 }
4987 break;
4988 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004989 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004990 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004991 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004992 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07004993 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004994}
4995
Mathieu Chartier590fee92013-09-13 13:46:47 -07004996mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004997 Handle<mirror::DexCache> dex_cache,
4998 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07004999 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005000 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005001 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005002 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005003 return resolved;
5004 }
5005 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005006 Thread* const self = Thread::Current();
5007 StackHandleScope<1> hs(self);
5008 Handle<mirror::Class> klass(
5009 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005010 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005011 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005012 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005013 }
5014
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005015 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005016 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005017 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005018 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005019 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005020
Andreas Gampe58a5af82014-07-31 16:23:49 -07005021 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005022 const char* name = dex_file.GetFieldName(field_id);
5023 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5024 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005025 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005026 } else {
5027 resolved = klass->FindInstanceField(name, type);
5028 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005029 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005030 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005031 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005032 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005033 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005034 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005035 return resolved;
5036}
5037
Brian Carlstromea46f952013-07-30 01:26:50 -07005038mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005039 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005040 Handle<mirror::DexCache> dex_cache,
5041 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005042 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005043 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005044 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005045 return resolved;
5046 }
5047 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005048 Thread* self = Thread::Current();
5049 StackHandleScope<1> hs(self);
5050 Handle<mirror::Class> klass(
5051 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005052 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005053 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005054 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005055 }
5056
Ian Rogersdfb325e2013-10-30 01:00:44 -07005057 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5058 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005059 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005060 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005061 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005062 dex_cache->SetResolvedField(field_idx, resolved);
5063 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005064 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005065 }
5066 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005067}
5068
Brian Carlstromea46f952013-07-30 01:26:50 -07005069const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005070 uint32_t* length) {
5071 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5072 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005073 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005074 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005075 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005076}
5077
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005078void ClassLinker::DumpAllClasses(int flags) {
5079 if (dex_cache_image_class_lookup_required_) {
5080 MoveImageClassesToClassTable();
5081 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005082 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5083 // 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 -08005084 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005085 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005086 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005087 for (GcRoot<mirror::Class>& it : class_table_) {
5088 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005089 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005090 }
5091
5092 for (size_t i = 0; i < all_classes.size(); ++i) {
5093 all_classes[i]->DumpClass(std::cerr, flags);
5094 }
5095}
5096
Elliott Hughes956af0f2014-12-11 14:34:28 -08005097static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005098 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005099 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5100 base -= sizeof(void*); // Move backward so that code_offset != 0.
5101 const uint32_t code_offset = sizeof(void*);
5102 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005103}
5104
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005105bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5106 return (entry_point == GetQuickResolutionStub()) ||
5107 (quick_resolution_trampoline_ == entry_point);
5108}
5109
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005110bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5111 return (entry_point == GetQuickToInterpreterBridge()) ||
5112 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5113}
5114
5115bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5116 return (entry_point == GetQuickGenericJniStub()) ||
5117 (quick_generic_jni_trampoline_ == entry_point);
5118}
5119
5120const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5121 return GetQuickGenericJniStub();
5122}
5123
Elliott Hughes956af0f2014-12-11 14:34:28 -08005124void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5125 const void* method_code) const {
5126 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005127 oat_method.LinkMethod(method);
5128 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005129}
5130
5131void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5132 if (!method->IsNative()) {
5133 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005134 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5135 } else {
5136 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005137 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005138 oat_method.LinkMethod(method);
5139 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005140 }
5141}
5142
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005143void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005144 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005145 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005146 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005147 MoveImageClassesToClassTable();
5148 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005149 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005150 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5151 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005152}
5153
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005154size_t ClassLinker::NumLoadedClasses() {
5155 if (dex_cache_image_class_lookup_required_) {
5156 MoveImageClassesToClassTable();
5157 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005158 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005159 // Only return non zygote classes since these are the ones which apps which care about.
5160 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005161}
5162
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005163pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005164 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005165}
5166
5167pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005168 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005169}
5170
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005171void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005172 DCHECK(!init_done_);
5173
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005174 DCHECK(klass != nullptr);
5175 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005176
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005177 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005178 DCHECK(class_roots != nullptr);
5179 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005180 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005181}
5182
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005183const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5184 static const char* class_roots_descriptors[] = {
5185 "Ljava/lang/Class;",
5186 "Ljava/lang/Object;",
5187 "[Ljava/lang/Class;",
5188 "[Ljava/lang/Object;",
5189 "Ljava/lang/String;",
5190 "Ljava/lang/DexCache;",
5191 "Ljava/lang/ref/Reference;",
5192 "Ljava/lang/reflect/ArtField;",
5193 "Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005194 "Ljava/lang/reflect/Field;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005195 "Ljava/lang/reflect/Proxy;",
5196 "[Ljava/lang/String;",
5197 "[Ljava/lang/reflect/ArtField;",
5198 "[Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005199 "[Ljava/lang/reflect/Field;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005200 "Ljava/lang/ClassLoader;",
5201 "Ljava/lang/Throwable;",
5202 "Ljava/lang/ClassNotFoundException;",
5203 "Ljava/lang/StackTraceElement;",
5204 "Z",
5205 "B",
5206 "C",
5207 "D",
5208 "F",
5209 "I",
5210 "J",
5211 "S",
5212 "V",
5213 "[Z",
5214 "[B",
5215 "[C",
5216 "[D",
5217 "[F",
5218 "[I",
5219 "[J",
5220 "[S",
5221 "[Ljava/lang/StackTraceElement;",
5222 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005223 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5224 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005225
5226 const char* descriptor = class_roots_descriptors[class_root];
5227 CHECK(descriptor != nullptr);
5228 return descriptor;
5229}
5230
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005231std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5232 const {
5233 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005234 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005235}
5236
5237bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005238 const GcRoot<mirror::Class>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005239 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5240 return false;
5241 }
5242 std::string temp;
5243 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5244}
5245
5246std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5247 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005248 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005249}
5250
5251bool ClassLinker::ClassDescriptorHashEquals::operator()(
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005252 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005253 if (a.Read()->GetClassLoader() != b.second) {
5254 return false;
5255 }
5256 return a.Read()->DescriptorEquals(b.first);
5257}
5258
5259bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005260 const char* descriptor) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005261 return a.Read()->DescriptorEquals(descriptor);
5262}
5263
5264std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005265 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005266}
5267
Sebastien Hertz6963e442014-11-26 22:11:27 +01005268bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07005269 if (Runtime::Current()->UseJit()) {
5270 // JIT can have direct code pointers from any method to any other method.
5271 return true;
5272 }
Sebastien Hertz6963e442014-11-26 22:11:27 +01005273 // Non-image methods don't use direct code pointer.
5274 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
5275 return false;
5276 }
5277 if (m->IsPrivate()) {
5278 // The method can only be called inside its own oat file. Therefore it won't be called using
5279 // its direct code if the oat file has been compiled in PIC mode.
Sebastien Hertz6963e442014-11-26 22:11:27 +01005280 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
Richard Uhler07b3c232015-03-31 15:57:54 -07005281 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Sebastien Hertz6963e442014-11-26 22:11:27 +01005282 if (oat_dex_file == nullptr) {
5283 // No oat file: the method has not been compiled.
5284 return false;
5285 }
5286 const OatFile* oat_file = oat_dex_file->GetOatFile();
5287 return oat_file != nullptr && !oat_file->IsPic();
5288 } else {
5289 // The method can be called outside its own oat file. Therefore it won't be called using its
5290 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
5291 ReaderMutexLock mu(Thread::Current(), dex_lock_);
5292 for (const OatFile* oat_file : oat_files_) {
5293 if (!oat_file->IsPic()) {
5294 return true;
5295 }
5296 }
5297 return false;
5298 }
5299}
5300
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005301jobject ClassLinker::CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files) {
5302 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
5303 // We could move the jobject to the callers, but all call-sites do this...
5304 ScopedObjectAccessUnchecked soa(self);
5305
5306 // Register the dex files.
5307 for (const DexFile* dex_file : dex_files) {
5308 RegisterDexFile(*dex_file);
5309 }
5310
5311 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
5312 StackHandleScope<11> hs(self);
5313
5314 Handle<mirror::ArtField> h_dex_elements_field =
5315 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements));
5316
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005317 mirror::Class* dex_elements_class = h_dex_elements_field->GetType<true>();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005318 DCHECK(dex_elements_class != nullptr);
5319 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005320 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
5321 mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005322 Handle<mirror::Class> h_dex_element_class =
5323 hs.NewHandle(dex_elements_class->GetComponentType());
5324
5325 Handle<mirror::ArtField> h_element_file_field =
5326 hs.NewHandle(
5327 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
5328 DCHECK_EQ(h_dex_element_class.Get(), h_element_file_field->GetDeclaringClass());
5329
5330 Handle<mirror::ArtField> h_cookie_field =
5331 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005332 DCHECK_EQ(h_cookie_field->GetDeclaringClass(), h_element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005333
5334 // Fill the elements array.
5335 int32_t index = 0;
5336 for (const DexFile* dex_file : dex_files) {
5337 StackHandleScope<3> hs2(self);
5338
5339 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(self, 1));
5340 DCHECK(h_long_array.Get() != nullptr);
5341 h_long_array->Set(0, reinterpret_cast<intptr_t>(dex_file));
5342
5343 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
5344 h_cookie_field->GetDeclaringClass()->AllocObject(self));
5345 DCHECK(h_dex_file.Get() != nullptr);
5346 h_cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
5347
5348 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
5349 DCHECK(h_element.Get() != nullptr);
5350 h_element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
5351
5352 h_dex_elements->Set(index, h_element.Get());
5353 index++;
5354 }
5355 DCHECK_EQ(index, h_dex_elements->GetLength());
5356
5357 // Create DexPathList.
5358 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
5359 h_dex_elements_field->GetDeclaringClass()->AllocObject(self));
5360 DCHECK(h_dex_path_list.Get() != nullptr);
5361 // Set elements.
5362 h_dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
5363
5364 // Create PathClassLoader.
5365 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
5366 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
5367 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
5368 h_path_class_class->AllocObject(self));
5369 DCHECK(h_path_class_loader.Get() != nullptr);
5370 // Set DexPathList.
5371 Handle<mirror::ArtField> h_path_list_field = hs.NewHandle(
5372 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList));
5373 DCHECK(h_path_list_field.Get() != nullptr);
5374 h_path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
5375
5376 // Make a pretend boot-classpath.
5377 // TODO: Should we scan the image?
5378 Handle<mirror::ArtField> h_parent_field = hs.NewHandle(
5379 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent",
5380 "Ljava/lang/ClassLoader;"));
5381 DCHECK(h_parent_field.Get() != nullptr);
5382 mirror::Object* boot_cl =
5383 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
5384 h_parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
5385
5386 // Make it a global ref and return.
5387 ScopedLocalRef<jobject> local_ref(
5388 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
5389 return soa.Env()->NewGlobalRef(local_ref.get());
5390}
5391
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005392} // namespace art