blob: be4b9e9b68de98033616d7214e88903d8351e27d [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromdbc05252011-09-09 01:59:59 -070019#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070020#include <iostream>
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070022#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070023#include <string>
Andreas Gampea696c0a2014-12-10 20:51:45 -080024#include <unistd.h>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070027
Elliott Hughes1aa246d2012-12-13 09:29:36 -080028#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080029#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010030#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080031#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080032#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080033#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000034#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080035#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070037#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070038#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/accounting/card_table-inl.h"
40#include "gc/accounting/heap_bitmap.h"
41#include "gc/heap.h"
42#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070043#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070044#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070045#include "interpreter/interpreter.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080046#include "jit/jit.h"
47#include "jit/jit_code_cache.h"
Ian Rogers0571d352011-11-03 19:51:38 -070048#include "leb128.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080049#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070050#include "oat_file.h"
Richard Uhler66d874d2015-01-15 09:37:19 -080051#include "oat_file_assistant.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070052#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070053#include "mirror/art_field-inl.h"
54#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055#include "mirror/class.h"
56#include "mirror/class-inl.h"
57#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070058#include "mirror/dex_cache-inl.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070059#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080060#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/object-inl.h"
62#include "mirror/object_array-inl.h"
63#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070064#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080065#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070066#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080067#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070068#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070069#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070070#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070071#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070072#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070073#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070074#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080075#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070076#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070077
78namespace art {
79
Ian Rogers00f7d0e2012-07-19 15:28:27 -070080static void ThrowNoClassDefFoundError(const char* fmt, ...)
81 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070082 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070083static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070084 va_list args;
85 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080086 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +000087 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080088 va_end(args);
89}
90
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080091static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070092 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070093 // The class failed to initialize on a previous attempt, so we want to throw
94 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
95 // failed in verification, in which case v2 5.4.1 says we need to re-throw
96 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080097 Runtime* const runtime = Runtime::Current();
98 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -070099 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
100 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700101
Elliott Hughes5c599942012-06-13 16:45:05 -0700102 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800103 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800104 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700105 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
106 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000107 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700108 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700109 if (c->GetVerifyErrorClass() != NULL) {
110 // TODO: change the verifier to store an _instance_, with a useful detail message?
111 std::string temp;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000112 self->ThrowNewException(c->GetVerifyErrorClass()->GetDescriptor(&temp),
Ian Rogers7b078e82014-09-10 14:44:24 -0700113 PrettyDescriptor(c).c_str());
114 } else {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000115 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
Ian Rogers7b078e82014-09-10 14:44:24 -0700116 PrettyDescriptor(c).c_str());
117 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700118 }
119}
120
Brian Carlstromb23eab12014-10-08 17:55:21 -0700121static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
122 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
123 if (VLOG_IS_ON(class_linker)) {
124 std::string temp;
125 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000126 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700127 }
128}
129
130static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
131 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700132 Thread* self = Thread::Current();
133 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700134
135 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700136 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700137
138 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700139 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
140 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700141
Elliott Hughesa4f94742012-05-29 16:28:38 -0700142 // We only wrap non-Error exceptions; an Error can just be used as-is.
143 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000144 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700145 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700146 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700147}
148
Fred Shih381e4ca2014-08-25 17:24:27 -0700149// Gap between two fields in object layout.
150struct FieldGap {
151 uint32_t start_offset; // The offset from the start of the object.
152 uint32_t size; // The gap size of 1, 2, or 4 bytes.
153};
154struct FieldGapsComparator {
155 explicit FieldGapsComparator() {
156 }
157 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
158 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800159 // Sort by gap size, largest first. Secondary sort by starting offset.
160 return lhs.size > rhs.size || (lhs.size == rhs.size && lhs.start_offset < rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700161 }
162};
163typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
164
165// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800166static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700167 DCHECK(gaps != nullptr);
168
169 uint32_t current_offset = gap_start;
170 while (current_offset != gap_end) {
171 size_t remaining = gap_end - current_offset;
172 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
173 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
174 current_offset += sizeof(uint32_t);
175 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
176 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
177 current_offset += sizeof(uint16_t);
178 } else {
179 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
180 current_offset += sizeof(uint8_t);
181 }
182 DCHECK_LE(current_offset, gap_end) << "Overran gap";
183 }
184}
185// Shuffle fields forward, making use of gaps whenever possible.
186template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000187static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700188 MemberOffset* field_offset,
Fred Shih381e4ca2014-08-25 17:24:27 -0700189 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
190 FieldGaps* gaps)
191 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
192 DCHECK(current_field_idx != nullptr);
193 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700194 DCHECK(gaps != nullptr);
195 DCHECK(field_offset != nullptr);
196
197 DCHECK(IsPowerOfTwo(n));
198 while (!grouped_and_sorted_fields->empty()) {
199 mirror::ArtField* field = grouped_and_sorted_fields->front();
200 Primitive::Type type = field->GetTypeAsPrimitiveType();
201 if (Primitive::ComponentSize(type) < n) {
202 break;
203 }
204 if (!IsAligned<n>(field_offset->Uint32Value())) {
205 MemberOffset old_offset = *field_offset;
206 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
207 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
208 }
209 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
210 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700211 if (!gaps->empty() && gaps->top().size >= n) {
212 FieldGap gap = gaps->top();
213 gaps->pop();
214 DCHECK(IsAligned<n>(gap.start_offset));
215 field->SetOffset(MemberOffset(gap.start_offset));
216 if (gap.size > n) {
217 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
218 }
219 } else {
220 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
221 field->SetOffset(*field_offset);
222 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
223 }
224 ++(*current_field_idx);
225 }
226}
227
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800228ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700229 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700230 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700231 dex_cache_image_class_lookup_required_(false),
232 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800233 class_roots_(nullptr),
234 array_iftable_(nullptr),
235 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700236 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800237 log_new_dex_caches_roots_(false),
238 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700239 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800240 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800241 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100242 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800243 quick_to_interpreter_bridge_trampoline_(nullptr),
244 image_pointer_size_(sizeof(void*)) {
Ian Rogers98379392014-02-24 16:53:16 -0800245 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700246}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700247
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800248void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800249 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700250 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700251
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700252 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700253
Elliott Hughes30646832011-10-13 16:59:46 -0700254 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700255 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700256 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700257 // The GC can't handle an object with a null class since we can't get the size of this object.
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800258 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700259 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
260 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700261 heap->AllocNonMovableObject<true>(self, nullptr,
262 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700263 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700264 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700265 mirror::Class::SetClassClass(java_lang_Class.Get());
266 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700267 if (kUseBakerOrBrooksReadBarrier) {
268 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800269 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700270 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700271 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800272 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800273 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700274
Elliott Hughes418d20f2011-09-22 14:00:39 -0700275 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700276 Handle<mirror::Class> class_array_class(hs.NewHandle(
277 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700278 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700279
Ian Rogers23435d02012-09-24 11:23:12 -0700280 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700281 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
282 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700283 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700284 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700285 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700286 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700287
Ian Rogers23435d02012-09-24 11:23:12 -0700288 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700289 Handle<mirror::Class> object_array_class(hs.NewHandle(
290 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700291 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700292
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700293 // Setup the char (primitive) class to be used for char[].
294 Handle<mirror::Class> char_class(hs.NewHandle(
295 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700296 // The primitive char class won't be initialized by
297 // InitializePrimitiveClass until line 459, but strings (and
298 // internal char arrays) will be allocated before that and the
299 // component size, which is computed from the primitive type, needs
300 // to be set here.
301 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700302
Ian Rogers23435d02012-09-24 11:23:12 -0700303 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700304 Handle<mirror::Class> char_array_class(hs.NewHandle(
305 AllocClass(self, java_lang_Class.Get(),
306 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700307 char_array_class->SetComponentType(char_class.Get());
308 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700309
Ian Rogers23435d02012-09-24 11:23:12 -0700310 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700311 Handle<mirror::Class> java_lang_String(hs.NewHandle(
312 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700313 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700314 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700315 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400316
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700317 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700318 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
319 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
320 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
321 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700322 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700323
Ian Rogers23435d02012-09-24 11:23:12 -0700324 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700325 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700326 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
327 kClassRootsMax));
328 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700329 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
330 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
331 SetClassRoot(kClassArrayClass, class_array_class.Get());
332 SetClassRoot(kObjectArrayClass, object_array_class.Get());
333 SetClassRoot(kCharArrayClass, char_array_class.Get());
334 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700335 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700336
337 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700338 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
339 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
340 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
341 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
342 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
343 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
344 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
345 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700346
Ian Rogers23435d02012-09-24 11:23:12 -0700347 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700348 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349
Ian Rogers23435d02012-09-24 11:23:12 -0700350 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700351 Handle<mirror::Class> int_array_class(hs.NewHandle(
352 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700353 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700354 mirror::IntArray::SetArrayClass(int_array_class.Get());
355 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700356
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700357 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700358
Ian Rogers52813c92012-10-11 11:50:38 -0700359 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700360 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
361 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700362 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700363 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700364 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700365
Brian Carlstromf3632832014-05-20 15:36:53 -0700366 // Constructor, Field, Method, and AbstractMethod are necessary so
367 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700368 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
369 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700370 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700371 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700372 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700373 mirror::Class::SetStatus(java_lang_reflect_ArtField, mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700374 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700375
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700376 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
377 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700378 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800379 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
380 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700381 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700382 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700383 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700384
385 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700386 Handle<mirror::Class> object_array_string(hs.NewHandle(
387 AllocClass(self, java_lang_Class.Get(),
388 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700389 object_array_string->SetComponentType(java_lang_String.Get());
390 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700391
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700392 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
393 AllocClass(self, java_lang_Class.Get(),
394 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700395 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
396 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700397
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700398 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
399 AllocClass(self, java_lang_Class.Get(),
400 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700401 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
402 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700403
Ian Rogers23435d02012-09-24 11:23:12 -0700404 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
405 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
406 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700407 CHECK_NE(0U, boot_class_path.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800408 for (auto& dex_file : boot_class_path) {
409 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700410 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800411 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700412 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
414 // now we can use FindSystemClass
415
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700416 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700417 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
418 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700419
Jeff Hao88474b42013-10-23 16:24:40 -0700420 // Create runtime resolution and imt conflict methods. Also setup the default imt.
421 Runtime* runtime = Runtime::Current();
422 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
423 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700424 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700425 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
426
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700427 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
428 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700429 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800430 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700431 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700432 quick_resolution_trampoline_ = GetQuickResolutionStub();
433 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
434 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700435 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700436
Mathieu Chartier66f19252012-09-18 08:57:04 -0700437 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700438 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800439 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700440 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700441 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700442 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800443 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700444 std::ostringstream os1, os2;
445 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
446 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
447 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
448 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700449 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800450 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700451 CHECK_EQ(java_lang_String.Get(), String_class);
452 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700453 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454
Ian Rogers23435d02012-09-24 11:23:12 -0700455 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800456 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800457 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700458
Ian Rogers98379392014-02-24 16:53:16 -0800459 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800460 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700461
Ian Rogers98379392014-02-24 16:53:16 -0800462 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700463 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700464
Ian Rogers98379392014-02-24 16:53:16 -0800465 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800466 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700467
Ian Rogers98379392014-02-24 16:53:16 -0800468 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700469 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470
Ian Rogers98379392014-02-24 16:53:16 -0800471 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800472 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700473
Ian Rogers98379392014-02-24 16:53:16 -0800474 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800475 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700476
Ian Rogers98379392014-02-24 16:53:16 -0800477 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800478 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700479
Ian Rogers98379392014-02-24 16:53:16 -0800480 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700481 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700482
Ian Rogers98379392014-02-24 16:53:16 -0800483 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700484 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700485
Ian Rogers23435d02012-09-24 11:23:12 -0700486 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800487 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700488 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800489 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700490 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700491 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
492 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700493 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700494 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700495 array_iftable->SetInterface(0, java_lang_Cloneable);
496 array_iftable->SetInterface(1, java_io_Serializable);
497 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700498
Ian Rogers23435d02012-09-24 11:23:12 -0700499 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700500 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
501 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
502 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
503 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700504 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700505 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800506 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700507 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700508
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700509 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800510 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700511 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700512
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700513 mirror::Class::SetStatus(java_lang_reflect_ArtField, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800514 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700515 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700516
Brian Carlstromf3632832014-05-20 15:36:53 -0700517 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700518 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700519 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700520
Brian Carlstromea46f952013-07-30 01:26:50 -0700521 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700522 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700523 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700524
Brian Carlstromea46f952013-07-30 01:26:50 -0700525 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700526 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700527 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700528
Ian Rogers23435d02012-09-24 11:23:12 -0700529 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700530
Ian Rogers23435d02012-09-24 11:23:12 -0700531 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800532 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700533 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
534
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700535 // Create java.lang.reflect.Field.class root.
536 mirror::Class* java_lang_reflect_Field = FindSystemClass(self, "Ljava/lang/reflect/Field;");
537 CHECK(java_lang_reflect_Field != nullptr);
538 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
539 mirror::Field::SetClass(java_lang_reflect_Field);
540
541 // Create java.lang.reflect.Field array root.
542 mirror::Class* java_lang_reflect_Field_array =
543 FindSystemClass(self, "[Ljava/lang/reflect/Field;");
544 CHECK(java_lang_reflect_Field_array != nullptr);
545 SetClassRoot(kJavaLangReflectFieldArrayClass, java_lang_reflect_Field_array);
546 mirror::Field::SetArrayClass(java_lang_reflect_Field_array);
547
Brian Carlstrom1f870082011-08-23 16:02:11 -0700548 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700549 // finish initializing Reference class
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700550 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700551 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
552 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
553 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
554 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700555 mirror::Class* java_lang_ref_FinalizerReference =
556 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700557 java_lang_ref_FinalizerReference->SetAccessFlags(
558 java_lang_ref_FinalizerReference->GetAccessFlags() |
559 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700560 mirror::Class* java_lang_ref_PhantomReference =
561 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700562 java_lang_ref_PhantomReference->SetAccessFlags(
563 java_lang_ref_PhantomReference->GetAccessFlags() |
564 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700565 mirror::Class* java_lang_ref_SoftReference =
566 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700567 java_lang_ref_SoftReference->SetAccessFlags(
568 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700569 mirror::Class* java_lang_ref_WeakReference =
570 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700571 java_lang_ref_WeakReference->SetAccessFlags(
572 java_lang_ref_WeakReference->GetAccessFlags() |
573 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700574
Ian Rogers23435d02012-09-24 11:23:12 -0700575 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800576 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700577 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700578 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
579
jeffhao8cd6dda2012-02-22 10:15:34 -0800580 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700581 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800582 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800583 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700584 SetClassRoot(kJavaLangClassNotFoundException,
585 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800586 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700587 SetClassRoot(kJavaLangStackTraceElementArrayClass,
588 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800589 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700590
Andreas Gampe76bd8802014-12-10 16:43:58 -0800591 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
592 // initialized.
593 {
594 const DexFile& dex_file = java_lang_Object->GetDexFile();
595 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
596 CHECK(void_string_id != nullptr);
597 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
598 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
599 CHECK(void_type_id != nullptr);
600 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
601 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
602 // as referrer so the used dex cache is core's one.
603 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
604 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
605 self->AssertNoPendingException();
606 }
607
Ian Rogers98379392014-02-24 16:53:16 -0800608 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700609
Brian Carlstroma004aa92012-02-08 18:05:09 -0800610 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700611}
612
Ian Rogers98379392014-02-24 16:53:16 -0800613void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800614 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700615
616 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700617 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700618 // as the types of the field can't be resolved prior to the runtime being
619 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800620 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700621 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800622 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800623
Brian Carlstromea46f952013-07-30 01:26:50 -0700624 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700625 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
626 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700627
Brian Carlstromea46f952013-07-30 01:26:50 -0700628 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700629 CHECK_STREQ(queue->GetName(), "queue");
630 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700631
Brian Carlstromea46f952013-07-30 01:26:50 -0700632 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700633 CHECK_STREQ(queueNext->GetName(), "queueNext");
634 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700635
Brian Carlstromea46f952013-07-30 01:26:50 -0700636 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700637 CHECK_STREQ(referent->GetName(), "referent");
638 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700639
Brian Carlstromea46f952013-07-30 01:26:50 -0700640 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700641 CHECK_STREQ(zombie->GetName(), "zombie");
642 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700643
Brian Carlstroma663ea52011-08-19 23:33:41 -0700644 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700645 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700646 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800647 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700648 CHECK(klass != nullptr);
649 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700650 // note SetClassRoot does additional validation.
651 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700652 }
653
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700654 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700655
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700656 // disable the slow paths in FindClass and CreatePrimitiveClass now
657 // that Object, Class, and Object[] are setup
658 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700659
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800660 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700661}
662
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700663void ClassLinker::RunRootClinits() {
664 Thread* self = Thread::Current();
665 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800666 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700667 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700668 StackHandleScope<1> hs(self);
669 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700670 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700671 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700672 }
673 }
674}
675
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700676const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700677 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800678 if (kIsDebugBuild) {
679 for (size_t i = 0; i < oat_files_.size(); ++i) {
680 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700681 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800682 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700683 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
684 oat_files_.push_back(oat_file);
685 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800686}
687
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700688OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
689 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700690 OatFile* oat_file = space->ReleaseOatFile();
691 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700692 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700693 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700694}
695
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100696const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800697 const char* dex_location = dex_file.GetLocation().c_str();
698 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100699 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800700}
701
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100702const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
703 const char* dex_location,
704 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700705 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100706 for (const OatFile* oat_file : oat_files_) {
707 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700708
709 if (oat_location != nullptr) {
710 if (oat_file->GetLocation() != oat_location) {
711 continue;
712 }
713 }
714
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700715 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800716 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700717 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100718 if (oat_dex_file != nullptr) {
719 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800720 }
721 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100722 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800723}
724
Richard Uhler66d874d2015-01-15 09:37:19 -0800725std::vector<std::unique_ptr<const DexFile>> ClassLinker::OpenDexFilesFromOat(
726 const char* dex_location, const char* oat_location,
727 std::vector<std::string>* error_msgs) {
728 CHECK(error_msgs != nullptr);
Calin Juravle621962a2014-09-02 15:53:55 +0100729
Richard Uhler66d874d2015-01-15 09:37:19 -0800730 // Verify we aren't holding the mutator lock, which could starve GC if we
731 // have to generate or relocate an oat file.
732 Locks::mutator_lock_->AssertNotHeld(Thread::Current());
733
734 OatFileAssistant oat_file_assistant(dex_location, oat_location, kRuntimeISA,
735 !Runtime::Current()->IsAotCompiler());
736
737 // Lock the target oat location to avoid races generating and loading the
738 // oat file.
739 std::string error_msg;
740 if (!oat_file_assistant.Lock(&error_msg)) {
741 // Don't worry too much if this fails. If it does fail, it's unlikely we
742 // can generate an oat file anyway.
743 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700744 }
745
Richard Uhler66d874d2015-01-15 09:37:19 -0800746 // Check if we already have an up-to-date oat file open.
747 const OatFile* source_oat_file = nullptr;
748 {
749 ReaderMutexLock mu(Thread::Current(), dex_lock_);
750 for (const OatFile* oat_file : oat_files_) {
751 CHECK(oat_file != nullptr);
752 if (oat_file_assistant.GivenOatFileIsUpToDate(*oat_file)) {
753 source_oat_file = oat_file;
754 break;
Andreas Gampe833a4852014-05-21 18:46:59 -0700755 }
756 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700757 }
758
Richard Uhler66d874d2015-01-15 09:37:19 -0800759 // If we didn't have an up-to-date oat file open, try to load one from disk.
760 if (source_oat_file == nullptr) {
761 // Update the oat file on disk if we can. This may fail, but that's okay.
762 // Best effort is all that matters here.
763 if (!oat_file_assistant.MakeUpToDate(&error_msg)) {
764 LOG(WARNING) << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700765 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700766
Richard Uhler66d874d2015-01-15 09:37:19 -0800767 // Get the oat file on disk.
768 std::unique_ptr<OatFile> oat_file = oat_file_assistant.GetBestOatFile();
769 if (oat_file.get() != nullptr) {
770 source_oat_file = oat_file.release();
771 RegisterOatFile(source_oat_file);
Andreas Gampe833a4852014-05-21 18:46:59 -0700772 }
773 }
774
Richard Uhler66d874d2015-01-15 09:37:19 -0800775 std::vector<std::unique_ptr<const DexFile>> dex_files;
Andreas Gampe833a4852014-05-21 18:46:59 -0700776
Richard Uhler66d874d2015-01-15 09:37:19 -0800777 // Load the dex files from the oat file.
778 if (source_oat_file != nullptr) {
779 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
780 if (dex_files.empty()) {
781 error_msgs->push_back("Failed to open dex files from "
782 + source_oat_file->GetLocation());
Andreas Gampe833a4852014-05-21 18:46:59 -0700783 }
784 }
785
Richard Uhler66d874d2015-01-15 09:37:19 -0800786 // Fall back to running out of the original dex file if we couldn't load any
787 // dex_files from the oat file.
788 if (dex_files.empty()) {
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700789 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800790 if (!DexFile::Open(dex_location, dex_location, &error_msg, &dex_files)) {
791 LOG(WARNING) << error_msg;
792 error_msgs->push_back("Failed to open dex files from "
793 + std::string(dex_location));
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700794 }
795 } else {
796 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
797 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700798 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800799 return dex_files;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700800}
801
Brian Carlstromae826982011-11-09 01:33:42 -0800802const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700803 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700804 for (size_t i = 0; i < oat_files_.size(); i++) {
805 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700806 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -0800807 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700808 return oat_file;
809 }
810 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700811 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -0700812}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700813
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800814void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700815 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700816 DCHECK(obj != nullptr);
817 DCHECK(class_linker != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700818 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700819 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -0700820 if (!method->IsNative()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800821 const size_t pointer_size = class_linker->image_pointer_size_;
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800822 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800823 if (!method->IsRuntimeMethod() && method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800824 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
825 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -0700826 }
827 }
828 }
829}
830
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700831void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800832 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700833 CHECK(!init_done_);
834
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700835 Runtime* const runtime = Runtime::Current();
836 Thread* const self = Thread::Current();
837 gc::Heap* const heap = runtime->GetHeap();
838 gc::space::ImageSpace* const space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700839 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700840 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700841 OatFile& oat_file = GetImageOatFile(space);
842 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
843 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700844 const char* image_file_location = oat_file.GetOatHeader().
845 GetStoreValueByKey(OatHeader::kImageLocationKey);
846 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700847 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -0700848 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -0800849 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +0100850 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800851 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
852 mirror::ObjectArray<mirror::DexCache>* dex_caches =
853 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700854
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700855 StackHandleScope<1> hs(self);
856 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
857 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
858 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700859 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700860
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700861 // Special case of setting up the String class early so that we can test arbitrary objects
862 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700863 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800864
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700865 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700866 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700867 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800868 StackHandleScope<1> hs2(self);
869 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700870 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700871 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
872 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700873 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700874 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800875 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
876 if (dex_file.get() == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700877 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700878 << " from within oat file " << oat_file.GetLocation()
879 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -0800880 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700881 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700882
883 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
884
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800885 AppendToBootClassPath(*dex_file.get(), dex_cache);
886 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700887 }
888
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700889 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
890 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -0700891 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -0800892 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700893 if (!runtime->IsAotCompiler()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800894 // Aot compiler supports having an image with a different pointer size than the runtime. This
Mathieu Chartier2d721012014-11-10 11:08:06 -0800895 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
896 // also use 32 bit dex2oat on a system with 64 bit apps.
897 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
898 << sizeof(void*);
899 }
900 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
901 image_pointer_size_ = 4;
902 } else {
903 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
904 image_pointer_size_ = 8;
905 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700906
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700907 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800908 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700909 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700910 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700911
912 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800913 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700914 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700915
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800916 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700917 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800918 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800919 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700920 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
921 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Fred Shih4ee7a662014-07-11 09:59:27 -0700922 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -0700923 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800924 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
925 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
926 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
927 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
928 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
929 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
930 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
931 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
932 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
933 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700934
Ian Rogers98379392014-02-24 16:53:16 -0800935 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700936
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800937 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700938}
939
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700940void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
941 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
942 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800943 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800944 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800945 }
946 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800947 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700948 }
949 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800950 for (auto& root : new_class_roots_) {
951 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800952 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800953 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700954 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700955 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
956 // corresponding object. This is slow, but luckily for us, this may only happen with a
957 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800958 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800959 DCHECK(it != class_table_.end());
960 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700961 }
962 }
963 }
964 if ((flags & kVisitRootFlagClearRootLog) != 0) {
965 new_class_roots_.clear();
966 }
967 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
968 log_new_class_table_roots_ = true;
969 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
970 log_new_class_table_roots_ = false;
971 }
972 // We deliberately ignore the class roots in the image since we
973 // handle image roots by using the MS/CMS rescanning of dirty cards.
974}
975
Brian Carlstroma663ea52011-08-19 23:33:41 -0700976// Keep in sync with InitCallback. Anything we visit, we need to
977// reinit references to when reinitializing a ClassLinker from a
978// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -0800979void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800980 class_roots_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers50b35e22012-10-04 10:09:15 -0700981 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -0700982 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700983 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800984 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700985 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800986 dex_cache.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -0700987 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800988 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
989 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800990 dex_caches_[index].VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -0700991 }
Elliott Hughesf8349362012-06-18 15:00:06 -0700992 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800993 if ((flags & kVisitRootFlagClearRootLog) != 0) {
994 new_dex_cache_roots_.clear();
995 }
996 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
997 log_new_dex_caches_roots_ = true;
998 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
999 log_new_dex_caches_roots_ = false;
1000 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001001 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001002 VisitClassRoots(callback, arg, flags);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001003 array_iftable_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001004 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001005 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001006 find_array_class_cache_[i].VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001007 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001008}
1009
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001010void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1011 if (dex_cache_image_class_lookup_required_) {
1012 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001013 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001014 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001015 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001016 for (GcRoot<mirror::Class>& root : class_table_) {
1017 if (!visitor(root.Read(), arg)) {
1018 return;
1019 }
1020 }
1021 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1022 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001023 return;
1024 }
1025 }
1026}
1027
Ian Rogersdbf3be02014-08-29 15:40:08 -07001028static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001029 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001030 classes->insert(c);
1031 return true;
1032}
1033
Ian Rogersdbf3be02014-08-29 15:40:08 -07001034struct GetClassesVisitorArrayArg {
1035 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1036 int32_t index;
1037 bool success;
1038};
1039
1040static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1041 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1042 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1043 if (arg->index < (*arg->classes)->GetLength()) {
1044 (*arg->classes)->Set(arg->index, c);
1045 arg->index++;
1046 return true;
1047 } else {
1048 arg->success = false;
1049 return false;
1050 }
1051}
1052
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001053void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001054 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1055 // is avoiding duplicates.
1056 if (!kMovingClasses) {
1057 std::set<mirror::Class*> classes;
1058 VisitClasses(GetClassesVisitorSet, &classes);
1059 for (mirror::Class* klass : classes) {
1060 if (!visitor(klass, arg)) {
1061 return;
1062 }
1063 }
1064 } else {
1065 Thread* self = Thread::Current();
1066 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001067 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001068 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1069 GetClassesVisitorArrayArg local_arg;
1070 local_arg.classes = &classes;
1071 local_arg.success = false;
1072 // We size the array assuming classes won't be added to the class table during the visit.
1073 // If this assumption fails we iterate again.
1074 while (!local_arg.success) {
1075 size_t class_table_size;
1076 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001077 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001078 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001079 }
1080 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1081 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1082 classes.Assign(
1083 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1084 CHECK(classes.Get() != nullptr); // OOME.
1085 local_arg.index = 0;
1086 local_arg.success = true;
1087 VisitClasses(GetClassesVisitorArray, &local_arg);
1088 }
1089 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1090 // If the class table shrank during creation of the clases array we expect null elements. If
1091 // the class table grew then the loop repeats. If classes are created after the loop has
1092 // finished then we don't visit.
1093 mirror::Class* klass = classes->Get(i);
1094 if (klass != nullptr && !visitor(klass, arg)) {
1095 return;
1096 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001097 }
1098 }
1099}
1100
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001101ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001102 mirror::Class::ResetClass();
1103 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001104 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001105 mirror::ArtField::ResetClass();
1106 mirror::ArtMethod::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001107 mirror::Field::ResetClass();
1108 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001109 mirror::BooleanArray::ResetArrayClass();
1110 mirror::ByteArray::ResetArrayClass();
1111 mirror::CharArray::ResetArrayClass();
1112 mirror::DoubleArray::ResetArrayClass();
1113 mirror::FloatArray::ResetArrayClass();
1114 mirror::IntArray::ResetArrayClass();
1115 mirror::LongArray::ResetArrayClass();
1116 mirror::ShortArray::ResetArrayClass();
1117 mirror::Throwable::ResetClass();
1118 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001119 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001120}
1121
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001122mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001123 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001124 StackHandleScope<16> hs(self);
1125 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1126 Handle<mirror::DexCache> dex_cache(
1127 hs.NewHandle(down_cast<mirror::DexCache*>(
1128 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1129 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001130 if (dex_cache.Get() == nullptr) {
1131 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001132 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001133 Handle<mirror::String>
1134 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001135 if (location.Get() == nullptr) {
1136 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001137 }
Ian Rogers700a4022014-05-19 16:49:03 -07001138 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001139 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001140 if (strings.Get() == nullptr) {
1141 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001142 }
Ian Rogers700a4022014-05-19 16:49:03 -07001143 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001144 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001145 if (types.Get() == nullptr) {
1146 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001147 }
Ian Rogers700a4022014-05-19 16:49:03 -07001148 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001149 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001150 if (methods.Get() == nullptr) {
1151 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001152 }
Ian Rogers700a4022014-05-19 16:49:03 -07001153 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001154 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001155 if (fields.Get() == nullptr) {
1156 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001157 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001158 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1159 fields.Get());
1160 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001161}
1162
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001163mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001164 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001165 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001166 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001167 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001168 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001169 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1170 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001171 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001172 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001173 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001174 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001175 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001176}
1177
Ian Rogers6fac4472014-02-25 17:01:10 -08001178mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001179 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001180}
1181
Brian Carlstromea46f952013-07-30 01:26:50 -07001182mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001183 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001184 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001185}
1186
Brian Carlstromea46f952013-07-30 01:26:50 -07001187mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001188 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001189 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001190}
1191
Mathieu Chartier590fee92013-09-13 13:46:47 -07001192mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1193 Thread* self, size_t length) {
1194 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1195 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001196}
1197
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001198mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1199 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001200 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001201
1202 // For temporary classes we must wait for them to be retired.
1203 if (init_done_ && klass->IsTemp()) {
1204 CHECK(!klass->IsResolved());
1205 if (klass->IsErroneous()) {
1206 ThrowEarlierClassFailure(klass);
1207 return nullptr;
1208 }
1209 StackHandleScope<1> hs(self);
1210 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1211 ObjectLock<mirror::Class> lock(self, h_class);
1212 // Loop and wait for the resolving thread to retire this class.
1213 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1214 lock.WaitIgnoringInterrupts();
1215 }
1216 if (h_class->IsErroneous()) {
1217 ThrowEarlierClassFailure(h_class.Get());
1218 return nullptr;
1219 }
1220 CHECK(h_class->IsRetired());
1221 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001222 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
1223 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001224 }
1225
Brian Carlstromaded5f72011-10-07 17:15:04 -07001226 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001227 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001228 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001229 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1230 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001231 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001232 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1233 ThrowClassCircularityError(h_class.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001234 mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001235 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001236 }
1237 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001238 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001239 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001240 }
1241 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001242
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001243 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001244 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001245 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001246 }
1247 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001248 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001249 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001250 return klass;
1251}
1252
Ian Rogers68b56852014-08-29 20:19:11 -07001253typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
1254
1255// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001256ClassPathEntry FindInClassPath(const char* descriptor,
1257 size_t hash, const std::vector<const DexFile*>& class_path) {
1258 for (const DexFile* dex_file : class_path) {
1259 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001260 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07001261 return ClassPathEntry(dex_file, dex_class_def);
1262 }
1263 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001264 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07001265}
1266
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001267mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1268 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001269 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001270 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08001271 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001272 if (class_loader->GetClass() !=
1273 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
1274 class_loader->GetParent()->GetClass() !=
1275 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
1276 return nullptr;
1277 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001278 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001279 // Check if this would be found in the parent boot class loader.
1280 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001281 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001282 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08001283 // May return null if resolution on another thread fails.
1284 klass = EnsureResolved(self, descriptor, klass);
1285 } else {
1286 // May OOME.
1287 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
1288 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001289 }
Ian Rogers32427292014-11-19 14:05:21 -08001290 if (klass == nullptr) {
1291 CHECK(self->IsExceptionPending()) << descriptor;
1292 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001293 }
Ian Rogers32427292014-11-19 14:05:21 -08001294 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001295 } else {
Ian Rogers32427292014-11-19 14:05:21 -08001296 // Handle as if this is the child PathClassLoader.
1297 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001298 StackHandleScope<3> hs(self);
1299 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
1300 // We need to get the DexPathList and loop through it.
1301 Handle<mirror::ArtField> cookie_field =
1302 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
1303 Handle<mirror::ArtField> dex_file_field =
1304 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07001305 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001306 mirror::Object* dex_path_list =
1307 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
1308 GetObject(class_loader.Get());
1309 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
1310 cookie_field.Get() != nullptr) {
1311 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1312 mirror::Object* dex_elements_obj =
1313 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1314 GetObject(dex_path_list);
1315 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1316 // at the mCookie which is a DexFile vector.
1317 if (dex_elements_obj != nullptr) {
1318 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
1319 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
1320 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
1321 mirror::Object* element = dex_elements->GetWithoutChecks(i);
1322 if (element == nullptr) {
1323 // Should never happen, fall back to java code to throw a NPE.
1324 break;
1325 }
1326 mirror::Object* dex_file = dex_file_field->GetObject(element);
1327 if (dex_file != nullptr) {
Andreas Gampe324b9bb2015-02-23 16:33:22 -08001328 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
1329 if (long_array == nullptr) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001330 // This should never happen so log a warning.
1331 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
1332 break;
1333 }
Andreas Gampe324b9bb2015-02-23 16:33:22 -08001334 int32_t long_array_size = long_array->GetLength();
1335 for (int32_t j = 0; j < long_array_size; ++j) {
1336 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
1337 long_array->GetWithoutChecks(j)));
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001338 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001339 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001340 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001341 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
1342 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001343 if (klass == nullptr) {
1344 CHECK(self->IsExceptionPending()) << descriptor;
1345 self->ClearException();
1346 return nullptr;
1347 }
1348 return klass;
1349 }
1350 }
1351 }
1352 }
1353 }
1354 }
Ian Rogers32427292014-11-19 14:05:21 -08001355 self->AssertNoPendingException();
1356 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001357 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001358}
1359
Ian Rogers98379392014-02-24 16:53:16 -08001360mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001361 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001362 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001363 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001364 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001365 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001366 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1367 // for primitive classes that aren't backed by dex files.
1368 return FindPrimitiveClass(descriptor[0]);
1369 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001370 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001371 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001372 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07001373 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001374 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001375 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001376 // Class is not yet loaded.
1377 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001378 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001379 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001380 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001381 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07001382 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001383 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07001384 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07001385 } else {
1386 // The boot class loader is searched ahead of the application class loader, failures are
1387 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
1388 // trigger the chaining with a proper stack trace.
1389 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001390 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07001391 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05001392 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001393 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001394 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001395 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
1396 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001397 if (cp_klass != nullptr) {
1398 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07001399 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001400
1401 if (Runtime::Current()->IsAotCompiler()) {
1402 // Oops, compile-time, can't run actual class-loader code.
1403 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
1404 self->SetException(pre_allocated);
1405 return nullptr;
1406 }
1407
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001408 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001409 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001410 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07001411 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07001412 {
1413 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001414 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1415 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07001416 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001417 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07001418 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07001419 }
Ian Rogers68b56852014-08-29 20:19:11 -07001420 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001421 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1422 WellKnownClasses::java_lang_ClassLoader_loadClass,
1423 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001424 }
Ian Rogers98379392014-02-24 16:53:16 -08001425 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001426 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07001427 return nullptr;
1428 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08001429 // broken loader - throw NPE to be compatible with Dalvik
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001430 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
1431 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07001432 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08001433 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001434 // success, return mirror::Class*
1435 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001436 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001437 }
Ian Rogers07140832014-09-30 15:43:59 -07001438 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001439}
1440
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001441mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001442 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001443 const DexFile& dex_file,
1444 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001445 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001446 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001447
Brian Carlstromaded5f72011-10-07 17:15:04 -07001448 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001449 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001450 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001451 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001452 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001453 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001454 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001455 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001456 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001457 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1458 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001459 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001460 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001461 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001462 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001463 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001464 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001465 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001466 }
1467
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001468 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001469 // Allocate a class with the status of not ready.
1470 // Interface object should get the right size here. Regular class will
1471 // figure out the right size later and be replaced with one of the right
1472 // size when the class becomes resolved.
1473 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001474 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001475 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001476 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07001477 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001478 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001479 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07001480 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001481 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001482 if (self->IsExceptionPending()) {
1483 // An exception occured during load, set status to erroneous while holding klass' lock in case
1484 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001485 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001486 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001487 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001488 return nullptr;
1489 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001490 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001491
Mathieu Chartier590fee92013-09-13 13:46:47 -07001492 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001493 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001494 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001495 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1496 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001497 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001498 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001499
Brian Carlstromaded5f72011-10-07 17:15:04 -07001500 // Finish loading (if necessary) by finding parents
1501 CHECK(!klass->IsLoaded());
1502 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1503 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001504 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001505 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001506 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001507 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001508 }
1509 CHECK(klass->IsLoaded());
1510 // Link the class (if necessary)
1511 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001512 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001513 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001514
1515 mirror::Class* new_class = nullptr;
1516 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001517 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001518 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001519 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001520 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001521 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001522 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07001523 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001524 CHECK(new_class != nullptr) << descriptor;
1525 CHECK(new_class->IsResolved()) << descriptor;
1526
1527 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001528
Sebastien Hertza8a697f2015-01-15 12:28:47 +01001529 // Instrumentation may have updated entrypoints for all methods of all
1530 // classes. However it could not update methods of this class while we
1531 // were loading it. Now the class is resolved, we can update entrypoints
1532 // as required by instrumentation.
1533 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
1534 // We must be in the kRunnable state to prevent instrumentation from
1535 // suspending all threads to update entrypoints while we are doing it
1536 // for this class.
1537 DCHECK_EQ(self->GetState(), kRunnable);
1538 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(new_class_h.Get());
1539 }
1540
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001541 /*
1542 * We send CLASS_PREPARE events to the debugger from here. The
1543 * definition of "preparation" is creating the static fields for a
1544 * class and initializing them to the standard default values, but not
1545 * executing any code (that comes later, during "initialization").
1546 *
1547 * We did the static preparation in LinkClass.
1548 *
1549 * The class has been prepared and resolved but possibly not yet verified
1550 * at this point.
1551 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001552 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001553
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001554 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001555}
1556
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001557uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
1558 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07001559 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001560 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07001561 size_t num_8 = 0;
1562 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001563 size_t num_32 = 0;
1564 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001565 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001566 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1567 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001568 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001569 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07001570 switch (c) {
1571 case 'L':
1572 case '[':
1573 num_ref++;
1574 break;
1575 case 'J':
1576 case 'D':
1577 num_64++;
1578 break;
1579 case 'I':
1580 case 'F':
1581 num_32++;
1582 break;
1583 case 'S':
1584 case 'C':
1585 num_16++;
1586 break;
1587 case 'B':
1588 case 'Z':
1589 num_8++;
1590 break;
1591 default:
1592 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08001593 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001594 }
1595 }
1596 }
Fred Shih37f05ef2014-07-16 18:38:08 -07001597 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001598}
1599
Ian Rogers97b52f82014-08-14 11:34:07 -07001600OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
1601 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001602 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001603 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
1604 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001605 *found = false;
1606 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001607 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001608 *found = true;
1609 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08001610}
1611
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001612static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
1613 uint32_t method_idx) {
1614 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07001615 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001616 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001617 ClassDataItemIterator it(dex_file, class_data);
1618 // Skip fields
1619 while (it.HasNextStaticField()) {
1620 it.Next();
1621 }
1622 while (it.HasNextInstanceField()) {
1623 it.Next();
1624 }
1625 // Process methods
1626 size_t class_def_method_index = 0;
1627 while (it.HasNextDirectMethod()) {
1628 if (it.GetMemberIndex() == method_idx) {
1629 return class_def_method_index;
1630 }
1631 class_def_method_index++;
1632 it.Next();
1633 }
1634 while (it.HasNextVirtualMethod()) {
1635 if (it.GetMemberIndex() == method_idx) {
1636 return class_def_method_index;
1637 }
1638 class_def_method_index++;
1639 it.Next();
1640 }
1641 DCHECK(!it.HasNext());
1642 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08001643 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001644}
1645
Ian Rogers97b52f82014-08-14 11:34:07 -07001646const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08001647 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001648 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001649 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08001650 size_t oat_method_index;
1651 if (method->IsStatic() || method->IsDirect()) {
1652 // Simple case where the oat method index was stashed at load time.
1653 oat_method_index = method->GetMethodIndex();
1654 } else {
1655 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1656 // by search for its position in the declared virtual methods.
1657 oat_method_index = declaring_class->NumDirectMethods();
1658 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001659 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001660 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07001661 // Check method index instead of identity in case of duplicate method definitions.
1662 if (method->GetDexMethodIndex() ==
1663 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001664 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001665 break;
1666 }
Ian Rogersf320b632012-03-13 18:47:47 -07001667 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001668 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001669 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
1670 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001671 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001672 DCHECK_EQ(oat_method_index,
1673 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001674 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001675 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07001676 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
1677 declaring_class->GetDexClassDefIndex(),
1678 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001679 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001680 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001681 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001682 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07001683}
1684
1685// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001686const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001687 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07001688 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001689 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07001690 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001691 bool found;
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001692 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1693 if (found) {
1694 auto* code = oat_method.GetQuickCode();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001695 if (code != nullptr) {
1696 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08001697 }
1698 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001699 jit::Jit* const jit = Runtime::Current()->GetJit();
1700 if (jit != nullptr) {
1701 auto* code = jit->GetCodeCache()->GetCodeFor(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001702 if (code != nullptr) {
1703 return code;
1704 }
1705 }
1706 if (method->IsNative()) {
1707 // No code and native? Use generic trampoline.
1708 return GetQuickGenericJniStub();
1709 }
1710 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07001711}
1712
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001713const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
1714 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
1715 return nullptr;
1716 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001717 bool found;
1718 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1719 if (found) {
1720 return oat_method.GetQuickCode();
1721 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001722 jit::Jit* jit = Runtime::Current()->GetJit();
1723 if (jit != nullptr) {
1724 auto* code = jit->GetCodeCache()->GetCodeFor(method);
1725 if (code != nullptr) {
1726 return code;
1727 }
1728 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001729 return nullptr;
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001730}
1731
Ian Rogersef7d42f2014-01-06 12:55:46 -08001732const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
1733 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001734 bool found;
1735 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
1736 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001737 return nullptr;
1738 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001739 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001740 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001741}
1742
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001743// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001744static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07001745 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08001746 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001747 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08001748 // May return true for native code, in the case of generic JNI
1749 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001750 return true;
1751 }
1752 // If interpreter mode is enabled, every method (except native and proxy) must
1753 // be run with interpreter.
1754 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
1755 !method->IsNative() && !method->IsProxyMethod();
1756}
1757
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001758void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08001759 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07001760 if (klass->NumDirectMethods() == 0) {
1761 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08001762 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001763 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001764 if (!runtime->IsStarted()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001765 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001766 return; // OAT file unavailable.
1767 }
Ian Rogers19846512012-02-24 11:42:47 -08001768 }
Alex Light64ad14d2014-08-19 14:23:13 -07001769
Mathieu Chartierf8322842014-05-16 10:59:25 -07001770 const DexFile& dex_file = klass->GetDexFile();
1771 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07001772 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07001773 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07001774 // There should always be class data if there were direct methods.
1775 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08001776 ClassDataItemIterator it(dex_file, class_data);
1777 // Skip fields
1778 while (it.HasNextStaticField()) {
1779 it.Next();
1780 }
1781 while (it.HasNextInstanceField()) {
1782 it.Next();
1783 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001784 bool has_oat_class;
1785 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1786 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07001787 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001788 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001789 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001790 if (!method->IsStatic()) {
1791 // Only update static methods.
1792 continue;
Ian Rogers19846512012-02-24 11:42:47 -08001793 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001794 const void* quick_code = nullptr;
1795 if (has_oat_class) {
1796 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001797 quick_code = oat_method.GetQuickCode();
1798 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001799 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001800 if (enter_interpreter) {
1801 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07001802 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001803 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001804 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08001805 } else {
1806 quick_code = GetQuickToInterpreterBridge();
1807 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001808 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001809 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08001810 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001811 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08001812}
1813
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001814void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07001815 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001816 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001817 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001818 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001819 // The following code only applies to a non-compiler runtime.
1820 return;
1821 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001822 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001823 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001824 if (oat_class != nullptr) {
1825 // Every kind of method should at least get an invoke stub from the oat_method.
1826 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001827 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001828 oat_method.LinkMethod(method.Get());
1829 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001830
Jeff Hao16743632013-05-08 10:59:04 -07001831 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001832 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08001833 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001834 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001835 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001836 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07001837 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001838 }
1839
Brian Carlstrom92827a52011-10-10 15:50:01 -07001840 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001841 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001842 return;
1843 }
Ian Rogers19846512012-02-24 11:42:47 -08001844
1845 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001846 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001847 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
1848 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001849 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001850 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001851 if (!method->IsNative()) {
1852 // Set entry point from compiled code if there's no code or in interpreter only mode.
1853 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001854 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001855 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001856 }
Ian Rogers0d6de042012-02-29 08:50:26 -08001857 }
jeffhao26c0a1a2012-01-17 16:28:33 -08001858
Ian Rogers62d6c772013-02-27 08:32:07 -08001859 if (method->IsNative()) {
1860 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001861 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07001862
1863 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001864 // We have a native method here without code. Then it should have either the generic JNI
1865 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
1866 // TODO: this doesn't handle all the cases where trampolines may be installed.
1867 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1868 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07001869 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001870 }
1871}
1872
Fred Shih37f05ef2014-07-16 18:38:08 -07001873
Fred Shih37f05ef2014-07-16 18:38:08 -07001874
Ian Rogers7b078e82014-09-10 14:44:24 -07001875void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07001876 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001877 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001878 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001879 CHECK(klass.Get() != nullptr);
1880 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001881 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001882 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001883 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001884
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001885 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07001886 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07001887 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001888 klass->SetAccessFlags(access_flags);
1889 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001890 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001891 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001892
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001893 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001894 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08001895 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001896
Ian Rogers13735952014-10-08 12:43:28 -07001897 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001898 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001899 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001900 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001901
Ian Rogers97b52f82014-08-14 11:34:07 -07001902
1903 bool has_oat_class = false;
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001904 if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001905 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1906 &has_oat_class);
1907 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001908 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07001909 }
1910 }
1911 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001912 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001913 }
1914}
1915
Ian Rogers7b078e82014-09-10 14:44:24 -07001916void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07001917 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001918 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001919 const OatFile::OatClass* oat_class) {
1920 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07001921 ClassDataItemIterator it(dex_file, class_data);
1922 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001923 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001924 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001925 CHECK(self->IsExceptionPending()); // OOME.
1926 return;
1927 }
1928 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07001929 }
1930 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001931 mirror::ObjectArray<mirror::ArtField>* fields =
1932 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001933 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001934 CHECK(self->IsExceptionPending()); // OOME.
1935 return;
1936 }
1937 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07001938 }
1939 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001940 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001941 StackHandleScope<1> hs(self);
1942 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001943 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001944 CHECK(self->IsExceptionPending()); // OOME.
1945 return;
1946 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001947 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07001948 LoadField(dex_file, it, klass, sfield);
1949 }
1950 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001951 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001952 StackHandleScope<1> hs(self);
1953 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001954 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001955 CHECK(self->IsExceptionPending()); // OOME.
1956 return;
1957 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001958 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07001959 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001960 }
1961
Ian Rogers0571d352011-11-03 19:51:38 -07001962 // Load methods.
1963 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001964 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07001965 mirror::ObjectArray<mirror::ArtMethod>* directs =
1966 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001967 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001968 CHECK(self->IsExceptionPending()); // OOME.
1969 return;
1970 }
1971 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001972 }
Ian Rogers0571d352011-11-03 19:51:38 -07001973 if (it.NumVirtualMethods() != 0) {
1974 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07001975 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
1976 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001977 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001978 CHECK(self->IsExceptionPending()); // OOME.
1979 return;
1980 }
1981 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001982 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001983 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07001984 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
1985 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001986 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001987 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001988 StackHandleScope<1> hs(self);
1989 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001990 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001991 CHECK(self->IsExceptionPending()); // OOME.
1992 return;
1993 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001994 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001995 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07001996 uint32_t it_method_index = it.GetMemberIndex();
1997 if (last_dex_method_index == it_method_index) {
1998 // duplicate case
1999 method->SetMethodIndex(last_class_def_method_index);
2000 } else {
2001 method->SetMethodIndex(class_def_method_index);
2002 last_dex_method_index = it_method_index;
2003 last_class_def_method_index = class_def_method_index;
2004 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002005 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002006 }
2007 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002008 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002009 StackHandleScope<1> hs(self);
2010 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002011 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002012 CHECK(self->IsExceptionPending()); // OOME.
2013 return;
2014 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002015 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002016 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002017 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002018 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002019 }
2020 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002021}
2022
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002023void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002024 Handle<mirror::Class> klass,
2025 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002026 uint32_t field_idx = it.GetMemberIndex();
2027 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002028 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002029 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002030}
2031
Brian Carlstromea46f952013-07-30 01:26:50 -07002032mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002033 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002034 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002035 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002036 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002037 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002038
Brian Carlstromea46f952013-07-30 01:26:50 -07002039 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002040 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002041 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002042 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002043 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002044 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002045
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002046 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002047 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002048 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002049 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002050
Ian Rogers19846512012-02-24 11:42:47 -08002051 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002052 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002053
Andreas Gampe51829322014-08-25 15:05:04 -07002054 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002055
Ian Rogersdfb325e2013-10-30 01:00:44 -07002056 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002057 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002058 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2059 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002060 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002061 klass->SetFinalizable();
2062 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002063 std::string temp;
2064 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002065 // The Enum class declares a "final" finalize() method to prevent subclasses from
2066 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2067 // subclasses, so we exclude it here.
2068 // We also want to avoid setting the flag on Object, where we know that finalize() is
2069 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002070 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2071 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002072 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002073 }
2074 }
2075 }
2076 } else if (method_name[0] == '<') {
2077 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002078 bool is_init = (strcmp("<init>", method_name) == 0);
2079 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002080 if (UNLIKELY(!is_init && !is_clinit)) {
2081 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2082 } else {
2083 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2084 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002085 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002086 access_flags |= kAccConstructor;
2087 }
2088 }
2089 }
2090 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002091
Mathieu Chartier66f19252012-09-18 08:57:04 -07002092 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002093}
2094
Ian Rogers7b078e82014-09-10 14:44:24 -07002095void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002096 StackHandleScope<1> hs(self);
2097 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002098 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2099 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002100 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002101}
2102
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002103void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002104 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002105 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002106 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002107 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002108}
2109
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002110bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002111 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002112 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002113 mirror::DexCache* dex_cache = GetDexCache(i);
2114 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002115 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002116 }
2117 }
2118 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002119}
2120
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002121bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002122 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002123 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002124}
2125
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002126void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002127 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002128 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002129 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002130 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2131 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002132 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002133 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002134 if (log_new_dex_caches_roots_) {
2135 // TODO: This is not safe if we can remove dex caches.
2136 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2137 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002138}
2139
Brian Carlstromaded5f72011-10-07 17:15:04 -07002140void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002141 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002142 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002143 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002144 if (IsDexFileRegisteredLocked(dex_file)) {
2145 return;
2146 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002147 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002148 // Don't alloc while holding the lock, since allocation may need to
2149 // suspend all threads and another thread may need the dex_lock_ to
2150 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002151 StackHandleScope<1> hs(self);
2152 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002153 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2154 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002155 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002156 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002157 if (IsDexFileRegisteredLocked(dex_file)) {
2158 return;
2159 }
2160 RegisterDexFileLocked(dex_file, dex_cache);
2161 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002162}
2163
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002164void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002165 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002166 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002167 RegisterDexFileLocked(dex_file, dex_cache);
2168}
2169
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002170mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002171 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002172 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002173 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002174 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002175 if (dex_cache->GetDexFile() == &dex_file) {
2176 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002177 }
2178 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002179 // Search matching by location name.
2180 std::string location(dex_file.GetLocation());
2181 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002182 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002183 if (dex_cache->GetDexFile()->GetLocation() == location) {
2184 return dex_cache;
2185 }
2186 }
2187 // Failure, dump diagnostic and abort.
2188 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002189 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002190 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2191 }
2192 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002193 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002194}
2195
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002196void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002197 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08002198 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002199 mirror::DexCache* dex_cache = GetDexCache(i);
2200 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08002201 }
2202}
2203
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002204mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002205 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002206 if (UNLIKELY(klass == nullptr)) {
2207 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002208 }
2209 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002210}
2211
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002212mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2213 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002214 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07002215 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002216 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002217 StackHandleScope<1> hs(self);
2218 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002219 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002220 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
2221 h_class->SetPrimitiveType(type);
2222 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002223 const char* descriptor = Primitive::Descriptor(type);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002224 mirror::Class* existing = InsertClass(descriptor, h_class.Get(),
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002225 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002226 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002227 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07002228}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002229
Brian Carlstrombe977852011-07-19 14:54:54 -07002230// Create an array class (i.e. the class object for the array, not the
2231// array itself). "descriptor" looks like "[C" or "[[[[B" or
2232// "[Ljava/lang/String;".
2233//
2234// If "descriptor" refers to an array of primitives, look up the
2235// primitive type's internally-generated class object.
2236//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002237// "class_loader" is the class loader of the class that's referring to
2238// us. It's used to ensure that we're looking for the element type in
2239// the right context. It does NOT become the class loader for the
2240// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002241//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002242// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002243mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002244 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002245 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002246 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002247 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002248 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
2249 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002250 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002251 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002252 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002253 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
2254 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002255 if (component_type.Get() == nullptr) {
2256 DCHECK(self->IsExceptionPending());
2257 return nullptr;
2258 } else {
2259 self->ClearException();
2260 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002261 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002262 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2263 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2264 return nullptr;
2265 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002266 // See if the component type is already loaded. Array classes are
2267 // always associated with the class loader of their underlying
2268 // element type -- an array of Strings goes with the loader for
2269 // java/lang/String -- so we need to look for it there. (The
2270 // caller should have checked for the existence of the class
2271 // before calling here, but they did so with *their* class loader,
2272 // not the component type's loader.)
2273 //
2274 // If we find it, the caller adds "loader" to the class' initiating
2275 // loader list, which should prevent us from going through this again.
2276 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002277 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002278 // are the same, because our caller (FindClass) just did the
2279 // lookup. (Even if we get this wrong we still have correct behavior,
2280 // because we effectively do this lookup again when we add the new
2281 // class to the hash table --- necessary because of possible races with
2282 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002283 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002284 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002285 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002286 return new_class;
2287 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002288 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002289
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002290 // Fill out the fields in the Class.
2291 //
2292 // It is possible to execute some methods against arrays, because
2293 // all arrays are subclasses of java_lang_Object_, so we need to set
2294 // up a vtable. We can just point at the one in java_lang_Object_.
2295 //
2296 // Array classes are simple enough that we don't need to do a full
2297 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002298 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002299 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002300 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002301 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002302 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002303 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002304 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002305 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002306 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002307 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002308 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002309 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002310 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002311 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002312 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002313 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002314 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002315 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002316 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002317 }
2318 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002319 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002320 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002321 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002322 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002323 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002324 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002325 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002326 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002327 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002328 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002329 new_class->SetSuperClass(java_lang_Object);
2330 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002331 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002332 new_class->SetClassLoader(component_type->GetClassLoader());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002333 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002334 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002335 StackHandleScope<mirror::Class::kImtSize> hs2(self,
2336 Runtime::Current()->GetImtUnimplementedMethod());
2337 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002338 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002339 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002340 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002341 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002342
2343
2344 // All arrays have java/lang/Cloneable and java/io/Serializable as
2345 // interfaces. We need to set that up here, so that stuff like
2346 // "instanceof" works right.
2347 //
2348 // Note: The GC could run during the call to FindSystemClass,
2349 // so we need to make sure the class object is GC-valid while we're in
2350 // there. Do this by clearing the interface list so the GC will just
2351 // think that the entries are null.
2352
2353
2354 // Use the single, global copies of "interfaces" and "iftable"
2355 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002356 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002357 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002358 CHECK(array_iftable != nullptr);
2359 new_class->SetIfTable(array_iftable);
2360 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002361
Elliott Hughes00626c22013-06-14 15:04:14 -07002362 // Inherit access flags from the component type.
2363 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2364 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2365 access_flags &= kAccJavaFlagsMask;
2366 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002367 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002368 access_flags |= kAccAbstract | kAccFinal;
2369 access_flags &= ~kAccInterface;
2370
2371 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002372
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002373 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002374 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002375 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002376 }
2377 // Another thread must have loaded the class after we
2378 // started but before we finished. Abandon what we've
2379 // done.
2380 //
2381 // (Yes, this happens.)
2382
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002383 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002384}
2385
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002386mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002387 switch (type) {
2388 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002389 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002390 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002391 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002392 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002393 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002394 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002395 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002396 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002397 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002398 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002399 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002400 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002401 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002402 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002403 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002404 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002405 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002406 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002407 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002408 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002409 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002410 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002411 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002412}
2413
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002414mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2415 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002416 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002417 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002418 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002419 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08002420 source += " from ";
2421 source += dex_cache->GetLocation()->ToModifiedUtf8();
2422 }
2423 LOG(INFO) << "Loaded class " << descriptor << source;
2424 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002425 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002426 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002427 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002428 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002429 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002430 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002431 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002432 // Check a class loaded with the system class loader matches one in the image if the class
2433 // is in the image.
2434 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002435 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002436 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002437 }
2438 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002439 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002440 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002441 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002442 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002443 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002444 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002445}
2446
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002447mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
2448 size_t hash) {
2449 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002450 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
2451 hash);
2452 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002453 CHECK(klass->IsProxyClass());
2454 return nullptr;
2455 }
2456
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002457 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002458 CHECK_NE(existing, klass) << descriptor;
2459 CHECK(!existing->IsResolved()) << descriptor;
2460 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
2461
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002462 CHECK(!klass->IsTemp()) << descriptor;
2463 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
2464 dex_cache_image_class_lookup_required_) {
2465 // Check a class loaded with the system class loader matches one in the image if the class
2466 // is in the image.
2467 existing = LookupClassFromImage(descriptor);
2468 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002469 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002470 }
2471 }
2472 VerifyObject(klass);
2473
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002474 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002475 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002476 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002477 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002478 }
2479
2480 return existing;
2481}
2482
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002483bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002484 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002485 auto pair = std::make_pair(descriptor, class_loader);
2486 auto it = class_table_.Find(pair);
2487 if (it != class_table_.end()) {
2488 class_table_.Erase(it);
2489 return true;
2490 }
2491 it = pre_zygote_class_table_.Find(pair);
2492 if (it != pre_zygote_class_table_.end()) {
2493 pre_zygote_class_table_.Erase(it);
2494 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08002495 }
2496 return false;
2497}
2498
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002499mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002500 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002501 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002502 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002503 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002504 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002505 return result;
2506 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07002507 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002508 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
2509 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002510 } else {
2511 // Lookup failed but need to search dex_caches_.
2512 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002513 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002514 InsertClass(descriptor, result, hash);
2515 } else {
2516 // Searching the image dex files/caches failed, we don't want to get into this situation
2517 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2518 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07002519 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002520 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2521 MoveImageClassesToClassTable();
2522 }
2523 }
2524 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002525 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002526}
2527
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002528mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002529 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002530 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002531 auto descriptor_pair = std::make_pair(descriptor, class_loader);
2532 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
2533 if (it == pre_zygote_class_table_.end()) {
2534 it = class_table_.FindWithHash(descriptor_pair, hash);
2535 if (it == class_table_.end()) {
2536 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07002537 }
2538 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002539 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002540}
2541
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002542static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
2543 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2544 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002545 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002546 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2547 return root->AsObjectArray<mirror::DexCache>();
2548}
2549
2550void ClassLinker::MoveImageClassesToClassTable() {
2551 Thread* self = Thread::Current();
2552 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2553 if (!dex_cache_image_class_lookup_required_) {
2554 return; // All dex cache classes are already in the class table.
2555 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002556 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002557 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002558 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002559 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2560 mirror::DexCache* dex_cache = dex_caches->Get(i);
2561 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
2562 for (int32_t j = 0; j < types->GetLength(); j++) {
2563 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002564 if (klass != nullptr) {
2565 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002566 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002567 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002568 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
2569 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002570 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002571 << PrettyClassAndClassLoader(klass);
2572 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002573 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002574 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002575 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002576 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002577 }
2578 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002579 }
2580 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002581 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002582}
2583
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002584void ClassLinker::MoveClassTableToPreZygote() {
2585 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2586 DCHECK(pre_zygote_class_table_.Empty());
2587 pre_zygote_class_table_ = std::move(class_table_);
2588 class_table_.Clear();
2589}
2590
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002591mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002592 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002593 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2594 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
2595 mirror::DexCache* dex_cache = dex_caches->Get(i);
2596 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00002597 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002598 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002599 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002600 const DexFile::TypeId* type_id =
2601 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002602 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002603 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
2604 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002605 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002606 return klass;
2607 }
2608 }
2609 }
2610 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002611 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002612}
2613
2614void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
2615 result.clear();
2616 if (dex_cache_image_class_lookup_required_) {
2617 MoveImageClassesToClassTable();
2618 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002619 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2620 while (true) {
2621 auto it = class_table_.Find(descriptor);
2622 if (it == class_table_.end()) {
2623 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002624 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002625 result.push_back(it->Read());
2626 class_table_.Erase(it);
2627 }
2628 for (mirror::Class* k : result) {
2629 class_table_.Insert(GcRoot<mirror::Class>(k));
2630 }
2631 size_t pre_zygote_start = result.size();
2632 // Now handle the pre zygote table.
2633 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
2634 // called from the debugger.
2635 while (true) {
2636 auto it = pre_zygote_class_table_.Find(descriptor);
2637 if (it == pre_zygote_class_table_.end()) {
2638 break;
2639 }
2640 result.push_back(it->Read());
2641 pre_zygote_class_table_.Erase(it);
2642 }
2643 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
2644 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002645 }
2646}
2647
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002648void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002649 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002650 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08002651
Ian Rogers9ffb0392012-09-10 11:56:50 -07002652 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002653 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07002654 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07002655 return;
2656 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002657 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002658 return;
2659 }
jeffhao98eacac2011-09-14 16:11:53 -07002660
Ian Rogers9ffb0392012-09-10 11:56:50 -07002661 // The class might already be erroneous, for example at compile time if we attempted to verify
2662 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002663 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002664 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002665 return;
2666 }
2667
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002668 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002669 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002670 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002671 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002672 << PrettyClass(klass.Get());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002673 CHECK(!Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002674 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002675 }
jeffhao98eacac2011-09-14 16:11:53 -07002676
Jeff Hao4a200f52014-04-01 14:58:49 -07002677 // Skip verification if disabled.
2678 if (!Runtime::Current()->IsVerificationEnabled()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002679 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07002680 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07002681 return;
2682 }
2683
Ian Rogers9ffb0392012-09-10 11:56:50 -07002684 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002685 StackHandleScope<2> hs(self);
2686 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002687 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07002688 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002689 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002690
2691 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002692 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002693 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002694 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07002695 std::string error_msg(
2696 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
2697 PrettyDescriptor(klass.Get()).c_str(),
2698 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08002699 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002700 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002701 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002702 self->ClearException();
2703 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002704 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
2705 if (cause.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002706 self->GetException()->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002707 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08002708 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002709 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00002710 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
2711 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002712 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002713 return;
2714 }
2715 }
2716
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002717 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07002718 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002719 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002720 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002721 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002722 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002723 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002724 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002725 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
2726 PrettyDescriptor(klass.Get()).c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002727 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07002728 return;
2729 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002730 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08002731 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07002732 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002733 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002734 Runtime::Current()->IsAotCompiler(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002735 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002736 }
2737 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07002738 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002739 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07002740 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2741 << " because: " << error_msg;
2742 }
Ian Rogers1f539342012-10-03 21:09:42 -07002743 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002744 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002745 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002746 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002747 // Even though there were no verifier failures we need to respect whether the super-class
2748 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002749 if (super.Get() == nullptr || super->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002750 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002751 } else {
2752 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002753 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002754 // Pretend a soft failure occured so that we don't consider the class verified below.
2755 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002756 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002757 } else {
2758 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
2759 // Soft failures at compile time should be retried at runtime. Soft
2760 // failures at runtime will be handled by slow paths in the generated
2761 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002762 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002763 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002764 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002765 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002766 // As this is a fake verified status, make sure the methods are _not_ marked preverified
2767 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07002768 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002769 }
2770 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07002771 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002772 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08002773 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2774 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002775 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002776 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002777 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002778 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002779 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002780 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002781 // Let the interpreter know it by setting the kAccPreverified flag onto each
2782 // method.
2783 // Note: we're going here during compilation and at runtime. When we set the
2784 // kAccPreverified flag when compiling image classes, the flag is recorded
2785 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07002786 EnsurePreverifiedMethods(klass);
2787 }
2788}
2789
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002790void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002791 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002792 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07002793 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002794 }
jeffhao98eacac2011-09-14 16:11:53 -07002795}
2796
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002797bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
2798 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002799 // If we're compiling, we can only verify the class using the oat file if
2800 // we are not compiling the image or if the class we're verifying is not part of
2801 // the app. In other words, we will only check for preverification of bootclasspath
2802 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002803 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002804 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002805 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002806 return false;
2807 }
2808 // We are compiling an app (not the image).
2809
2810 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002811 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002812 return false;
2813 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002814 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002815
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002816 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002817 // In case we run without an image there won't be a backing oat file.
2818 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07002819 return false;
2820 }
2821
Andreas Gampe76bd8802014-12-10 16:43:58 -08002822 // We may be running with a preopted oat file but without image. In this case,
2823 // we don't skip verification of preverified classes to ensure we initialize
2824 // dex caches with all types resolved during verification.
2825 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
2826 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
2827 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
2828 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002829 if (!Runtime::Current()->IsAotCompiler() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08002830 !Runtime::Current()->GetHeap()->HasImageSpace() &&
2831 klass->GetClassLoader() != nullptr) {
2832 return false;
2833 }
2834
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002835 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002836 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002837 if (oat_file_class_status == mirror::Class::kStatusVerified ||
2838 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002839 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002840 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002841 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07002842 // Compile time verification failed with a soft error. Compile time verification can fail
2843 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08002844 // class ... {
2845 // Foo x;
2846 // .... () {
2847 // if (...) {
2848 // v1 gets assigned a type of resolved class Foo
2849 // } else {
2850 // v1 gets assigned a type of unresolved class Bar
2851 // }
2852 // iput x = v1
2853 // } }
2854 // when we merge v1 following the if-the-else it results in Conflict
2855 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2856 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2857 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2858 // at compile time).
2859 return false;
2860 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002861 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07002862 // Compile time verification failed with a hard error. This is caused by invalid instructions
2863 // in the class. These errors are unrecoverable.
2864 return false;
2865 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002866 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002867 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2868 // not loading the class.
2869 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2870 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002871 return false;
2872 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002873 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002874 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002875 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07002876 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08002877 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002878}
2879
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002880void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002881 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002882 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2883 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2884 }
2885 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2886 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2887 }
2888}
2889
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002890void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07002891 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002892 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2893 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002894 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002895 return; // native or abstract method
2896 }
2897 if (code_item->tries_size_ == 0) {
2898 return; // nothing to process
2899 }
Ian Rogers13735952014-10-08 12:43:28 -07002900 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002901 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2902 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2903 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2904 CatchHandlerIterator iterator(handlers_ptr);
2905 for (; iterator.HasNext(); iterator.Next()) {
2906 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2907 // unresolved exception types will be ignored by exception delivery
2908 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002909 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002910 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002911 DCHECK(Thread::Current()->IsExceptionPending());
2912 Thread::Current()->ClearException();
2913 }
2914 }
2915 }
2916 handlers_ptr = iterator.EndDataPointer();
2917 }
2918}
2919
Brian Carlstromea46f952013-07-30 01:26:50 -07002920static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002921static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
2922 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08002923
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07002924mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07002925 jobjectArray interfaces, jobject loader,
2926 jobjectArray methods, jobjectArray throws) {
2927 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002928 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002929 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002930 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002931 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002932 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002933 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002934 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002935 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002936 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07002937 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
2938 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002939 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08002940 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002941 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002942 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002943 klass->SetDexCache(proxy_class->GetDexCache());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002944 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08002945
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002946 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07002947 {
2948 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002949 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002950 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002951 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002952 }
2953 klass->SetSFields(sfields);
2954 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002955 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
2956 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002957 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
2958 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002959 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002960 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002961 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002962 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002963 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002964 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002965 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
2966 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002967 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
2968 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002969 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002970 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002971 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002972 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002973 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002974 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002975 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002976
Ian Rogers466bb252011-10-14 03:29:56 -07002977 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07002978 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002979 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002980 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002981 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002982 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002983 }
2984 klass->SetDirectMethods(directs);
2985 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002986 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002987 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002988 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002989 }
2990 klass->SetDirectMethod(0, constructor);
2991 }
Jesse Wilson95caa792011-10-12 18:14:17 -04002992
Mathieu Chartier590fee92013-09-13 13:46:47 -07002993 // Create virtual method using specified prototypes.
2994 size_t num_virtual_methods =
2995 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07002996 {
Brian Carlstromf3632832014-05-20 15:36:53 -07002997 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
2998 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002999 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003000 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003001 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003002 }
3003 klass->SetVirtualMethods(virtuals);
3004 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003005 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003006 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003007 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3008 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003009 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003010 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003011 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003012 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003013 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003014 }
3015 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003016 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003017
3018 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003019 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003020 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003021
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003022 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3023 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003024 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003025 // Must hold lock on object when resolved.
3026 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003027 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003028 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003029 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003030 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003031 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003032 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003033 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003034 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003035
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003036 CHECK(klass->IsRetired());
3037 CHECK_NE(klass.Get(), new_class);
3038 klass.Assign(new_class);
3039
3040 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003041 interfaces_sfield->SetObject<false>(klass.Get(),
3042 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003043 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003044 throws_sfield->SetObject<false>(klass.Get(),
3045 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003046
3047 {
3048 // Lock on klass is released. Lock new class object.
3049 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003050 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003051 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003052
3053 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003054 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003055 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003056 CheckProxyConstructor(klass->GetDirectMethod(0));
3057 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003058 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003059 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3060 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003061 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3062 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003063 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003064 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003065
Mathieu Chartier590fee92013-09-13 13:46:47 -07003066 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003067 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003068 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003069 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3070
3071 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003072 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003073 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003074
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003075 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003076 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003077 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003078 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003079 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003080 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3081 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003082 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003083 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003084}
3085
Ian Rogersef7d42f2014-01-06 12:55:46 -08003086std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003087 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003088 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003089 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003090 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3091}
3092
Ian Rogersef7d42f2014-01-06 12:55:46 -08003093mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3094 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003095 DCHECK(proxy_class->IsProxyClass());
3096 DCHECK(proxy_method->IsProxyMethod());
3097 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003098 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003099 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003100 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003101 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003102 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003103 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003104 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003105 break;
3106 }
3107 }
3108 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003109 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003110 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003111 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003112 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003113 return resolved_method;
3114}
3115
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003116
Brian Carlstromea46f952013-07-30 01:26:50 -07003117mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003118 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003119 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003120 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003121 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003122 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003123 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3124 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003125 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3126 // constructor method.
3127 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3128 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003129 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3130 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003131 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3132 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003133 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003134 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003135 }
Ian Rogers466bb252011-10-14 03:29:56 -07003136 // Make this constructor public and fix the class to be our Proxy version
3137 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003138 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003139 return constructor;
3140}
3141
Brian Carlstromea46f952013-07-30 01:26:50 -07003142static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003143 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003144 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003145 CHECK_STREQ(constructor->GetName(), "<init>");
3146 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3147 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003148 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003149}
3150
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003151mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003152 Handle<mirror::Class> klass,
3153 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003154 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3155 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003156 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003157 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003158 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003159 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003160 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003161 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003162 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003163 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003164 }
Ian Rogers466bb252011-10-14 03:29:56 -07003165
3166 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3167 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003168 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003169 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003170
Ian Rogers466bb252011-10-14 03:29:56 -07003171 // At runtime the method looks like a reference and argument saving method, clone the code
3172 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003173 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003174 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003175
Ian Rogersc2b44472011-12-14 21:17:17 -08003176 return method;
3177}
Jesse Wilson95caa792011-10-12 18:14:17 -04003178
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003179static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3180 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003181 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003182 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003183 CHECK(!prototype->IsFinal());
3184 CHECK(method->IsFinal());
3185 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003186
3187 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3188 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07003189 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
3190 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08003191 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3192
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003193 CHECK_STREQ(method->GetName(), prototype->GetName());
3194 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003195 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07003196 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04003197}
3198
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003199static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3200 bool can_init_parents)
3201 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003202 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003203 return true;
3204 }
3205 if (!can_init_statics) {
3206 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07003207 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003208 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003209 return false;
3210 }
3211 // Check if there are encoded static values needing initialization.
3212 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003213 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003214 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003215 if (dex_class_def->static_values_off_ != 0) {
3216 return false;
3217 }
3218 }
3219 }
3220 if (!klass->IsInterface() && klass->HasSuperClass()) {
3221 mirror::Class* super_class = klass->GetSuperClass();
3222 if (!can_init_parents && !super_class->IsInitialized()) {
3223 return false;
3224 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003225 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003226 return false;
3227 }
3228 }
3229 }
3230 return true;
3231}
3232
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003233bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07003234 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003235 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3236
3237 // Are we already initialized and therefore done?
3238 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3239 // an initialized class will never change its state.
3240 if (klass->IsInitialized()) {
3241 return true;
3242 }
3243
3244 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003245 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003246 return false;
3247 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003248
Ian Rogers7b078e82014-09-10 14:44:24 -07003249 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003250 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003251 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003252 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003253
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003254 // Re-check under the lock in case another thread initialized ahead of us.
3255 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003256 return true;
3257 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003258
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003259 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003260 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003261 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003262 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003263 return false;
3264 }
3265
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003266 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003267
3268 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003269 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003270 if (!klass->IsVerified()) {
3271 // We failed to verify, expect either the klass to be erroneous or verification failed at
3272 // compile time.
3273 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003274 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003275 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003276 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003277 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003278 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003279 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003280 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07003281 } else {
3282 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003283 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003284 }
3285
Brian Carlstromd1422f82011-09-28 11:37:09 -07003286 // If the class is kStatusInitializing, either this thread is
3287 // initializing higher up the stack or another thread has beat us
3288 // to initializing and we need to wait. Either way, this
3289 // invocation of InitializeClass will not be responsible for
3290 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003291 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07003292 // Could have got an exception during verification.
3293 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003294 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003295 return false;
3296 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003297 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003298 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003299 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003300 return true;
3301 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003302 // No. That's fine. Wait for another thread to finish initializing.
3303 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003304 }
3305
3306 if (!ValidateSuperClassDescriptors(klass)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003307 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003308 return false;
3309 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003310 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003311
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003312 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003313
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003314 // From here out other threads may observe that we're initializing and so changes of state
3315 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003316 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003317 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003318
3319 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003320 }
3321
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003322 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003323 if (!klass->IsInterface() && klass->HasSuperClass()) {
3324 mirror::Class* super_class = klass->GetSuperClass();
3325 if (!super_class->IsInitialized()) {
3326 CHECK(!super_class->IsInterface());
3327 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003328 StackHandleScope<1> hs(self);
3329 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07003330 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003331 if (!super_initialized) {
3332 // The super class was verified ahead of entering initializing, we should only be here if
3333 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003334 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003335 << "Super class initialization failed for "
3336 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003337 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003338 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003339 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003340 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003341 // Initialization failed because the super-class is erroneous.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003342 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003343 return false;
3344 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003345 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003346 }
3347
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003348 const size_t num_static_fields = klass->NumStaticFields();
3349 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003350 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003351 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003352 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07003353 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003354 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003355 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003356
3357 // Eagerly fill in static fields so that the we don't have to do as many expensive
3358 // Class::FindStaticField in ResolveField.
3359 for (size_t i = 0; i < num_static_fields; ++i) {
3360 mirror::ArtField* field = klass->GetStaticField(i);
3361 const uint32_t field_idx = field->GetDexFieldIndex();
3362 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
3363 if (resolved_field == nullptr) {
3364 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07003365 } else {
3366 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003367 }
3368 }
3369
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003370 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
3371 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07003372 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003373 ClassDataItemIterator field_it(dex_file, class_data);
3374 if (value_it.HasNext()) {
3375 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003376 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003377 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003378 StackHandleScope<1> hs2(self);
3379 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003380 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003381 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003382 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003383 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003384 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003385 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003386 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003387 }
3388 }
3389 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003390
Ian Rogersd91d6d62013-09-25 20:26:14 -07003391 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003392 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003393 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003394 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003395 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003396 }
3397
Ian Rogers7b078e82014-09-10 14:44:24 -07003398 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003399 uint64_t t1 = NanoTime();
3400
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003401 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003402 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003403 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003404
3405 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003406 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003407 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003408 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003409 } else if (Runtime::Current()->IsTransactionAborted()) {
3410 // The exception thrown when the transaction aborted has been caught and cleared
3411 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01003412 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
3413 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02003414 Runtime::Current()->ThrowTransactionAbortError(self);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003415 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003416 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003417 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003418 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3419 RuntimeStats* thread_stats = self->GetStats();
3420 ++global_stats->class_init_count;
3421 ++thread_stats->class_init_count;
3422 global_stats->class_init_time_ns += (t1 - t0);
3423 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003424 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003425 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003426 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003427 std::string temp;
3428 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003429 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003430 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003431 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003432 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003433 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003434 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003435 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003436}
3437
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003438bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003439 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003440 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003441 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003442 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003443 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08003444 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003445
3446 // When we wake up, repeat the test for init-in-progress. If
3447 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07003448 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003449 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003450 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003451 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003452 return false;
3453 }
3454 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003455 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003456 continue;
3457 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003458 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
3459 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003460 // Compile time initialization failed.
3461 return false;
3462 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003463 if (klass->IsErroneous()) {
3464 // The caller wants an exception, but it was thrown in a
3465 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003466 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003467 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003468 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003469 return false;
3470 }
3471 if (klass->IsInitialized()) {
3472 return true;
3473 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003474 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003475 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003476 }
Ian Rogers07140832014-09-30 15:43:59 -07003477 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003478}
3479
Ian Rogersb5fb2072014-12-02 17:22:02 -08003480static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
3481 Handle<mirror::ArtMethod> method1,
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003482 Handle<mirror::ArtMethod> method2,
3483 std::string* error_msg)
Ian Rogersb5fb2072014-12-02 17:22:02 -08003484 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3485 {
3486 StackHandleScope<1> hs(self);
3487 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
Vladimir Marko862f43c2015-02-10 18:22:57 +00003488 mirror::Class* other_return_type = method2->GetReturnType();
3489 // NOTE: return_type.Get() must be sequenced after method2->GetReturnType().
3490 if (UNLIKELY(other_return_type != return_type.Get())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003491 *error_msg = StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
3492 PrettyClassAndClassLoader(return_type.Get()).c_str(),
3493 return_type.Get(),
3494 PrettyClassAndClassLoader(other_return_type).c_str(),
3495 other_return_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003496 return false;
3497 }
3498 }
3499 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
3500 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
3501 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003502 if (types2 != nullptr && types2->Size() != 0) {
3503 *error_msg = StringPrintf("Type list mismatch with %s",
3504 PrettyMethod(method2.Get(), true).c_str());
3505 return false;
3506 }
3507 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003508 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003509 if (types1->Size() != 0) {
3510 *error_msg = StringPrintf("Type list mismatch with %s",
3511 PrettyMethod(method2.Get(), true).c_str());
3512 return false;
3513 }
3514 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003515 }
3516 uint32_t num_types = types1->Size();
3517 if (UNLIKELY(num_types != types2->Size())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003518 *error_msg = StringPrintf("Type list mismatch with %s",
3519 PrettyMethod(method2.Get(), true).c_str());
Ian Rogersb5fb2072014-12-02 17:22:02 -08003520 return false;
3521 }
3522 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00003523 StackHandleScope<1> hs(self);
3524 Handle<mirror::Class> param_type(hs.NewHandle(
3525 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true)));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003526 mirror::Class* other_param_type =
3527 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
Vladimir Marko862f43c2015-02-10 18:22:57 +00003528 // NOTE: param_type.Get() must be sequenced after method2->GetClassFromTypeIndex(...).
3529 if (UNLIKELY(param_type.Get() != other_param_type)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003530 *error_msg = StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
3531 i,
3532 PrettyClassAndClassLoader(param_type.Get()).c_str(),
3533 param_type.Get(),
3534 PrettyClassAndClassLoader(other_param_type).c_str(),
3535 other_param_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003536 return false;
3537 }
3538 }
3539 return true;
3540}
3541
3542
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003543bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003544 if (klass->IsInterface()) {
3545 return true;
3546 }
Ian Rogers151f2212014-05-06 11:27:27 -07003547 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07003548 Thread* self = Thread::Current();
3549 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003550 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
3551 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003552 if (klass->HasSuperClass() &&
3553 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003554 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003555 h_m.Assign(klass->GetVTableEntry(i));
3556 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003557 if (h_m.Get() != super_h_m.Get()) {
3558 std::string error_msg;
3559 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3560 ThrowLinkageError(klass.Get(),
3561 "Class %s method %s resolves differently in superclass %s: %s",
3562 PrettyDescriptor(klass.Get()).c_str(),
3563 PrettyMethod(h_m.Get()).c_str(),
3564 PrettyDescriptor(klass->GetSuperClass()).c_str(),
3565 error_msg.c_str());
3566 return false;
3567 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003568 }
3569 }
3570 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003571 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07003572 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
3573 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
3574 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003575 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
3576 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003577 if (h_m.Get() != super_h_m.Get()) {
3578 std::string error_msg;
3579 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3580 ThrowLinkageError(klass.Get(),
3581 "Class %s method %s resolves differently in interface %s: %s",
3582 PrettyDescriptor(klass.Get()).c_str(),
3583 PrettyMethod(h_m.Get()).c_str(),
3584 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str(),
3585 error_msg.c_str());
3586 return false;
3587 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003588 }
3589 }
3590 }
3591 }
3592 return true;
3593}
3594
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003595bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
3596 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003597 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003598 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003599 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003600 return true;
3601 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003602 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003603 if (!success) {
3604 if (can_init_fields && can_init_parents) {
3605 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
3606 }
3607 } else {
3608 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08003609 }
3610 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003611}
3612
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003613void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
3614 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
3615 if (fields != nullptr) {
3616 for (int index = 0; index < fields->GetLength(); index ++) {
3617 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
3618 fields->Get(index)->SetDeclaringClass(new_class);
3619 }
3620 }
3621 }
3622
3623 fields = new_class->GetSFields();
3624 if (fields != nullptr) {
3625 for (int index = 0; index < fields->GetLength(); index ++) {
3626 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
3627 fields->Get(index)->SetDeclaringClass(new_class);
3628 }
3629 }
3630 }
3631
3632 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
3633 if (methods != nullptr) {
3634 for (int index = 0; index < methods->GetLength(); index ++) {
3635 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3636 methods->Get(index)->SetDeclaringClass(new_class);
3637 }
3638 }
3639 }
3640
3641 methods = new_class->GetVirtualMethods();
3642 if (methods != nullptr) {
3643 for (int index = 0; index < methods->GetLength(); index ++) {
3644 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3645 methods->Get(index)->SetDeclaringClass(new_class);
3646 }
3647 }
3648 }
3649}
3650
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003651bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
3652 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003653 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003654 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003655
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003656 if (!LinkSuperClass(klass)) {
3657 return false;
3658 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003659 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
3660 self, Runtime::Current()->GetImtUnimplementedMethod());
3661 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003662 return false;
3663 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003664 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003665 return false;
3666 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003667 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07003668 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003669 return false;
3670 }
3671 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003672 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003673
3674 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
3675 // We don't need to retire this class as it has no embedded tables or it was created the
3676 // correct size during class linker initialization.
3677 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
3678
3679 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003680 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003681 }
3682
3683 // This will notify waiters on klass that saw the not yet resolved
3684 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003685 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003686 *new_class = klass.Get();
3687 } else {
3688 CHECK(!klass->IsResolved());
3689 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003690 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003691 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003692 CHECK(self->IsExceptionPending()); // Expect an OOME.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003693 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003694 return false;
3695 }
3696
3697 CHECK_EQ((*new_class)->GetClassSize(), class_size);
3698 StackHandleScope<1> hs(self);
3699 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
3700 ObjectLock<mirror::Class> lock(self, new_class_h);
3701
3702 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
3703
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003704 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
3705 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003706 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003707
3708 // This will notify waiters on temp class that saw the not yet resolved class in the
3709 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003710 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003711
3712 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
3713 // This will notify waiters on new_class that saw the not yet resolved
3714 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003715 mirror::Class::SetStatus(new_class_h, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003716 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003717 return true;
3718}
3719
Andreas Gampefd9eb392014-11-06 16:52:58 -08003720static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
3721 size_t* virtual_methods,
3722 size_t* direct_methods,
3723 size_t* static_fields,
3724 size_t* instance_fields) {
3725 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
3726
3727 while (dex_data.HasNextStaticField()) {
3728 dex_data.Next();
3729 (*static_fields)++;
3730 }
3731 while (dex_data.HasNextInstanceField()) {
3732 dex_data.Next();
3733 (*instance_fields)++;
3734 }
3735 while (dex_data.HasNextDirectMethod()) {
3736 (*direct_methods)++;
3737 dex_data.Next();
3738 }
3739 while (dex_data.HasNextVirtualMethod()) {
3740 (*virtual_methods)++;
3741 dex_data.Next();
3742 }
3743 DCHECK(!dex_data.HasNext());
3744}
3745
3746static void DumpClass(std::ostream& os,
3747 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
3748 const char* suffix) {
3749 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
3750 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
3751 os << " Static fields:\n";
3752 while (dex_data.HasNextStaticField()) {
3753 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3754 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3755 dex_data.Next();
3756 }
3757 os << " Instance fields:\n";
3758 while (dex_data.HasNextInstanceField()) {
3759 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3760 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3761 dex_data.Next();
3762 }
3763 os << " Direct methods:\n";
3764 while (dex_data.HasNextDirectMethod()) {
3765 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3766 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3767 dex_data.Next();
3768 }
3769 os << " Virtual methods:\n";
3770 while (dex_data.HasNextVirtualMethod()) {
3771 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3772 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3773 dex_data.Next();
3774 }
3775}
3776
3777static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3778 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
3779 std::ostringstream os;
3780 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
3781 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
3782 return os.str();
3783}
3784
3785
3786// Very simple structural check on whether the classes match. Only compares the number of
3787// methods and fields.
3788static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3789 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
3790 std::string* error_msg) {
3791 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
3792 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
3793
3794 // Counters for current dex file.
3795 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
3796 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
3797 &dex_instance_fields1);
3798 // Counters for compile-time dex file.
3799 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
3800 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
3801 &dex_instance_fields2);
3802
3803 if (dex_virtual_methods1 != dex_virtual_methods2) {
3804 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3805 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
3806 dex_virtual_methods2, class_dump.c_str());
3807 return false;
3808 }
3809 if (dex_direct_methods1 != dex_direct_methods2) {
3810 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3811 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
3812 dex_direct_methods2, class_dump.c_str());
3813 return false;
3814 }
3815 if (dex_static_fields1 != dex_static_fields2) {
3816 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3817 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
3818 dex_static_fields2, class_dump.c_str());
3819 return false;
3820 }
3821 if (dex_instance_fields1 != dex_instance_fields2) {
3822 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3823 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
3824 dex_instance_fields2, class_dump.c_str());
3825 return false;
3826 }
3827
3828 return true;
3829}
3830
3831// Checks whether a the super-class changed from what we had at compile-time. This would
3832// invalidate quickening.
3833static bool CheckSuperClassChange(Handle<mirror::Class> klass,
3834 const DexFile& dex_file,
3835 const DexFile::ClassDef& class_def,
3836 mirror::Class* super_class)
3837 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3838 // Check for unexpected changes in the superclass.
3839 // Quick check 1) is the super_class class-loader the boot class loader? This always has
3840 // precedence.
3841 if (super_class->GetClassLoader() != nullptr &&
3842 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
3843 // which is implied by different dex cache.
3844 klass->GetDexCache() != super_class->GetDexCache()) {
3845 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
3846 // definition for the super-class, and (b) the files are in separate oat files. The oat files
3847 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
3848 const OatFile* class_oat_file = dex_file.GetOatFile();
3849 if (class_oat_file != nullptr) {
3850 const OatFile* loaded_super_oat_file = super_class->GetDexFile().GetOatFile();
3851 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
3852 // Now check (a).
3853 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
3854 if (super_class_def != nullptr) {
3855 // Uh-oh, we found something. Do our check.
3856 std::string error_msg;
3857 if (!SimpleStructuralCheck(dex_file, *super_class_def,
3858 super_class->GetDexFile(), *super_class->GetClassDef(),
3859 &error_msg)) {
3860 // Print a warning to the log. This exception might be caught, e.g., as common in test
3861 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
3862 // only save the type of the exception.
3863 LOG(WARNING) << "Incompatible structural change detected: " <<
3864 StringPrintf(
3865 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3866 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3867 class_oat_file->GetLocation().c_str(),
3868 loaded_super_oat_file->GetLocation().c_str(),
3869 error_msg.c_str());
3870 ThrowIncompatibleClassChangeError(klass.Get(),
3871 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3872 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3873 class_oat_file->GetLocation().c_str(),
3874 loaded_super_oat_file->GetLocation().c_str(),
3875 error_msg.c_str());
3876 return false;
3877 }
3878 }
3879 }
3880 }
3881 }
3882 return true;
3883}
3884
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003885bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003886 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003887 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3888 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003889 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003890 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003891 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003892 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003893 return false;
3894 }
Ian Rogersbe125a92012-01-11 15:19:49 -08003895 // Verify
3896 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003897 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003898 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003899 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08003900 return false;
3901 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003902 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003903 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08003904
3905 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
3906 DCHECK(Thread::Current()->IsExceptionPending());
3907 return false;
3908 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003909 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003910 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003911 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003912 for (size_t i = 0; i < interfaces->Size(); i++) {
3913 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003914 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003915 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003916 DCHECK(Thread::Current()->IsExceptionPending());
3917 return false;
3918 }
3919 // Verify
3920 if (!klass->CanAccess(interface)) {
3921 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003922 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003923 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003924 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003925 return false;
3926 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003927 }
3928 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003929 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003930 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003931 return true;
3932}
3933
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003934bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003935 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003936 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003937 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003938 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003939 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003940 return false;
3941 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003942 return true;
3943 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003944 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003945 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
3946 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003947 return false;
3948 }
3949 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003950 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003951 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003952 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003953 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003954 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003955 return false;
3956 }
3957 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003958 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003959 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003960 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003961 return false;
3962 }
Elliott Hughes20cde902011-10-04 17:37:27 -07003963
Brian Carlstromf3632832014-05-20 15:36:53 -07003964 // Inherit kAccClassIsFinalizable from the superclass in case this
3965 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07003966 if (super->IsFinalizable()) {
3967 klass->SetFinalizable();
3968 }
3969
Elliott Hughes2da50362011-10-10 16:57:08 -07003970 // Inherit reference flags (if any) from the superclass.
3971 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
3972 if (reference_flags != 0) {
3973 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
3974 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07003975 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07003976 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003977 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003978 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003979 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07003980 return false;
3981 }
Elliott Hughes2da50362011-10-10 16:57:08 -07003982
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003983 if (kIsDebugBuild) {
3984 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003985 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003986 CHECK(super->IsResolved());
3987 super = super->GetSuperClass();
3988 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003989 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003990 return true;
3991}
3992
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003993// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003994bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003995 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
3996 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003997 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003998 if (klass->IsInterface()) {
3999 // No vtable.
4000 size_t count = klass->NumVirtualMethods();
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004001 if (!IsUint<16>(count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004002 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004003 return false;
4004 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004005 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004006 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004007 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004008 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4009 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004010 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004011 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004012}
4013
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004014// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4015// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4016// caches in the implementation below.
4017class MethodNameAndSignatureComparator FINAL : public ValueObject {
4018 public:
4019 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4020 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4021 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4022 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004023 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4024 }
4025
4026 const char* GetName() {
4027 if (name_ == nullptr) {
4028 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4029 }
4030 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004031 }
4032
4033 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4034 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4035 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4036 const DexFile* other_dex_file = other->GetDexFile();
4037 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4038 if (dex_file_ == other_dex_file) {
4039 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4040 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004041 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004042 uint32_t other_name_len;
4043 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4044 &other_name_len);
4045 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4046 return false;
4047 }
4048 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4049 }
4050
4051 private:
4052 // Dex file for the method to compare against.
4053 const DexFile* const dex_file_;
4054 // MethodId for the method to compare against.
4055 const DexFile::MethodId* const mid_;
4056 // Lazily computed name from the dex file's strings.
4057 const char* name_;
4058 // Lazily computed name length.
4059 uint32_t name_len_;
4060};
4061
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004062class LinkVirtualHashTable {
4063 public:
4064 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4065 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4066 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4067 }
4068 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4069 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4070 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004071 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004072 uint32_t index = hash % hash_size_;
4073 // Linear probe until we have an empty slot.
4074 while (hash_table_[index] != invalid_index_) {
4075 if (++index == hash_size_) {
4076 index = 0;
4077 }
4078 }
4079 hash_table_[index] = virtual_method_index;
4080 }
4081 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4082 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4083 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004084 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004085 size_t index = hash % hash_size_;
4086 while (true) {
4087 const uint32_t value = hash_table_[index];
4088 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4089 // the block and can safely assume not found.
4090 if (value == invalid_index_) {
4091 break;
4092 }
4093 if (value != removed_index_) { // This signifies not already overriden.
4094 mirror::ArtMethod* virtual_method =
4095 klass_->GetVirtualMethodDuringLinking(value);
4096 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4097 hash_table_[index] = removed_index_;
4098 return value;
4099 }
4100 }
4101 if (++index == hash_size_) {
4102 index = 0;
4103 }
4104 }
4105 return GetNotFoundIndex();
4106 }
4107 static uint32_t GetNotFoundIndex() {
4108 return invalid_index_;
4109 }
4110
4111 private:
4112 static const uint32_t invalid_index_;
4113 static const uint32_t removed_index_;
4114
4115 Handle<mirror::Class> klass_;
4116 const size_t hash_size_;
4117 uint32_t* const hash_table_;
4118};
4119
4120const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4121const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4122
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004123bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004124 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004125 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004126 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4127 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004128 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004129 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004130 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004131 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4132 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4133 if (UNLIKELY(vtable.Get() == nullptr)) {
4134 CHECK(self->IsExceptionPending()); // OOME.
4135 return false;
4136 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004137 for (size_t i = 0; i < super_vtable_length; i++) {
4138 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004139 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004140 if (num_virtual_methods == 0) {
4141 klass->SetVTable(vtable.Get());
4142 return true;
4143 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004144 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004145 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4146 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4147 if (num_virtual_methods == 0) {
4148 klass->SetVTable(super_vtable);
4149 return true;
4150 }
4151 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004152 if (UNLIKELY(vtable.Get() == nullptr)) {
4153 CHECK(self->IsExceptionPending()); // OOME.
4154 return false;
4155 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004156 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004157 // How the algorithm works:
4158 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4159 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4160 // method which has not been matched to a vtable method, and j if the virtual method at the
4161 // index overrode the super virtual method at index j.
4162 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4163 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4164 // the need for the initial vtable which we later shrink back down).
4165 // 3. Add non overridden methods to the end of the vtable.
4166 static constexpr size_t kMaxStackHash = 250;
4167 const size_t hash_table_size = num_virtual_methods * 3;
4168 uint32_t* hash_table_ptr;
4169 std::unique_ptr<uint32_t[]> hash_heap_storage;
4170 if (hash_table_size <= kMaxStackHash) {
4171 hash_table_ptr = reinterpret_cast<uint32_t*>(
4172 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4173 } else {
4174 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4175 hash_table_ptr = hash_heap_storage.get();
4176 }
4177 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4178 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004179 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004180 hash_table.Add(i);
4181 }
4182 // Loop through each super vtable method and see if they are overriden by a method we added to
4183 // the hash table.
4184 for (size_t j = 0; j < super_vtable_length; ++j) {
4185 // Search the hash table to see if we are overidden by any method.
4186 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4187 MethodNameAndSignatureComparator super_method_name_comparator(
4188 super_method->GetInterfaceMethodIfProxy());
4189 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4190 if (hash_index != hash_table.GetNotFoundIndex()) {
4191 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4192 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4193 super_method->GetAccessFlags())) {
4194 if (super_method->IsFinal()) {
4195 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4196 PrettyMethod(virtual_method).c_str(),
4197 super_method->GetDeclaringClassDescriptor());
4198 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004199 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004200 vtable->SetWithoutChecks<false>(j, virtual_method);
4201 virtual_method->SetMethodIndex(j);
4202 } else {
4203 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004204 << " would have incorrectly overridden the package-private method in "
4205 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004206 }
4207 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004208 }
4209 // Add the non overridden methods at the end.
4210 size_t actual_count = super_vtable_length;
4211 for (size_t i = 0; i < num_virtual_methods; ++i) {
4212 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4213 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4214 if (method_idx < super_vtable_length &&
4215 local_method == vtable->GetWithoutChecks(method_idx)) {
4216 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004217 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004218 vtable->SetWithoutChecks<false>(actual_count, local_method);
4219 local_method->SetMethodIndex(actual_count);
4220 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004221 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004222 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004223 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004224 return false;
4225 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004226 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004227 CHECK_LE(actual_count, max_count);
4228 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004229 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004230 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004231 CHECK(self->IsExceptionPending()); // OOME.
4232 return false;
4233 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004234 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004235 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004236 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004237 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004238 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004239 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4240 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004241 return false;
4242 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004243 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4244 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004245 CHECK(self->IsExceptionPending()); // OOME.
4246 return false;
4247 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004248 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004249 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004250 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004251 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004252 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004253 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004254 }
4255 return true;
4256}
4257
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004258bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4259 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4260 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004261 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004262 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004263 const bool has_superclass = klass->HasSuperClass();
4264 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4265 const bool have_interfaces = interfaces.Get() != nullptr;
4266 const size_t num_interfaces =
4267 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4268 if (num_interfaces == 0) {
4269 if (super_ifcount == 0) {
4270 // Class implements no interfaces.
4271 DCHECK_EQ(klass->GetIfTableCount(), 0);
4272 DCHECK(klass->GetIfTable() == nullptr);
4273 return true;
4274 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004275 // Class implements same interfaces as parent, are any of these not marker interfaces?
4276 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004277 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004278 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004279 if (super_iftable->GetMethodArrayCount(i) > 0) {
4280 has_non_marker_interface = true;
4281 break;
4282 }
4283 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004284 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004285 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004286 klass->SetIfTable(super_iftable);
4287 return true;
4288 }
4289 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004290 size_t ifcount = super_ifcount + num_interfaces;
4291 for (size_t i = 0; i < num_interfaces; i++) {
4292 mirror::Class* interface = have_interfaces ?
4293 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4294 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004295 if (UNLIKELY(!interface->IsInterface())) {
4296 std::string temp;
4297 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4298 PrettyDescriptor(klass.Get()).c_str(),
4299 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4300 return false;
4301 }
4302 ifcount += interface->GetIfTableCount();
4303 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004304 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004305 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004306 CHECK(self->IsExceptionPending()); // OOME.
4307 return false;
4308 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004309 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004310 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004311 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004312 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004313 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004314 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004315 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004316 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004317 // Flatten the interface inheritance hierarchy.
4318 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004319 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004320 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4321 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004322 // Check if interface is already in iftable
4323 bool duplicate = false;
4324 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004325 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004326 if (existing_interface == interface) {
4327 duplicate = true;
4328 break;
4329 }
4330 }
4331 if (!duplicate) {
4332 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004333 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004334 // Add this interface's non-duplicate super-interfaces.
4335 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004336 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004337 bool super_duplicate = false;
4338 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004339 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004340 if (existing_interface == super_interface) {
4341 super_duplicate = true;
4342 break;
4343 }
4344 }
4345 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004346 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004347 }
4348 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004349 }
4350 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004351 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004352 // Shrink iftable in case duplicates were found
4353 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004354 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004355 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004356 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004357 CHECK(self->IsExceptionPending()); // OOME.
4358 return false;
4359 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004360 ifcount = idx;
4361 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004362 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004363 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004364 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004365 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004366 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004367 return true;
4368 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004369 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004370 size_t max_miranda_methods = 0; // The max size of miranda_list.
4371 for (size_t i = 0; i < ifcount; ++i) {
4372 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4373 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004374 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004375 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004376 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4377 hs.NewHandle(klass->GetVTableDuringLinking()));
4378 // Copy the IMT from the super class if possible.
4379 bool extend_super_iftable = false;
4380 if (has_superclass) {
4381 mirror::Class* super_class = klass->GetSuperClass();
4382 extend_super_iftable = true;
4383 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4384 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4385 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
4386 }
4387 } else {
4388 // No imt in the super class, need to reconstruct from the iftable.
4389 mirror::IfTable* if_table = super_class->GetIfTable();
4390 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4391 const size_t length = super_class->GetIfTableCount();
4392 for (size_t i = 0; i < length; ++i) {
4393 mirror::Class* interface = iftable->GetInterface(i);
4394 const size_t num_virtuals = interface->NumVirtualMethods();
4395 const size_t method_array_count = if_table->GetMethodArrayCount(i);
4396 DCHECK_EQ(num_virtuals, method_array_count);
4397 if (method_array_count == 0) {
4398 continue;
4399 }
4400 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
4401 for (size_t j = 0; j < num_virtuals; ++j) {
4402 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
4403 if (method->IsMiranda()) {
4404 continue;
4405 }
4406 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
4407 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4408 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4409 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4410 out_imt->SetReference(imt_index, method);
4411 } else if (imt_ref != conflict_method) {
4412 out_imt->SetReference(imt_index, conflict_method);
4413 }
4414 }
4415 }
4416 }
4417 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004418 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004419 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004420 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004421 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004422 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004423 const bool is_super = i < super_ifcount;
4424 const bool super_interface = is_super && extend_super_iftable;
4425 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
4426 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
4427 if (super_interface) {
4428 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
4429 DCHECK(if_table != nullptr);
4430 DCHECK(if_table->GetMethodArray(i) != nullptr);
4431 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004432 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004433 AsObjectArray<mirror::ArtMethod>());
4434 // We are overwriting a super class interface, try to only virtual methods instead of the
4435 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004436 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004437 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004438 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004439 // A new interface, we need the whole vtable incase a new interface method is implemented
4440 // in the whole superclass.
4441 input_array = vtable;
4442 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004443 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004444 CHECK(self->IsExceptionPending()); // OOME.
4445 return false;
4446 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004447 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004448 if (input_array.Get() == nullptr) {
4449 // If the added virtual methods is empty, do nothing.
4450 DCHECK(super_interface);
4451 continue;
4452 }
Ian Rogers62d6c772013-02-27 08:32:07 -08004453 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004454 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004455 MethodNameAndSignatureComparator interface_name_comparator(
4456 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07004457 int32_t k;
4458 // For each method listed in the interface's method list, find the
4459 // matching method in our class's method list. We want to favor the
4460 // subclass over the superclass, which just requires walking
4461 // back from the end of the vtable. (This only matters if the
4462 // superclass defines a private method and this class redefines
4463 // it -- otherwise it would use the same vtable slot. In .dex files
4464 // those don't end up in the virtual method table, so it shouldn't
4465 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004466 for (k = input_array->GetLength() - 1; k >= 0; --k) {
4467 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004468 mirror::ArtMethod* vtable_method_for_name_comparison =
4469 vtable_method->GetInterfaceMethodIfProxy();
4470 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004471 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004472 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004473 ThrowIllegalAccessError(
4474 klass.Get(),
4475 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004476 PrettyMethod(vtable_method).c_str(),
4477 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004478 return false;
4479 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004480 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004481 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004482 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4483 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4484 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4485 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4486 out_imt->SetReference(imt_index, vtable_method);
4487 } else if (imt_ref != conflict_method) {
4488 // If we are not a conflict and we have the same signature and name as the imt entry,
4489 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004490 MethodNameAndSignatureComparator imt_ref_name_comparator(
4491 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004492 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004493 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004494 out_imt->SetReference(imt_index, vtable_method);
4495 } else {
4496 out_imt->SetReference(imt_index, conflict_method);
4497 }
Jeff Hao88474b42013-10-23 16:24:40 -07004498 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004499 break;
4500 }
4501 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004502 if (k < 0 && !super_interface) {
4503 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004504 for (size_t l = 0; l < miranda_list_size; ++l) {
4505 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004506 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004507 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07004508 break;
4509 }
4510 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004511 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004512 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004513 miranda_method = interface_method->Clone(self)->AsArtMethod();
4514 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004515 CHECK(self->IsExceptionPending()); // OOME.
4516 return false;
4517 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004518 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004519 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004520 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004521 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004522 }
4523 }
4524 }
4525 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004526 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004527 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004528 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004529 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4530 if (old_method_count == 0) {
4531 virtuals = AllocArtMethodArray(self, new_method_count);
4532 } else {
4533 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4534 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004535 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004536 CHECK(self->IsExceptionPending()); // OOME.
4537 return false;
4538 }
4539 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004540
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004541 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004542 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004543 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004544 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004545 CHECK(self->IsExceptionPending()); // OOME.
4546 return false;
4547 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004548 for (size_t i = 0; i < miranda_list_size; ++i) {
4549 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004550 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004551 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4552 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4553 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004554 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004555 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004556 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004557 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004558 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004559
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004560 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004561 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
4562 for (int i = 0; i < check_vtable->GetLength(); ++i) {
4563 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004564 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004565 }
4566
Ian Rogers7b078e82014-09-10 14:44:24 -07004567 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004568 return true;
4569}
4570
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004571bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004572 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004573 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004574}
4575
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004576bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004577 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004578 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004579}
4580
Brian Carlstromdbc05252011-09-09 01:59:59 -07004581struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004582 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4583 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004584 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004585 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004586 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07004587 // 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 -07004588 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4589 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004590 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00004591 if (type1 == Primitive::kPrimNot) {
4592 // Reference always goes first.
4593 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08004594 }
Vladimir Markod5777482014-11-12 17:02:02 +00004595 if (type2 == Primitive::kPrimNot) {
4596 // Reference always goes first.
4597 return false;
4598 }
4599 size_t size1 = Primitive::ComponentSize(type1);
4600 size_t size2 = Primitive::ComponentSize(type2);
4601 if (size1 != size2) {
4602 // Larger primitive types go first.
4603 return size1 > size2;
4604 }
4605 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
4606 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004607 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004608 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
4609 // by name and for equal names by type id index.
4610 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
4611 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07004612 }
4613};
4614
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004615bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07004616 size_t* class_size) {
4617 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004618 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004619 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004620
Brian Carlstromea46f952013-07-30 01:26:50 -07004621 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004622 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004623
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004624 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07004625 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004626 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00004627 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004628 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004629 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004630 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004631 CHECK(super_class->IsResolved())
4632 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004633 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004634 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004635 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004636
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004637 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004638
Brian Carlstromdbc05252011-09-09 01:59:59 -07004639 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07004640 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07004641 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07004642 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07004643 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07004644 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004645 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004646 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004647 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004648 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004649 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4650 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004651
Fred Shih381e4ca2014-08-25 17:24:27 -07004652 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07004653 size_t current_field = 0;
4654 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07004655 FieldGaps gaps;
4656
Brian Carlstromdbc05252011-09-09 01:59:59 -07004657 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004658 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004659 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004660 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004661 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004662 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004663 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004664 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
4665 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07004666 MemberOffset old_offset = field_offset;
4667 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
4668 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
4669 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004670 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07004671 grouped_and_sorted_fields.pop_front();
4672 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004673 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00004674 field_offset = MemberOffset(field_offset.Uint32Value() +
4675 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004676 }
Fred Shih381e4ca2014-08-25 17:24:27 -07004677 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
4678 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00004679 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4680 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4681 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4682 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07004683 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
4684 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07004685 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004686
Elliott Hughesadb460d2011-10-05 17:02:34 -07004687 // 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 -07004688 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07004689 // We know there are no non-reference fields in the Reference classes, and we know
4690 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07004691 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004692 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07004693 --num_reference_fields;
4694 }
4695
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004696 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004697 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004698 if (is_static) {
4699 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004700 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004701 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004702 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004703 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08004704 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
Jeff Haoc7d11882015-02-03 15:08:39 -08004705 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
4706 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartier2d721012014-11-10 11:08:06 -08004707 } else {
4708 std::string temp;
4709 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
4710 size_t previous_size = klass->GetObjectSize();
4711 if (previous_size != 0) {
4712 // Make sure that we didn't originally have an incorrect size.
4713 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
4714 }
4715 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004716 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004717 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004718 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004719
4720 if (kIsDebugBuild) {
4721 // Make sure that the fields array is ordered by name but all reference
4722 // offsets are at the beginning as far as alignment allows.
4723 MemberOffset start_ref_offset = is_static
4724 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
4725 : klass->GetFirstReferenceInstanceFieldOffset();
4726 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
4727 num_reference_fields *
4728 sizeof(mirror::HeapReference<mirror::Object>));
4729 MemberOffset current_ref_offset = start_ref_offset;
4730 for (size_t i = 0; i < num_fields; i++) {
4731 mirror::ArtField* field = fields->Get(i);
4732 if ((false)) { // enable to debug field layout
4733 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
4734 << " class=" << PrettyClass(klass.Get())
4735 << " field=" << PrettyField(field)
4736 << " offset="
4737 << field->GetField32(mirror::ArtField::OffsetOffset());
4738 }
4739 if (i != 0) {
4740 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004741 // NOTE: The field names can be the same. This is not possible in the Java language
4742 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
4743 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00004744 }
4745 Primitive::Type type = field->GetTypeAsPrimitiveType();
4746 bool is_primitive = type != Primitive::kPrimNot;
4747 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
4748 strcmp("referent", field->GetName()) == 0) {
4749 is_primitive = true; // We lied above, so we have to expect a lie here.
4750 }
4751 MemberOffset offset = field->GetOffsetDuringLinking();
4752 if (is_primitive) {
4753 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
4754 // Shuffled before references.
4755 size_t type_size = Primitive::ComponentSize(type);
4756 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
4757 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
4758 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
4759 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
4760 }
4761 } else {
4762 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
4763 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
4764 sizeof(mirror::HeapReference<mirror::Object>));
4765 }
4766 }
4767 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
4768 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004769 return true;
4770}
4771
Vladimir Marko76649e82014-11-10 18:32:59 +00004772// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004773void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004774 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004775 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004776 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004777 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004778 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004779 // Compute reference offsets unless our superclass overflowed.
4780 if (reference_offsets != mirror::Class::kClassWalkSuper) {
4781 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00004782 if (num_reference_fields != 0u) {
4783 // All of the fields that contain object references are guaranteed be grouped in memory
4784 // starting at an appropriately aligned address after super class object data.
4785 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
4786 sizeof(mirror::HeapReference<mirror::Object>));
4787 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004788 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00004789 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004790 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004791 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00004792 reference_offsets |= (0xffffffffu << start_bit) &
4793 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004794 }
4795 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07004796 }
4797 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07004798 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004799}
4800
Mathieu Chartier590fee92013-09-13 13:46:47 -07004801mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004802 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004803 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004804 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004805 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004806 return resolved;
4807 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07004808 uint32_t utf16_length;
4809 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004810 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004811 dex_cache->SetResolvedString(string_idx, string);
4812 return string;
4813}
4814
Mathieu Chartier590fee92013-09-13 13:46:47 -07004815mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08004816 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004817 StackHandleScope<2> hs(Thread::Current());
4818 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
4819 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07004820 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
4821}
4822
4823mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004824 Handle<mirror::DexCache> dex_cache,
4825 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004826 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004827 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004828 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08004829 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07004830 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08004831 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004832 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05004833 // TODO: we used to throw here if resolved's class loader was not the
4834 // boot class loader. This was to permit different classes with the
4835 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004836 dex_cache->SetResolvedType(type_idx, resolved);
4837 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004838 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08004839 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08004840 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004841 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004842 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004843 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004844 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08004845 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08004846 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004847 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08004848 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004849 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004850 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004851 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07004852 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004853 return resolved;
4854}
4855
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004856mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004857 Handle<mirror::DexCache> dex_cache,
4858 Handle<mirror::ClassLoader> class_loader,
4859 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07004860 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004861 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07004862 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07004863 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004864 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004865 return resolved;
4866 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004867 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004868 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004869 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004870 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07004871 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004872 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004873 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004874 // Scan using method_idx, this saves string compares but will only hit for matching dex
4875 // caches/files.
4876 switch (type) {
4877 case kDirect: // Fall-through.
4878 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004879 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004880 break;
4881 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004882 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004883 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004884 break;
4885 case kSuper: // Fall-through.
4886 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004887 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004888 break;
4889 default:
4890 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07004891 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004892 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004893 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004894 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004895 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07004896 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07004897 switch (type) {
4898 case kDirect: // Fall-through.
4899 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08004900 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004901 break;
4902 case kInterface:
4903 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004904 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004905 break;
4906 case kSuper: // Fall-through.
4907 case kVirtual:
4908 resolved = klass->FindVirtualMethod(name, signature);
4909 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004910 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004911 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004912 // If we found a method, check for incompatible class changes.
4913 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004914 // Be a good citizen and update the dex cache to speed subsequent calls.
4915 dex_cache->SetResolvedMethod(method_idx, resolved);
4916 return resolved;
4917 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004918 // If we had a method, it's an incompatible-class-change error.
4919 if (resolved != nullptr) {
4920 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
4921 } else {
4922 // We failed to find the method which means either an access error, an incompatible class
4923 // change, or no such method. First try to find the method among direct and virtual methods.
4924 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
4925 const Signature signature = dex_file.GetMethodSignature(method_id);
4926 switch (type) {
4927 case kDirect:
4928 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07004929 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004930 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
4931 // have had a resolved method before, which triggers the "true" branch above.
4932 break;
4933 case kInterface:
4934 case kVirtual:
4935 case kSuper:
4936 resolved = klass->FindDirectMethod(name, signature);
4937 break;
4938 }
4939
4940 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08004941 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004942 if (resolved != nullptr && referrer.Get() != nullptr) {
4943 mirror::Class* methods_class = resolved->GetDeclaringClass();
4944 mirror::Class* referring_class = referrer->GetDeclaringClass();
4945 if (!referring_class->CanAccess(methods_class)) {
4946 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
4947 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004948 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004949 } else if (!referring_class->CanAccessMember(methods_class,
4950 resolved->GetAccessFlags())) {
4951 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004952 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004953 }
4954 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004955 if (!exception_generated) {
4956 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
4957 // interface methods and throw if we find the method there. If we find nothing, throw a
4958 // NoSuchMethodError.
4959 switch (type) {
4960 case kDirect:
4961 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004962 if (resolved != nullptr) {
4963 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4964 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004965 resolved = klass->FindInterfaceMethod(name, signature);
4966 if (resolved != nullptr) {
4967 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4968 } else {
4969 ThrowNoSuchMethodError(type, klass, name, signature);
4970 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004971 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004972 break;
4973 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004974 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004975 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
4976 } else {
4977 resolved = klass->FindVirtualMethod(name, signature);
4978 if (resolved != nullptr) {
4979 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4980 } else {
4981 ThrowNoSuchMethodError(type, klass, name, signature);
4982 }
4983 }
4984 break;
4985 case kSuper:
4986 if (resolved != nullptr) {
4987 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004988 } else {
4989 ThrowNoSuchMethodError(type, klass, name, signature);
4990 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004991 break;
4992 case kVirtual:
4993 if (resolved != nullptr) {
4994 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
4995 } else {
4996 resolved = klass->FindInterfaceMethod(name, signature);
4997 if (resolved != nullptr) {
4998 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4999 } else {
5000 ThrowNoSuchMethodError(type, klass, name, signature);
5001 }
5002 }
5003 break;
5004 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005005 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005006 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005007 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005008 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005009 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005010}
5011
Mathieu Chartier590fee92013-09-13 13:46:47 -07005012mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005013 Handle<mirror::DexCache> dex_cache,
5014 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005015 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005016 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005017 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005018 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005019 return resolved;
5020 }
5021 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005022 Thread* const self = Thread::Current();
5023 StackHandleScope<1> hs(self);
5024 Handle<mirror::Class> klass(
5025 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005026 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005027 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005028 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005029 }
5030
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005031 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005032 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005033 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005034 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005035 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005036
Andreas Gampe58a5af82014-07-31 16:23:49 -07005037 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005038 const char* name = dex_file.GetFieldName(field_id);
5039 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5040 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005041 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005042 } else {
5043 resolved = klass->FindInstanceField(name, type);
5044 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005045 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005046 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005047 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005048 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005049 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005050 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005051 return resolved;
5052}
5053
Brian Carlstromea46f952013-07-30 01:26:50 -07005054mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005055 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005056 Handle<mirror::DexCache> dex_cache,
5057 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005058 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005059 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005060 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005061 return resolved;
5062 }
5063 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005064 Thread* self = Thread::Current();
5065 StackHandleScope<1> hs(self);
5066 Handle<mirror::Class> klass(
5067 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005068 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005069 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005070 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005071 }
5072
Ian Rogersdfb325e2013-10-30 01:00:44 -07005073 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5074 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005075 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005076 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005077 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005078 dex_cache->SetResolvedField(field_idx, resolved);
5079 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005080 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005081 }
5082 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005083}
5084
Brian Carlstromea46f952013-07-30 01:26:50 -07005085const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005086 uint32_t* length) {
5087 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5088 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005089 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005090 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005091 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005092}
5093
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005094void ClassLinker::DumpAllClasses(int flags) {
5095 if (dex_cache_image_class_lookup_required_) {
5096 MoveImageClassesToClassTable();
5097 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005098 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5099 // 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 -08005100 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005101 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005102 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005103 for (GcRoot<mirror::Class>& it : class_table_) {
5104 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005105 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005106 }
5107
5108 for (size_t i = 0; i < all_classes.size(); ++i) {
5109 all_classes[i]->DumpClass(std::cerr, flags);
5110 }
5111}
5112
Elliott Hughes956af0f2014-12-11 14:34:28 -08005113static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005114 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005115 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5116 base -= sizeof(void*); // Move backward so that code_offset != 0.
5117 const uint32_t code_offset = sizeof(void*);
5118 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005119}
5120
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005121bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5122 return (entry_point == GetQuickResolutionStub()) ||
5123 (quick_resolution_trampoline_ == entry_point);
5124}
5125
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005126bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5127 return (entry_point == GetQuickToInterpreterBridge()) ||
5128 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5129}
5130
5131bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5132 return (entry_point == GetQuickGenericJniStub()) ||
5133 (quick_generic_jni_trampoline_ == entry_point);
5134}
5135
5136const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5137 return GetQuickGenericJniStub();
5138}
5139
Elliott Hughes956af0f2014-12-11 14:34:28 -08005140void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5141 const void* method_code) const {
5142 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005143 oat_method.LinkMethod(method);
5144 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005145}
5146
5147void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5148 if (!method->IsNative()) {
5149 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005150 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5151 } else {
5152 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005153 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005154 oat_method.LinkMethod(method);
5155 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005156 }
5157}
5158
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005159void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005160 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005161 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005162 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005163 MoveImageClassesToClassTable();
5164 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005165 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005166 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5167 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005168}
5169
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005170size_t ClassLinker::NumLoadedClasses() {
5171 if (dex_cache_image_class_lookup_required_) {
5172 MoveImageClassesToClassTable();
5173 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005174 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005175 // Only return non zygote classes since these are the ones which apps which care about.
5176 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005177}
5178
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005179pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005180 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005181}
5182
5183pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005184 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005185}
5186
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005187void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005188 DCHECK(!init_done_);
5189
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005190 DCHECK(klass != nullptr);
5191 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005192
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005193 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005194 DCHECK(class_roots != nullptr);
5195 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005196 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005197}
5198
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005199const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5200 static const char* class_roots_descriptors[] = {
5201 "Ljava/lang/Class;",
5202 "Ljava/lang/Object;",
5203 "[Ljava/lang/Class;",
5204 "[Ljava/lang/Object;",
5205 "Ljava/lang/String;",
5206 "Ljava/lang/DexCache;",
5207 "Ljava/lang/ref/Reference;",
5208 "Ljava/lang/reflect/ArtField;",
5209 "Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005210 "Ljava/lang/reflect/Field;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005211 "Ljava/lang/reflect/Proxy;",
5212 "[Ljava/lang/String;",
5213 "[Ljava/lang/reflect/ArtField;",
5214 "[Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005215 "[Ljava/lang/reflect/Field;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005216 "Ljava/lang/ClassLoader;",
5217 "Ljava/lang/Throwable;",
5218 "Ljava/lang/ClassNotFoundException;",
5219 "Ljava/lang/StackTraceElement;",
5220 "Z",
5221 "B",
5222 "C",
5223 "D",
5224 "F",
5225 "I",
5226 "J",
5227 "S",
5228 "V",
5229 "[Z",
5230 "[B",
5231 "[C",
5232 "[D",
5233 "[F",
5234 "[I",
5235 "[J",
5236 "[S",
5237 "[Ljava/lang/StackTraceElement;",
5238 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005239 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5240 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005241
5242 const char* descriptor = class_roots_descriptors[class_root];
5243 CHECK(descriptor != nullptr);
5244 return descriptor;
5245}
5246
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005247std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5248 const {
5249 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005250 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005251}
5252
5253bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005254 const GcRoot<mirror::Class>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005255 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5256 return false;
5257 }
5258 std::string temp;
5259 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5260}
5261
5262std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5263 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005264 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005265}
5266
5267bool ClassLinker::ClassDescriptorHashEquals::operator()(
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005268 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005269 if (a.Read()->GetClassLoader() != b.second) {
5270 return false;
5271 }
5272 return a.Read()->DescriptorEquals(b.first);
5273}
5274
5275bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005276 const char* descriptor) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005277 return a.Read()->DescriptorEquals(descriptor);
5278}
5279
5280std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005281 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005282}
5283
Sebastien Hertz6963e442014-11-26 22:11:27 +01005284bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07005285 if (Runtime::Current()->UseJit()) {
5286 // JIT can have direct code pointers from any method to any other method.
5287 return true;
5288 }
Sebastien Hertz6963e442014-11-26 22:11:27 +01005289 // Non-image methods don't use direct code pointer.
5290 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
5291 return false;
5292 }
5293 if (m->IsPrivate()) {
5294 // The method can only be called inside its own oat file. Therefore it won't be called using
5295 // its direct code if the oat file has been compiled in PIC mode.
5296 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
5297 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
5298 const OatFile::OatDexFile* oat_dex_file = class_linker->FindOpenedOatDexFileForDexFile(dex_file);
5299 if (oat_dex_file == nullptr) {
5300 // No oat file: the method has not been compiled.
5301 return false;
5302 }
5303 const OatFile* oat_file = oat_dex_file->GetOatFile();
5304 return oat_file != nullptr && !oat_file->IsPic();
5305 } else {
5306 // The method can be called outside its own oat file. Therefore it won't be called using its
5307 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
5308 ReaderMutexLock mu(Thread::Current(), dex_lock_);
5309 for (const OatFile* oat_file : oat_files_) {
5310 if (!oat_file->IsPic()) {
5311 return true;
5312 }
5313 }
5314 return false;
5315 }
5316}
5317
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005318jobject ClassLinker::CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files) {
5319 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
5320 // We could move the jobject to the callers, but all call-sites do this...
5321 ScopedObjectAccessUnchecked soa(self);
5322
5323 // Register the dex files.
5324 for (const DexFile* dex_file : dex_files) {
5325 RegisterDexFile(*dex_file);
5326 }
5327
5328 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
5329 StackHandleScope<11> hs(self);
5330
5331 Handle<mirror::ArtField> h_dex_elements_field =
5332 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements));
5333
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005334 mirror::Class* dex_elements_class = h_dex_elements_field->GetType<true>();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005335 DCHECK(dex_elements_class != nullptr);
5336 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005337 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
5338 mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005339 Handle<mirror::Class> h_dex_element_class =
5340 hs.NewHandle(dex_elements_class->GetComponentType());
5341
5342 Handle<mirror::ArtField> h_element_file_field =
5343 hs.NewHandle(
5344 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
5345 DCHECK_EQ(h_dex_element_class.Get(), h_element_file_field->GetDeclaringClass());
5346
5347 Handle<mirror::ArtField> h_cookie_field =
5348 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005349 DCHECK_EQ(h_cookie_field->GetDeclaringClass(), h_element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005350
5351 // Fill the elements array.
5352 int32_t index = 0;
5353 for (const DexFile* dex_file : dex_files) {
5354 StackHandleScope<3> hs2(self);
5355
5356 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(self, 1));
5357 DCHECK(h_long_array.Get() != nullptr);
5358 h_long_array->Set(0, reinterpret_cast<intptr_t>(dex_file));
5359
5360 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
5361 h_cookie_field->GetDeclaringClass()->AllocObject(self));
5362 DCHECK(h_dex_file.Get() != nullptr);
5363 h_cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
5364
5365 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
5366 DCHECK(h_element.Get() != nullptr);
5367 h_element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
5368
5369 h_dex_elements->Set(index, h_element.Get());
5370 index++;
5371 }
5372 DCHECK_EQ(index, h_dex_elements->GetLength());
5373
5374 // Create DexPathList.
5375 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
5376 h_dex_elements_field->GetDeclaringClass()->AllocObject(self));
5377 DCHECK(h_dex_path_list.Get() != nullptr);
5378 // Set elements.
5379 h_dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
5380
5381 // Create PathClassLoader.
5382 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
5383 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
5384 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
5385 h_path_class_class->AllocObject(self));
5386 DCHECK(h_path_class_loader.Get() != nullptr);
5387 // Set DexPathList.
5388 Handle<mirror::ArtField> h_path_list_field = hs.NewHandle(
5389 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList));
5390 DCHECK(h_path_list_field.Get() != nullptr);
5391 h_path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
5392
5393 // Make a pretend boot-classpath.
5394 // TODO: Should we scan the image?
5395 Handle<mirror::ArtField> h_parent_field = hs.NewHandle(
5396 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent",
5397 "Ljava/lang/ClassLoader;"));
5398 DCHECK(h_parent_field.Get() != nullptr);
5399 mirror::Object* boot_cl =
5400 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
5401 h_parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
5402
5403 // Make it a global ref and return.
5404 ScopedLocalRef<jobject> local_ref(
5405 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
5406 return soa.Env()->NewGlobalRef(local_ref.get());
5407}
5408
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005409} // namespace art