blob: e4d9baaff45690a2615505a124aee9c598d10b76 [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>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070024#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070025#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070026
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080028#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010029#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080030#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080031#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000033#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080034#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070035#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070036#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070037#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "gc/accounting/card_table-inl.h"
39#include "gc/accounting/heap_bitmap.h"
40#include "gc/heap.h"
41#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070042#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070043#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070044#include "interpreter/interpreter.h"
Ian Rogers0571d352011-11-03 19:51:38 -070045#include "leb128.h"
Ian Rogers1ff3c982014-08-12 02:30:58 -070046#include "method_helper-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080047#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070048#include "oat_file.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070049#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070050#include "mirror/art_field-inl.h"
51#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/class.h"
53#include "mirror/class-inl.h"
54#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070055#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/object-inl.h"
58#include "mirror/object_array-inl.h"
59#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070060#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070062#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080063#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070064#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070065#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070066#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070067#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070068#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070069#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070070#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080071#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070072#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070073
74namespace art {
75
Ian Rogers00f7d0e2012-07-19 15:28:27 -070076static void ThrowNoClassDefFoundError(const char* fmt, ...)
77 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070078 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070079static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070080 va_list args;
81 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080082 Thread* self = Thread::Current();
83 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
84 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080085 va_end(args);
86}
87
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080088static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070089 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070090 // The class failed to initialize on a previous attempt, so we want to throw
91 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
92 // failed in verification, in which case v2 5.4.1 says we need to re-throw
93 // the previous error.
Ian Rogers7b078e82014-09-10 14:44:24 -070094 Runtime* runtime = Runtime::Current();
95 bool is_compiler = runtime->IsCompiler();
96 if (!is_compiler) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -070097 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
98 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -070099
Elliott Hughes5c599942012-06-13 16:45:05 -0700100 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800101 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700102 if (is_compiler) {
103 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
104 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
105 self->SetException(ThrowLocation(), pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700106 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700107 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
108 if (c->GetVerifyErrorClass() != NULL) {
109 // TODO: change the verifier to store an _instance_, with a useful detail message?
110 std::string temp;
111 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
112 PrettyDescriptor(c).c_str());
113 } else {
114 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
115 PrettyDescriptor(c).c_str());
116 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700117 }
118}
119
Brian Carlstromb23eab12014-10-08 17:55:21 -0700120static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
121 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
122 if (VLOG_IS_ON(class_linker)) {
123 std::string temp;
124 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
125 << klass->GetLocation() << "\n" << Thread::Current()->GetException(nullptr)->Dump();
126 }
127}
128
129static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
130 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700131 Thread* self = Thread::Current();
132 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700133
134 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700135 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700136
137 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700138 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
139 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700140
Elliott Hughesa4f94742012-05-29 16:28:38 -0700141 // We only wrap non-Error exceptions; an Error can just be used as-is.
142 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800143 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700144 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;",
145 nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700146 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700147 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700148}
149
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800150static size_t Hash(const char* s) {
151 // This is the java.lang.String hashcode for convenience, not interoperability.
152 size_t hash = 0;
153 for (; *s != '\0'; ++s) {
154 hash = hash * 31 + *s;
155 }
156 return hash;
157}
158
Fred Shih381e4ca2014-08-25 17:24:27 -0700159// Gap between two fields in object layout.
160struct FieldGap {
161 uint32_t start_offset; // The offset from the start of the object.
162 uint32_t size; // The gap size of 1, 2, or 4 bytes.
163};
164struct FieldGapsComparator {
165 explicit FieldGapsComparator() {
166 }
167 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
168 NO_THREAD_SAFETY_ANALYSIS {
169 // Sort by gap size, largest first.
170 return lhs.size > rhs.size;
171 }
172};
173typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
174
175// Adds largest aligned gaps to queue of gaps.
176void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
177 DCHECK(gaps != nullptr);
178
179 uint32_t current_offset = gap_start;
180 while (current_offset != gap_end) {
181 size_t remaining = gap_end - current_offset;
182 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
183 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
184 current_offset += sizeof(uint32_t);
185 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
186 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
187 current_offset += sizeof(uint16_t);
188 } else {
189 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
190 current_offset += sizeof(uint8_t);
191 }
192 DCHECK_LE(current_offset, gap_end) << "Overran gap";
193 }
194}
195// Shuffle fields forward, making use of gaps whenever possible.
196template<int n>
197static void ShuffleForward(const size_t num_fields, size_t* current_field_idx,
198 MemberOffset* field_offset,
199 mirror::ObjectArray<mirror::ArtField>* fields,
200 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
201 FieldGaps* gaps)
202 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
203 DCHECK(current_field_idx != nullptr);
204 DCHECK(grouped_and_sorted_fields != nullptr);
205 DCHECK(fields != nullptr || (num_fields == 0 && grouped_and_sorted_fields->empty()));
206 DCHECK(gaps != nullptr);
207 DCHECK(field_offset != nullptr);
208
209 DCHECK(IsPowerOfTwo(n));
210 while (!grouped_and_sorted_fields->empty()) {
211 mirror::ArtField* field = grouped_and_sorted_fields->front();
212 Primitive::Type type = field->GetTypeAsPrimitiveType();
213 if (Primitive::ComponentSize(type) < n) {
214 break;
215 }
216 if (!IsAligned<n>(field_offset->Uint32Value())) {
217 MemberOffset old_offset = *field_offset;
218 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
219 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
220 }
221 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
222 grouped_and_sorted_fields->pop_front();
223 fields->Set<false>(*current_field_idx, field);
224 if (!gaps->empty() && gaps->top().size >= n) {
225 FieldGap gap = gaps->top();
226 gaps->pop();
227 DCHECK(IsAligned<n>(gap.start_offset));
228 field->SetOffset(MemberOffset(gap.start_offset));
229 if (gap.size > n) {
230 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
231 }
232 } else {
233 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
234 field->SetOffset(*field_offset);
235 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
236 }
237 ++(*current_field_idx);
238 }
239}
240
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800241ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700242 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700243 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700244 dex_cache_image_class_lookup_required_(false),
245 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800246 class_roots_(nullptr),
247 array_iftable_(nullptr),
248 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700249 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800250 log_new_dex_caches_roots_(false),
251 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700252 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800253 portable_resolution_trampoline_(nullptr),
254 quick_resolution_trampoline_(nullptr),
255 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800256 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100257 quick_generic_jni_trampoline_(nullptr),
258 quick_to_interpreter_bridge_trampoline_(nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -0800259 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700260}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700261
Alex Light64ad14d2014-08-19 14:23:13 -0700262void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800263 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700264 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700265
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700266 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700267
Elliott Hughes30646832011-10-13 16:59:46 -0700268 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700269 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700270 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700271 // 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 -0800272 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700273 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
274 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700275 heap->AllocNonMovableObject<true>(self, nullptr,
276 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700277 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700278 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700279 mirror::Class::SetClassClass(java_lang_Class.Get());
280 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700281 if (kUseBakerOrBrooksReadBarrier) {
282 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800283 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700284 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700285 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800286 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800287 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700288
Elliott Hughes418d20f2011-09-22 14:00:39 -0700289 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700290 Handle<mirror::Class> class_array_class(hs.NewHandle(
291 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700292 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700293
Ian Rogers23435d02012-09-24 11:23:12 -0700294 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700295 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
296 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700297 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700298 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700299 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700300 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700301
Ian Rogers23435d02012-09-24 11:23:12 -0700302 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700303 Handle<mirror::Class> object_array_class(hs.NewHandle(
304 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700305 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700306
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700307 // Setup the char (primitive) class to be used for char[].
308 Handle<mirror::Class> char_class(hs.NewHandle(
309 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700310 // The primitive char class won't be initialized by
311 // InitializePrimitiveClass until line 459, but strings (and
312 // internal char arrays) will be allocated before that and the
313 // component size, which is computed from the primitive type, needs
314 // to be set here.
315 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700316
Ian Rogers23435d02012-09-24 11:23:12 -0700317 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700318 Handle<mirror::Class> char_array_class(hs.NewHandle(
319 AllocClass(self, java_lang_Class.Get(),
320 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700321 char_array_class->SetComponentType(char_class.Get());
322 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700323
Ian Rogers23435d02012-09-24 11:23:12 -0700324 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700325 Handle<mirror::Class> java_lang_String(hs.NewHandle(
326 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700327 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700328 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700329 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400330
Fred Shih4ee7a662014-07-11 09:59:27 -0700331 // Setup Reference.
332 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
333 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
334 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
335 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
336 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
337
Ian Rogers23435d02012-09-24 11:23:12 -0700338 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700339 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
340 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
341 kClassRootsMax));
342 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700343 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
344 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
345 SetClassRoot(kClassArrayClass, class_array_class.Get());
346 SetClassRoot(kObjectArrayClass, object_array_class.Get());
347 SetClassRoot(kCharArrayClass, char_array_class.Get());
348 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700349 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700350
351 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700352 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
353 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
354 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
355 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
356 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
357 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
358 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
359 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700360
Ian Rogers23435d02012-09-24 11:23:12 -0700361 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700362 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700363
Ian Rogers23435d02012-09-24 11:23:12 -0700364 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700365 Handle<mirror::Class> int_array_class(hs.NewHandle(
366 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700367 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700368 mirror::IntArray::SetArrayClass(int_array_class.Get());
369 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700370
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700371 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700372
Ian Rogers52813c92012-10-11 11:50:38 -0700373 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700374 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
375 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700376 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700377 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700378 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700379
Brian Carlstromf3632832014-05-20 15:36:53 -0700380 // Constructor, Field, Method, and AbstractMethod are necessary so
381 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700382 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
383 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700384 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700385 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700386 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700387 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700388 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700389
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700390 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
391 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700392 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700393 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700394 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700395 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700396
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700397 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700398
399 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700400 Handle<mirror::Class> object_array_string(hs.NewHandle(
401 AllocClass(self, java_lang_Class.Get(),
402 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700403 object_array_string->SetComponentType(java_lang_String.Get());
404 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700405
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700406 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
407 AllocClass(self, java_lang_Class.Get(),
408 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700409 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
410 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700411
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700412 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
413 AllocClass(self, java_lang_Class.Get(),
414 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700415 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
416 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700417
Ian Rogers23435d02012-09-24 11:23:12 -0700418 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
419 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
420 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700421 CHECK_NE(0U, boot_class_path.size());
422 for (size_t i = 0; i != boot_class_path.size(); ++i) {
423 const DexFile* dex_file = boot_class_path[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700424 CHECK(dex_file != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700425 AppendToBootClassPath(self, *dex_file);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700426 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700427
428 // now we can use FindSystemClass
429
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700430 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700431 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
432 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700433
Jeff Hao88474b42013-10-23 16:24:40 -0700434 // Create runtime resolution and imt conflict methods. Also setup the default imt.
435 Runtime* runtime = Runtime::Current();
436 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
437 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700438 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700439 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
440
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700441 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
442 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700443 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Alex Light64ad14d2014-08-19 14:23:13 -0700444 if (!runtime->IsCompiler()) {
445 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700446 quick_resolution_trampoline_ = GetQuickResolutionStub();
447 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
448 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700449 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700450
Mathieu Chartier66f19252012-09-18 08:57:04 -0700451 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700452 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800453 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700454 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700455 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700456 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800457 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700458 std::ostringstream os1, os2;
459 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
460 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
461 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
462 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700463 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800464 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700465 CHECK_EQ(java_lang_String.Get(), String_class);
466 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700467 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700468
Ian Rogers23435d02012-09-24 11:23:12 -0700469 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800470 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800471 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700472
Ian Rogers98379392014-02-24 16:53:16 -0800473 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800474 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700475
Ian Rogers98379392014-02-24 16:53:16 -0800476 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700477 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700478
Ian Rogers98379392014-02-24 16:53:16 -0800479 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800480 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700481
Ian Rogers98379392014-02-24 16:53:16 -0800482 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700483 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700484
Ian Rogers98379392014-02-24 16:53:16 -0800485 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800486 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700487
Ian Rogers98379392014-02-24 16:53:16 -0800488 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800489 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700490
Ian Rogers98379392014-02-24 16:53:16 -0800491 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800492 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700493
Ian Rogers98379392014-02-24 16:53:16 -0800494 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700495 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700496
Ian Rogers98379392014-02-24 16:53:16 -0800497 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700498 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700499
Ian Rogers23435d02012-09-24 11:23:12 -0700500 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800501 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700502 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800503 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700504 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700505 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
506 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700507 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700508 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700509 array_iftable->SetInterface(0, java_lang_Cloneable);
510 array_iftable->SetInterface(1, java_io_Serializable);
511 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700512
Ian Rogers23435d02012-09-24 11:23:12 -0700513 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700514 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
515 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
516 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
517 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700518 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700519 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800520 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700521 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700522
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700523 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800524 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700525 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700526
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700527 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800528 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700529 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700530
Brian Carlstromf3632832014-05-20 15:36:53 -0700531 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700532 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700533 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700534
Brian Carlstromea46f952013-07-30 01:26:50 -0700535 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700536 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700537 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700538
Brian Carlstromea46f952013-07-30 01:26:50 -0700539 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700540 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700541 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700542
Ian Rogers23435d02012-09-24 11:23:12 -0700543 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700544
Ian Rogers23435d02012-09-24 11:23:12 -0700545 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800546 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700547 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
548
Brian Carlstrom1f870082011-08-23 16:02:11 -0700549 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700550 // finish initializing Reference class
551 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
552 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
553 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
554 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
555 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700556 mirror::Class* java_lang_ref_FinalizerReference =
557 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700558 java_lang_ref_FinalizerReference->SetAccessFlags(
559 java_lang_ref_FinalizerReference->GetAccessFlags() |
560 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700561 mirror::Class* java_lang_ref_PhantomReference =
562 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700563 java_lang_ref_PhantomReference->SetAccessFlags(
564 java_lang_ref_PhantomReference->GetAccessFlags() |
565 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700566 mirror::Class* java_lang_ref_SoftReference =
567 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700568 java_lang_ref_SoftReference->SetAccessFlags(
569 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700570 mirror::Class* java_lang_ref_WeakReference =
571 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700572 java_lang_ref_WeakReference->SetAccessFlags(
573 java_lang_ref_WeakReference->GetAccessFlags() |
574 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700575
Ian Rogers23435d02012-09-24 11:23:12 -0700576 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800577 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700578 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700579 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
580
jeffhao8cd6dda2012-02-22 10:15:34 -0800581 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700582 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800583 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800584 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700585 SetClassRoot(kJavaLangClassNotFoundException,
586 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800587 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700588 SetClassRoot(kJavaLangStackTraceElementArrayClass,
589 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800590 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700591
Ian Rogers98379392014-02-24 16:53:16 -0800592 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700593
Brian Carlstroma004aa92012-02-08 18:05:09 -0800594 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700595}
596
Ian Rogers98379392014-02-24 16:53:16 -0800597void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800598 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700599
600 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700601 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700602 // as the types of the field can't be resolved prior to the runtime being
603 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800604 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700605 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800606 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800607
Brian Carlstromea46f952013-07-30 01:26:50 -0700608 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700609 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
610 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700611
Brian Carlstromea46f952013-07-30 01:26:50 -0700612 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700613 CHECK_STREQ(queue->GetName(), "queue");
614 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700615
Brian Carlstromea46f952013-07-30 01:26:50 -0700616 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700617 CHECK_STREQ(queueNext->GetName(), "queueNext");
618 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700619
Brian Carlstromea46f952013-07-30 01:26:50 -0700620 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700621 CHECK_STREQ(referent->GetName(), "referent");
622 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700623
Brian Carlstromea46f952013-07-30 01:26:50 -0700624 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700625 CHECK_STREQ(zombie->GetName(), "zombie");
626 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700627
Brian Carlstroma663ea52011-08-19 23:33:41 -0700628 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700629 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700630 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800631 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700632 CHECK(klass != nullptr);
633 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700634 // note SetClassRoot does additional validation.
635 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700636 }
637
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700638 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700639
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700640 // disable the slow paths in FindClass and CreatePrimitiveClass now
641 // that Object, Class, and Object[] are setup
642 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700643
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800644 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700645}
646
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700647void ClassLinker::RunRootClinits() {
648 Thread* self = Thread::Current();
649 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800650 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700651 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700652 StackHandleScope<1> hs(self);
653 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700654 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700655 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700656 }
657 }
658}
659
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700660bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800661 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000662 const char* oat_cache_filename,
663 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700664 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700665 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800666
Ian Rogers1d54e732013-05-02 21:10:01 -0700667 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800668 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700669 if (heap->GetImageSpace() == nullptr) {
670 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
671 // out of space anyway it might not matter.
672 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
673 "without an image.", dex_filename);
674 return false;
675 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700676 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800677
Brian Carlstrom6449c622014-02-10 23:48:36 -0800678 std::string dex_file_option("--dex-file=");
679 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800680
Brian Carlstrom6449c622014-02-10 23:48:36 -0800681 std::string oat_fd_option("--oat-fd=");
682 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800683
Brian Carlstrom6449c622014-02-10 23:48:36 -0800684 std::string oat_location_option("--oat-location=");
685 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800686
Brian Carlstrom6449c622014-02-10 23:48:36 -0800687 std::vector<std::string> argv;
688 argv.push_back(dex2oat);
689 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800690 argv.push_back("-classpath");
691 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800692 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800693
Ian Rogers8afeb852014-04-02 14:55:49 -0700694 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800695
Jeff Hao4a200f52014-04-01 14:58:49 -0700696 if (!Runtime::Current()->IsVerificationEnabled()) {
697 argv.push_back("--compiler-filter=verify-none");
698 }
699
Alex Light6e183f22014-07-18 14:57:04 -0700700 if (Runtime::Current()->MustRelocateIfPossible()) {
701 argv.push_back("--runtime-arg");
702 argv.push_back("-Xrelocate");
703 } else {
704 argv.push_back("--runtime-arg");
705 argv.push_back("-Xnorelocate");
706 }
707
Brian Carlstrom6449c622014-02-10 23:48:36 -0800708 if (!kIsTargetBuild) {
709 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700710 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700711
Brian Carlstrom6449c622014-02-10 23:48:36 -0800712 argv.push_back(boot_image_option);
713 argv.push_back(dex_file_option);
714 argv.push_back(oat_fd_option);
715 argv.push_back(oat_location_option);
716 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800717 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800718 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700719 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800720
721 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700722}
723
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700724const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700725 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800726 if (kIsDebugBuild) {
727 for (size_t i = 0; i < oat_files_.size(); ++i) {
728 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700729 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800730 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700731 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
732 oat_files_.push_back(oat_file);
733 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800734}
735
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700736OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
737 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700738 OatFile* oat_file = space->ReleaseOatFile();
739 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700740 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700741 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700742}
743
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100744const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800745 const char* dex_location = dex_file.GetLocation().c_str();
746 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100747 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800748}
749
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100750const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
751 const char* dex_location,
752 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700753 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100754 for (const OatFile* oat_file : oat_files_) {
755 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700756
757 if (oat_location != nullptr) {
758 if (oat_file->GetLocation() != oat_location) {
759 continue;
760 }
761 }
762
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700763 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800764 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700765 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100766 if (oat_dex_file != nullptr) {
767 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800768 }
769 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100770 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800771}
772
Calin Juravle621962a2014-09-02 15:53:55 +0100773
774// Loads all multi dex files from the given oat file returning true on success.
775//
776// Parameters:
777// oat_file - the oat file to load from
778// dex_location - the dex location used to generate the oat file
779// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
780// generated - whether or not the oat_file existed before or was just (re)generated
781// error_msgs - any error messages will be appended here
782// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
783static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
784 const char* dex_location,
785 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700786 bool generated,
787 std::vector<std::string>* error_msgs,
788 std::vector<const DexFile*>* dex_files) {
789 if (oat_file == nullptr) {
790 return false;
791 }
792
793 size_t old_size = dex_files->size(); // To rollback on error.
794
795 bool success = true;
796 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100797 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700798 const char* next_name = next_name_str.c_str();
799
Calin Juravle621962a2014-09-02 15:53:55 +0100800 uint32_t next_location_checksum;
801 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700802 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100803 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
804 // When i=0 the multidex name should be the same as the location name. We already have the
805 // checksum it so we don't need to recompute it.
806 if (dex_location_checksum == nullptr) {
807 next_location_checksum_pointer = nullptr;
808 } else {
809 next_location_checksum = *dex_location_checksum;
810 }
811 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700812 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100813 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700814 }
815
816 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
817
818 if (oat_dex_file == nullptr) {
819 if (i == 0 && generated) {
820 std::string error_msg;
821 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100822 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700823 oat_file->GetLocation().c_str());
824 error_msgs->push_back(error_msg);
825 }
826 break; // Not found, done.
827 }
828
829 // Checksum test. Test must succeed when generated.
830 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100831 if (next_location_checksum_pointer != nullptr) {
832 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700833 }
834
835 if (success) {
836 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
837 if (dex_file == nullptr) {
838 success = false;
839 error_msgs->push_back(error_msg);
840 } else {
841 dex_files->push_back(dex_file);
842 }
843 }
844
845 // When we generated the file, we expect success, or something is terribly wrong.
846 CHECK_EQ(false, generated && !success)
847 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100848 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700849 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
850 }
851
852 if (dex_files->size() == old_size) {
853 success = false; // We did not even find classes.dex
854 }
855
856 if (success) {
857 return true;
858 } else {
859 // Free all the dex files we have loaded.
860 auto it = dex_files->begin() + old_size;
861 auto it_end = dex_files->end();
862 for (; it != it_end; it++) {
863 delete *it;
864 }
865 dex_files->erase(dex_files->begin() + old_size, it_end);
866
867 return false;
868 }
869}
870
871// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
872// complicates the loading process, as we should not use an iterative loading process, because that
873// would register the oat file and dex files that come before the broken one. Instead, check all
874// multidex ahead of time.
875bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
876 std::vector<std::string>* error_msgs,
877 std::vector<const DexFile*>* dex_files) {
878 // 1) Check whether we have an open oat file.
879 // This requires a dex checksum, use the "primary" one.
880 uint32_t dex_location_checksum;
881 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
882 bool have_checksum = true;
883 std::string checksum_error_msg;
884 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100885 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700886 dex_location_checksum_pointer = nullptr;
887 have_checksum = false;
888 }
889
890 bool needs_registering = false;
891
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100892 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
893 dex_location_checksum_pointer);
894 std::unique_ptr<const OatFile> open_oat_file(
895 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700896
897 // 2) If we do not have an open one, maybe there's one on disk already.
898
899 // In case the oat file is not open, we play a locking game here so
900 // that if two different processes race to load and register or generate
901 // (or worse, one tries to open a partial generated file) we will be okay.
902 // This is actually common with apps that use DexClassLoader to work
903 // around the dex method reference limit and that have a background
904 // service running in a separate process.
905 ScopedFlock scoped_flock;
906
907 if (open_oat_file.get() == nullptr) {
908 if (oat_location != nullptr) {
909 // Can only do this if we have a checksum, else error.
910 if (!have_checksum) {
911 error_msgs->push_back(checksum_error_msg);
912 return false;
913 }
914
915 std::string error_msg;
916
917 // We are loading or creating one in the future. Time to set up the file lock.
918 if (!scoped_flock.Init(oat_location, &error_msg)) {
919 error_msgs->push_back(error_msg);
920 return false;
921 }
922
Alex Lighta59dd802014-07-02 16:28:08 -0700923 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700924 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
925 oat_location, &error_msg));
926
927 if (open_oat_file.get() == nullptr) {
928 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
929 dex_location, oat_location, error_msg.c_str());
930 VLOG(class_linker) << compound_msg;
931 error_msgs->push_back(compound_msg);
932 }
933 } else {
934 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100935 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700936 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
937 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100938 kRuntimeISA, error_msgs,
939 &obsolete_file_cleanup_failed));
940 // There's no point in going forward and eventually try to regenerate the
941 // file if we couldn't remove the obsolete one. Mostly likely we will fail
942 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100943 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
944 if (obsolete_file_cleanup_failed) {
945 return false;
946 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700947 }
948 needs_registering = true;
949 }
950
951 // 3) If we have an oat file, check all contained multidex files for our dex_location.
952 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100953 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
954 dex_location_checksum_pointer,
955 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700956 if (success) {
957 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
958 if (needs_registering) {
959 // We opened the oat file, so we must register it.
960 RegisterOatFile(oat_file);
961 }
Alex Light9dcc4572014-08-14 14:16:26 -0700962 // If the file isn't executable we failed patchoat but did manage to get the dex files.
963 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700964 } else {
965 if (needs_registering) {
966 // We opened it, delete it.
967 open_oat_file.reset();
968 } else {
969 open_oat_file.release(); // Do not delete open oat files.
970 }
971 }
972
973 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
974
975 // Need a checksum, fail else.
976 if (!have_checksum) {
977 error_msgs->push_back(checksum_error_msg);
978 return false;
979 }
980
981 // Look in cache location if no oat_location is given.
982 std::string cache_location;
983 if (oat_location == nullptr) {
984 // Use the dalvik cache.
985 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
986 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
987 oat_location = cache_location.c_str();
988 }
989
Alex Light64ad14d2014-08-19 14:23:13 -0700990 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700991 // Definitely need to lock now.
992 if (!scoped_flock.HasFile()) {
993 std::string error_msg;
994 if (!scoped_flock.Init(oat_location, &error_msg)) {
995 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700996 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -0700997 }
998 }
999
Alex Light64ad14d2014-08-19 14:23:13 -07001000 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001001 // Create the oat file.
1002 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1003 oat_location, error_msgs));
1004 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001005
1006 // Failed, bail.
1007 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001008 std::string error_msg;
1009 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1010 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1011 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001012 return false;
1013 }
1014
1015 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001016 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1017 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001018 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001019 if (success) {
1020 RegisterOatFile(open_oat_file.release());
1021 return true;
1022 } else {
1023 return false;
1024 }
1025}
1026
1027const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1028 uint32_t dex_location_checksum,
1029 const char* oat_location,
1030 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001031 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001032 !Runtime::Current()->IsCompiler(),
1033 error_msg));
1034 if (oat_file.get() == nullptr) {
1035 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1036 error_msg->c_str());
1037 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001038 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001039 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001040 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1041 if (image_space != nullptr) {
1042 const ImageHeader& image_header = image_space->GetImageHeader();
1043 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1044 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1045 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1046 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1047 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1048 actual_image_oat_checksum);
1049 return nullptr;
1050 }
1051
1052 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1053 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1054 if (expected_image_oat_offset != actual_image_oat_offset) {
1055 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1056 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1057 actual_image_oat_offset);
1058 return nullptr;
1059 }
1060 int32_t expected_patch_delta = image_header.GetPatchDelta();
1061 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1062 if (expected_patch_delta != actual_patch_delta) {
1063 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1064 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1065 return nullptr;
1066 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001067 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001068
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001069 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1070 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001071 if (oat_dex_file == nullptr) {
1072 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1073 dex_location);
1074 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001075 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001076 uint32_t expected_dex_checksum = dex_location_checksum;
1077 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1078 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001079 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1080 "found 0x%x", oat_location, expected_dex_checksum,
1081 actual_dex_checksum);
1082 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001083 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001084 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1085 if (dex_file.get() != nullptr) {
1086 return oat_file.release();
1087 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001088 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001089 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001090}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001091
Andreas Gampe833a4852014-05-21 18:46:59 -07001092const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1093 int fd, const char* oat_location,
1094 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001095 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001096 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001097 std::string error_msg;
1098 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001099 CHECK(!error_msg.empty());
1100 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001101 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001102 }
Igor Murashkin46774762014-10-22 11:37:02 -07001103 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001104 !Runtime::Current()->IsCompiler(),
1105 &error_msg));
1106 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001107 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1108 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001109 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001110 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001111 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001112
1113 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001114}
1115
Alex Light6e183f22014-07-18 14:57:04 -07001116bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1117 const InstructionSet instruction_set) {
1118 Runtime* runtime = Runtime::Current();
1119 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001120 if (image_space == nullptr) {
1121 return false;
1122 }
Alex Light6e183f22014-07-18 14:57:04 -07001123 uint32_t image_oat_checksum = 0;
1124 if (instruction_set == kRuntimeISA) {
1125 const ImageHeader& image_header = image_space->GetImageHeader();
1126 image_oat_checksum = image_header.GetOatChecksum();
1127 } else {
1128 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1129 image_space->GetImageLocation().c_str(), instruction_set));
1130 image_oat_checksum = image_header->GetOatChecksum();
1131 }
1132 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1133}
1134
1135bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1136 const InstructionSet instruction_set,
1137 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001138 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001139 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001140 if (image_space == nullptr) {
1141 *error_msg = "No image space for verification against";
1142 return false;
1143 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001144
1145 // If the requested instruction set is the same as the current runtime,
1146 // we can use the checksums directly. If it isn't, we'll have to read the
1147 // image header from the image for the right instruction set.
1148 uint32_t image_oat_checksum = 0;
1149 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001150 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001151 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001152 const ImageHeader& image_header = image_space->GetImageHeader();
1153 image_oat_checksum = image_header.GetOatChecksum();
1154 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001155 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001156 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001157 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001158 image_space->GetImageLocation().c_str(), instruction_set));
1159 image_oat_checksum = image_header->GetOatChecksum();
1160 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001161 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001162 }
1163 const OatHeader& oat_header = oat_file->GetOatHeader();
Alex Light6e183f22014-07-18 14:57:04 -07001164 bool ret = ((oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum)
1165 && (oat_header.GetImagePatchDelta() == image_patch_delta)
1166 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin));
1167 if (!ret) {
1168 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1169 oat_file->GetLocation().c_str(),
1170 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1171 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1172 oat_file->GetOatHeader().GetImagePatchDelta(),
1173 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1174 }
1175 return ret;
1176}
1177
1178bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1179 const char* dex_location,
1180 uint32_t dex_location_checksum,
1181 const InstructionSet instruction_set,
1182 std::string* error_msg) {
1183 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1184 return false;
1185 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001186
Brian Carlstromf3632832014-05-20 15:36:53 -07001187 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1188 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001189 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001190 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1191 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001192 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1193 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001194 oat_file->GetLocation().c_str(),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001195 oat_dex_file->GetDexFileLocation().c_str(),
1196 oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001197 }
1198 return false;
1199 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001200
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001201 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001202 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001203}
1204
Alex Lighta59dd802014-07-02 16:28:08 -07001205bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1206 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001207 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001208 std::string* error_msg) {
1209 CHECK(oat_file != nullptr);
1210 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001211 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001212 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001213 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1214 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1215 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001216 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001217 if (oat_dex_file == nullptr) {
1218 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001219 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001220 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001221 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001222 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001223 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001224 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001225 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001226 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001227 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001228 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001229 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001230 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001231 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001232 }
Alex Lighta59dd802014-07-02 16:28:08 -07001233 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001234}
1235
Andreas Gampe833a4852014-05-21 18:46:59 -07001236const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001237 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001238 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001239 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001240 std::vector<std::string>* error_msgs,
1241 bool* obsolete_file_cleanup_failed) {
1242 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001243 bool already_opened = false;
1244 std::string dex_location_str(dex_location);
1245 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1246 &already_opened,
1247 obsolete_file_cleanup_failed,
1248 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001249 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001250 if (oat_file.get() == nullptr) {
1251 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1252 dex_location));
1253 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001254 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001255 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1256 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001257 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1258 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001259 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001260 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001261 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001262 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001263 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1264 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1265 "dex location '%s'. Image checksum incorrect.",
1266 oat_file->GetLocation().c_str(), dex_location));
1267 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001268 } else {
1269 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001270 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001271}
1272
Brian Carlstromae826982011-11-09 01:33:42 -08001273const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001274 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001275 for (size_t i = 0; i < oat_files_.size(); i++) {
1276 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001277 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001278 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001279 return oat_file;
1280 }
1281 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001282 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001283}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001284
Alex Lighta59dd802014-07-02 16:28:08 -07001285const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1286 InstructionSet isa,
1287 bool *already_opened,
1288 bool *obsolete_file_cleanup_failed,
1289 std::vector<std::string>* error_msgs) {
1290 // Find out if we've already opened the file
1291 const OatFile* ret = nullptr;
1292 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1293 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1294 if (ret != nullptr) {
1295 *already_opened = true;
1296 return ret;
1297 }
1298
1299 std::string dalvik_cache;
1300 bool have_android_data = false;
1301 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001302 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001303 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001304 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001305 std::string cache_filename;
1306 if (have_dalvik_cache) {
1307 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1308 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1309 if (ret != nullptr) {
1310 *already_opened = true;
1311 return ret;
1312 }
1313 } else {
1314 // If we need to relocate we should just place odex back where it started.
1315 cache_filename = odex_filename;
1316 }
1317
1318 ret = nullptr;
1319
1320 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1321 //
1322 // Now we do the following:
1323 // 1) Try and open the odex version
1324 // 2) If present, checksum-verified & relocated correctly return it
1325 // 3) Close the odex version to free up its address space.
1326 // 4) Try and open the cache version
1327 // 5) If present, checksum-verified & relocated correctly return it
1328 // 6) Close the cache version to free up its address space.
1329 // 7) If we should relocate:
1330 // a) If we have opened and checksum-verified the odex version relocate it to
1331 // 'cache_filename' and return it
1332 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1333 // it. This should not happen often (I think only the run-test's will hit this case).
1334 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1335 // this point.
1336 // 9) Return nullptr
1337
1338 *already_opened = false;
1339 const Runtime* runtime = Runtime::Current();
1340 CHECK(runtime != nullptr);
1341 bool executable = !runtime->IsCompiler();
1342
1343 std::string odex_error_msg;
1344 bool should_patch_system = false;
1345 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001346 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001347 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001348 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001349 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001350 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001351 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001352 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001353 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001354 &odex_checksum_verified,
1355 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001356 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001357 } else {
1358 if (odex_checksum_verified) {
1359 // We can just relocate
1360 should_patch_system = true;
1361 odex_error_msg = "Image Patches are incorrect";
1362 }
1363 if (odex_oat_file.get() != nullptr) {
1364 have_system_odex = true;
1365 }
Alex Lighta59dd802014-07-02 16:28:08 -07001366 }
1367 }
1368
Alex Lighta59dd802014-07-02 16:28:08 -07001369 std::string cache_error_msg;
1370 bool should_patch_cache = false;
1371 bool cache_checksum_verified = false;
1372 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001373 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001374 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001375 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001376 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001377 &cache_checksum_verified,
1378 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001379 return cache_oat_file.release();
1380 } else if (cache_checksum_verified) {
1381 // We can just relocate
1382 should_patch_cache = true;
1383 cache_error_msg = "Image Patches are incorrect";
1384 }
1385 } else if (have_android_data) {
1386 // dalvik_cache does not exist but android data does. This means we should be able to create
1387 // it, so we should try.
1388 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1389 }
1390
1391 ret = nullptr;
1392 std::string error_msg;
1393 if (runtime->CanRelocate()) {
1394 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001395 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1396 if (space != nullptr) {
1397 const std::string& image_location = space->GetImageLocation();
1398 if (odex_checksum_verified && should_patch_system) {
1399 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1400 } else if (cache_checksum_verified && should_patch_cache) {
1401 CHECK(have_dalvik_cache);
1402 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1403 }
Alex Light84d76052014-08-22 17:49:35 -07001404 } else if (have_system_odex) {
1405 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001406 }
1407 }
1408 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1409 // implicitly: were able to fine where the cached version is but we were unable to use it,
1410 // either as a destination for relocation or to open a file. We should delete it if it is
1411 // there.
1412 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1413 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1414 "searching for dex file %s: %s",
1415 cache_filename.c_str(), dex_location.c_str(),
1416 strerror(errno));
1417 error_msgs->push_back(rm_error_msg);
1418 VLOG(class_linker) << rm_error_msg;
1419 // Let the caller know that we couldn't remove the obsolete file.
1420 // This is a good indication that further writes may fail as well.
1421 *obsolete_file_cleanup_failed = true;
1422 }
1423 }
1424 if (ret == nullptr) {
1425 VLOG(class_linker) << error_msg;
1426 error_msgs->push_back(error_msg);
1427 std::string relocation_msg;
1428 if (runtime->CanRelocate()) {
1429 relocation_msg = StringPrintf(" and relocation failed");
1430 }
1431 if (have_dalvik_cache && cache_checksum_verified) {
1432 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1433 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1434 cache_filename.c_str(), cache_error_msg.c_str(),
1435 relocation_msg.c_str());
1436 } else {
1437 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1438 "dalvik_cache availible)%s.", odex_filename.c_str(),
1439 odex_error_msg.c_str(), relocation_msg.c_str());
1440 }
1441 VLOG(class_linker) << error_msg;
1442 error_msgs->push_back(error_msg);
1443 }
1444 return ret;
1445}
1446
Alex Light9dcc4572014-08-14 14:16:26 -07001447const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1448 InstructionSet isa,
1449 std::string* error_msg) {
1450 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001451 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001452 if (output.get() == nullptr) {
1453 return nullptr;
1454 }
Alex Light84d76052014-08-22 17:49:35 -07001455 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1456 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001457 return output.release();
1458 } else {
1459 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1460 oat_path.c_str());
1461 return nullptr;
1462 }
1463}
1464
Alex Lighta59dd802014-07-02 16:28:08 -07001465const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1466 const std::string& output_oat,
1467 const std::string& image_location,
1468 InstructionSet isa,
1469 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001470 Runtime* runtime = Runtime::Current();
1471 DCHECK(runtime != nullptr);
1472 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001473 // We don't have an image space so there is no point in trying to patchoat.
1474 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1475 << "running without an image. Attempting to use oat file for interpretation.";
1476 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1477 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001478 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001479 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1480 // input_oat but make sure we only do interpretation on it's dex files.
1481 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1482 << "disabled. Attempting to use oat file for interpretation";
1483 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1484 }
Alex Lighta59dd802014-07-02 16:28:08 -07001485 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001486 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001487
1488 std::string isa_arg("--instruction-set=");
1489 isa_arg += GetInstructionSetString(isa);
1490 std::string input_oat_filename_arg("--input-oat-file=");
1491 input_oat_filename_arg += input_oat;
1492 std::string output_oat_filename_arg("--output-oat-file=");
1493 output_oat_filename_arg += output_oat;
1494 std::string patched_image_arg("--patched-image-location=");
1495 patched_image_arg += image_location;
1496
1497 std::vector<std::string> argv;
1498 argv.push_back(patchoat);
1499 argv.push_back(isa_arg);
1500 argv.push_back(input_oat_filename_arg);
1501 argv.push_back(output_oat_filename_arg);
1502 argv.push_back(patched_image_arg);
1503
1504 std::string command_line(Join(argv, ' '));
1505 LOG(INFO) << "Relocate Oat File: " << command_line;
1506 bool success = Exec(argv, error_msg);
1507 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001508 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gampe7ba64962014-10-23 11:37:40 -07001509 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001510 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001511 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1512 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001513 return output.release();
1514 } else if (output.get() != nullptr) {
1515 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1516 "but output file '%s' failed verifcation: %s",
1517 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1518 } else {
1519 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1520 "but was unable to open output file '%s': %s",
1521 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1522 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001523 } else if (!runtime->IsCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001524 // patchoat failed which means we probably don't have enough room to place the output oat file,
1525 // instead of failing we should just run the interpreter from the dex files in the input oat.
1526 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1527 << "for interpretation. patchoat failure was: " << *error_msg;
1528 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001529 } else {
1530 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1531 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1532 error_msg->c_str());
1533 }
1534 return nullptr;
1535}
1536
Andreas Gampe7ba64962014-10-23 11:37:40 -07001537bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001538 bool* checksum_verified,
1539 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001540 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001541 if (image_space == nullptr) {
1542 *error_msg = "No image space present";
1543 return false;
1544 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001545 uint32_t real_image_checksum;
1546 void* real_image_oat_offset;
1547 int32_t real_patch_delta;
1548 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001549 const ImageHeader& image_header = image_space->GetImageHeader();
1550 real_image_checksum = image_header.GetOatChecksum();
1551 real_image_oat_offset = image_header.GetOatDataBegin();
1552 real_patch_delta = image_header.GetPatchDelta();
1553 } else {
1554 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1555 image_space->GetImageLocation().c_str(), isa));
1556 real_image_checksum = image_header->GetOatChecksum();
1557 real_image_oat_offset = image_header->GetOatDataBegin();
1558 real_patch_delta = image_header->GetPatchDelta();
1559 }
1560
1561 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001562 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001563
1564 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1565 *checksum_verified = oat_image_checksum == real_image_checksum;
1566 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001567 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1568 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001569 }
1570
Andreas Gampe7ba64962014-10-23 11:37:40 -07001571 bool offset_verified;
1572 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001573
Andreas Gampe7ba64962014-10-23 11:37:40 -07001574 if (!oat_file->IsPic()) {
1575 // If an oat file is not PIC, we need to check that the image is at the expected location and
1576 // patched in the same way.
1577 void* oat_image_oat_offset =
1578 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1579 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1580 if (!offset_verified) {
1581 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1582 real_image_oat_offset, oat_image_oat_offset);
1583 }
1584
1585 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1586 patch_delta_verified = oat_patch_delta == real_patch_delta;
1587 if (!patch_delta_verified) {
1588 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1589 "received 0x%x)", real_patch_delta, oat_patch_delta);
1590 }
1591 } else {
1592 // If an oat file is PIC, we ignore offset and patching delta.
1593 offset_verified = true;
1594 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001595 }
1596
1597 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001598 if (!ret) {
1599 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001600 }
1601 return ret;
1602}
1603
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001604const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1605 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001606 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001607 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001608 return oat_file;
1609 }
1610
Igor Murashkin46774762014-10-22 11:37:02 -07001611 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001612 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001613}
1614
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001615static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001616 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001617 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1618
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001619 DCHECK(obj != nullptr);
1620 DCHECK(class_linker != nullptr);
Ian Rogers848871b2013-08-05 10:56:33 -07001621
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001622 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001623 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001624 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001625 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers848871b2013-08-05 10:56:33 -07001626 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001627 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1628 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001629 }
1630 }
1631 }
1632}
1633
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001634void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001635 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001636 CHECK(!init_done_);
1637
Mathieu Chartier590fee92013-09-13 13:46:47 -07001638 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001639 gc::Heap* heap = Runtime::Current()->GetHeap();
1640 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001641 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001642 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001643 OatFile& oat_file = GetImageOatFile(space);
1644 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1645 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001646 const char* image_file_location = oat_file.GetOatHeader().
1647 GetStoreValueByKey(OatHeader::kImageLocationKey);
1648 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001649 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1650 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001651 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1652 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001653 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001654 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001655 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1656 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1657 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001658
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001659 StackHandleScope<1> hs(self);
1660 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1661 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1662 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001663 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001664
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001665 // Special case of setting up the String class early so that we can test arbitrary objects
1666 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001667 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001668
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001669 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001670 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001671 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001672 StackHandleScope<1> hs(self);
1673 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001674 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001675 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1676 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001677 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001678 std::string error_msg;
1679 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001680 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001681 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001682 << " from within oat file " << oat_file.GetLocation()
1683 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001684 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001685
1686 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1687
1688 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001689 }
1690
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001691 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1692 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001693 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001694
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001695 // Set entry point to interpreter if in InterpretOnly mode.
1696 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001697 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001698 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001699 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001700
1701 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001702 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001703 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001704
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001705 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001706 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1707 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001708 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001709 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001710 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001711 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1712 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1713 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1714 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1715 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1716 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1717 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1718 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1719 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1720 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001721
Ian Rogers98379392014-02-24 16:53:16 -08001722 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001723
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001724 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001725}
1726
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001727void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1728 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1729 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001730 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1731 it.second.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001732 }
1733 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1734 for (auto& pair : new_class_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001735 mirror::Class* old_ref = pair.second.Read<kWithoutReadBarrier>();
1736 pair.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1737 mirror::Class* new_ref = pair.second.Read<kWithoutReadBarrier>();
1738 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001739 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1740 // corresponding object. This is slow, but luckily for us, this may only happen with a
1741 // concurrent moving GC.
1742 for (auto it = class_table_.lower_bound(pair.first), end = class_table_.end();
1743 it != end && it->first == pair.first; ++it) {
1744 // If the class stored matches the old class, update it to the new value.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001745 if (old_ref == it->second.Read<kWithoutReadBarrier>()) {
1746 it->second = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001747 }
1748 }
1749 }
1750 }
1751 }
1752 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1753 new_class_roots_.clear();
1754 }
1755 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1756 log_new_class_table_roots_ = true;
1757 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1758 log_new_class_table_roots_ = false;
1759 }
1760 // We deliberately ignore the class roots in the image since we
1761 // handle image roots by using the MS/CMS rescanning of dirty cards.
1762}
1763
Brian Carlstroma663ea52011-08-19 23:33:41 -07001764// Keep in sync with InitCallback. Anything we visit, we need to
1765// reinit references to when reinitializing a ClassLinker from a
1766// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001767void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001768 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001769 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001770 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001771 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001772 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001773 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1774 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001775 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001776 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1777 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001778 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001779 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001780 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001781 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1782 new_dex_cache_roots_.clear();
1783 }
1784 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1785 log_new_dex_caches_roots_ = true;
1786 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1787 log_new_dex_caches_roots_ = false;
1788 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001789 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001790 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001791 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1792 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001793 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001794 if (!find_array_class_cache_[i].IsNull()) {
1795 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001796 }
1797 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001798}
1799
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001800void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1801 if (dex_cache_image_class_lookup_required_) {
1802 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001803 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001804 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001805 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001806 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1807 mirror::Class* c = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07001808 if (!visitor(c, arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001809 return;
1810 }
1811 }
1812}
1813
Ian Rogersdbf3be02014-08-29 15:40:08 -07001814static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001815 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001816 classes->insert(c);
1817 return true;
1818}
1819
Ian Rogersdbf3be02014-08-29 15:40:08 -07001820struct GetClassesVisitorArrayArg {
1821 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1822 int32_t index;
1823 bool success;
1824};
1825
1826static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1827 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1828 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1829 if (arg->index < (*arg->classes)->GetLength()) {
1830 (*arg->classes)->Set(arg->index, c);
1831 arg->index++;
1832 return true;
1833 } else {
1834 arg->success = false;
1835 return false;
1836 }
1837}
1838
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001839void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001840 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1841 // is avoiding duplicates.
1842 if (!kMovingClasses) {
1843 std::set<mirror::Class*> classes;
1844 VisitClasses(GetClassesVisitorSet, &classes);
1845 for (mirror::Class* klass : classes) {
1846 if (!visitor(klass, arg)) {
1847 return;
1848 }
1849 }
1850 } else {
1851 Thread* self = Thread::Current();
1852 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001853 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001854 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1855 GetClassesVisitorArrayArg local_arg;
1856 local_arg.classes = &classes;
1857 local_arg.success = false;
1858 // We size the array assuming classes won't be added to the class table during the visit.
1859 // If this assumption fails we iterate again.
1860 while (!local_arg.success) {
1861 size_t class_table_size;
1862 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001863 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogersdbf3be02014-08-29 15:40:08 -07001864 class_table_size = class_table_.size();
1865 }
1866 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1867 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1868 classes.Assign(
1869 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1870 CHECK(classes.Get() != nullptr); // OOME.
1871 local_arg.index = 0;
1872 local_arg.success = true;
1873 VisitClasses(GetClassesVisitorArray, &local_arg);
1874 }
1875 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1876 // If the class table shrank during creation of the clases array we expect null elements. If
1877 // the class table grew then the loop repeats. If classes are created after the loop has
1878 // finished then we don't visit.
1879 mirror::Class* klass = classes->Get(i);
1880 if (klass != nullptr && !visitor(klass, arg)) {
1881 return;
1882 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001883 }
1884 }
1885}
1886
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001887ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001888 mirror::Class::ResetClass();
1889 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001890 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001891 mirror::ArtField::ResetClass();
1892 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001893 mirror::BooleanArray::ResetArrayClass();
1894 mirror::ByteArray::ResetArrayClass();
1895 mirror::CharArray::ResetArrayClass();
1896 mirror::DoubleArray::ResetArrayClass();
1897 mirror::FloatArray::ResetArrayClass();
1898 mirror::IntArray::ResetArrayClass();
1899 mirror::LongArray::ResetArrayClass();
1900 mirror::ShortArray::ResetArrayClass();
1901 mirror::Throwable::ResetClass();
1902 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001903 STLDeleteElements(&boot_class_path_);
1904 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001905}
1906
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001907mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001908 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001909 StackHandleScope<16> hs(self);
1910 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1911 Handle<mirror::DexCache> dex_cache(
1912 hs.NewHandle(down_cast<mirror::DexCache*>(
1913 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1914 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001915 if (dex_cache.Get() == nullptr) {
1916 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001917 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001918 Handle<mirror::String>
1919 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001920 if (location.Get() == nullptr) {
1921 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001922 }
Ian Rogers700a4022014-05-19 16:49:03 -07001923 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001924 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001925 if (strings.Get() == nullptr) {
1926 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001927 }
Ian Rogers700a4022014-05-19 16:49:03 -07001928 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001929 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001930 if (types.Get() == nullptr) {
1931 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001932 }
Ian Rogers700a4022014-05-19 16:49:03 -07001933 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001934 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001935 if (methods.Get() == nullptr) {
1936 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001937 }
Ian Rogers700a4022014-05-19 16:49:03 -07001938 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001939 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001940 if (fields.Get() == nullptr) {
1941 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001942 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001943 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1944 fields.Get());
1945 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001946}
1947
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001948mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001949 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001950 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001951 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001952 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001953 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001954 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1955 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001956 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001957 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001958 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001959 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001960 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001961}
1962
Ian Rogers6fac4472014-02-25 17:01:10 -08001963mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001964 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001965}
1966
Brian Carlstromea46f952013-07-30 01:26:50 -07001967mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001968 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001969 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001970}
1971
Brian Carlstromea46f952013-07-30 01:26:50 -07001972mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001973 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001974 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001975}
1976
Mathieu Chartier590fee92013-09-13 13:46:47 -07001977mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1978 Thread* self, size_t length) {
1979 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1980 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001981}
1982
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001983mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1984 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001985 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001986
1987 // For temporary classes we must wait for them to be retired.
1988 if (init_done_ && klass->IsTemp()) {
1989 CHECK(!klass->IsResolved());
1990 if (klass->IsErroneous()) {
1991 ThrowEarlierClassFailure(klass);
1992 return nullptr;
1993 }
1994 StackHandleScope<1> hs(self);
1995 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1996 ObjectLock<mirror::Class> lock(self, h_class);
1997 // Loop and wait for the resolving thread to retire this class.
1998 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1999 lock.WaitIgnoringInterrupts();
2000 }
2001 if (h_class->IsErroneous()) {
2002 ThrowEarlierClassFailure(h_class.Get());
2003 return nullptr;
2004 }
2005 CHECK(h_class->IsRetired());
2006 // Get the updated class from class table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002007 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002008 }
2009
Brian Carlstromaded5f72011-10-07 17:15:04 -07002010 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002011 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002012 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002013 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2014 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002015 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002016 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2017 ThrowClassCircularityError(h_class.Get());
2018 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002019 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002020 }
2021 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002022 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002023 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002024 }
2025 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002026
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002027 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002028 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002029 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002030 }
2031 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002032 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002033 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002034 return klass;
2035}
2036
Ian Rogers68b56852014-08-29 20:19:11 -07002037typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2038
2039// Search a collection of DexFiles for a descriptor
2040ClassPathEntry FindInClassPath(const char* descriptor,
2041 const std::vector<const DexFile*>& class_path) {
2042 for (size_t i = 0; i != class_path.size(); ++i) {
2043 const DexFile* dex_file = class_path[i];
2044 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002045 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002046 return ClassPathEntry(dex_file, dex_class_def);
2047 }
2048 }
2049 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002050 return ClassPathEntry(static_cast<const DexFile*>(nullptr),
2051 static_cast<const DexFile::ClassDef*>(nullptr));
Ian Rogers68b56852014-08-29 20:19:11 -07002052}
2053
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002054mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2055 Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002056 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002057 if (class_loader->GetClass() !=
2058 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2059 class_loader->GetParent()->GetClass() !=
2060 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2061 return nullptr;
2062 }
2063 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2064 // Check if this would be found in the parent boot class loader.
2065 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002066 mirror::Class* klass = LookupClass(self, descriptor, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002067 if (klass != nullptr) {
2068 return EnsureResolved(self, descriptor, klass);
2069 }
Ian Rogers7b078e82014-09-10 14:44:24 -07002070 klass = DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002071 *pair.second);
2072 if (klass != nullptr) {
2073 return klass;
2074 }
2075 CHECK(self->IsExceptionPending()) << descriptor;
2076 self->ClearException();
2077 } else {
2078 // RegisterDexFile may allocate dex caches (and cause thread suspension).
2079 StackHandleScope<3> hs(self);
2080 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2081 // We need to get the DexPathList and loop through it.
2082 Handle<mirror::ArtField> cookie_field =
2083 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2084 Handle<mirror::ArtField> dex_file_field =
2085 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002086 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002087 mirror::Object* dex_path_list =
2088 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2089 GetObject(class_loader.Get());
2090 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2091 cookie_field.Get() != nullptr) {
2092 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2093 mirror::Object* dex_elements_obj =
2094 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2095 GetObject(dex_path_list);
2096 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2097 // at the mCookie which is a DexFile vector.
2098 if (dex_elements_obj != nullptr) {
2099 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2100 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2101 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2102 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2103 if (element == nullptr) {
2104 // Should never happen, fall back to java code to throw a NPE.
2105 break;
2106 }
2107 mirror::Object* dex_file = dex_file_field->GetObject(element);
2108 if (dex_file != nullptr) {
2109 const uint64_t cookie = cookie_field->GetLong(dex_file);
2110 auto* dex_files =
2111 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2112 if (dex_files == nullptr) {
2113 // This should never happen so log a warning.
2114 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2115 break;
2116 }
2117 for (const DexFile* dex_file : *dex_files) {
2118 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
2119 if (dex_class_def != nullptr) {
2120 RegisterDexFile(*dex_file);
2121 mirror::Class* klass =
Ian Rogers7b078e82014-09-10 14:44:24 -07002122 DefineClass(self, descriptor, class_loader, *dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002123 if (klass == nullptr) {
2124 CHECK(self->IsExceptionPending()) << descriptor;
2125 self->ClearException();
2126 return nullptr;
2127 }
2128 return klass;
2129 }
2130 }
2131 }
2132 }
2133 }
2134 }
2135 }
2136 return nullptr;
2137}
2138
Ian Rogers98379392014-02-24 16:53:16 -08002139mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002140 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002141 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002142 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002143 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002144 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002145 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2146 // for primitive classes that aren't backed by dex files.
2147 return FindPrimitiveClass(descriptor[0]);
2148 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002149 // Find the class in the loaded classes table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002150 mirror::Class* klass = LookupClass(self, descriptor, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002151 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002152 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002153 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002154 // Class is not yet loaded.
2155 if (descriptor[0] == '[') {
Ian Rogers98379392014-02-24 16:53:16 -08002156 return CreateArrayClass(self, descriptor, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002157 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002158 // The boot class loader, search the boot class path.
Ian Rogers68b56852014-08-29 20:19:11 -07002159 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2160 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002161 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2162 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002163 } else {
2164 // The boot class loader is searched ahead of the application class loader, failures are
2165 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2166 // trigger the chaining with a proper stack trace.
2167 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2168 self->SetException(ThrowLocation(), pre_allocated);
2169 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002170 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002171 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002172 // First try with the bootstrap class loader.
2173 if (class_loader.Get() != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002174 klass = LookupClass(self, descriptor, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002175 if (klass != nullptr) {
2176 return EnsureResolved(self, descriptor, klass);
2177 }
2178 }
Ian Rogers63557452014-06-04 16:57:15 -07002179 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2180 // a NoClassDefFoundError being allocated.
Ian Rogers68b56852014-08-29 20:19:11 -07002181 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2182 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002183 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2184 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002185 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002186 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002187 const std::vector<const DexFile*>* class_path;
2188 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002189 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002190 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002191 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002192 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2193 }
Ian Rogers68b56852014-08-29 20:19:11 -07002194 pair = FindInClassPath(descriptor, *class_path);
2195 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002196 return DefineClass(self, descriptor, class_loader, *pair.first, *pair.second);
2197 } else {
2198 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2199 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2200 self->SetException(ThrowLocation(), pre_allocated);
2201 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002202 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002203 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002204 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002205 mirror::Class* klass = FindClassInPathClassLoader(soa, self, descriptor, class_loader);
2206 if (klass != nullptr) {
2207 return klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002208 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002209 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002210 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002211 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002212 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002213 {
2214 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002215 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2216 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002217 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002218 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002219 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002220 }
Ian Rogers68b56852014-08-29 20:19:11 -07002221 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002222 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2223 WellKnownClasses::java_lang_ClassLoader_loadClass,
2224 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002225 }
Ian Rogers98379392014-02-24 16:53:16 -08002226 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002227 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002228 return nullptr;
2229 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002230 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002231 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002232 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002233 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002234 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002235 // success, return mirror::Class*
2236 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002237 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002238 }
Ian Rogers07140832014-09-30 15:43:59 -07002239 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002240}
2241
Ian Rogers7b078e82014-09-10 14:44:24 -07002242mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002243 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002244 const DexFile& dex_file,
2245 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002246 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002247 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002248 bool should_allocate = false;
2249
Brian Carlstromaded5f72011-10-07 17:15:04 -07002250 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002251 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002252 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002253 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002254 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002255 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002256 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002257 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002258 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002259 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2260 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002261 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002262 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002263 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002264 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002265 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002266 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002267 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002268 should_allocate = true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002269 }
2270 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002271 should_allocate = true;
2272 }
2273
2274 if (should_allocate) {
2275 // Allocate a class with the status of not ready.
2276 // Interface object should get the right size here. Regular class will
2277 // figure out the right size later and be replaced with one of the right
2278 // size when the class becomes resolved.
2279 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002280 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002281 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002282 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002283 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002284 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002285 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002286 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002287 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002288 if (self->IsExceptionPending()) {
2289 // An exception occured during load, set status to erroneous while holding klass' lock in case
2290 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002291 if (!klass->IsErroneous()) {
2292 klass->SetStatus(mirror::Class::kStatusError, self);
2293 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002294 return nullptr;
2295 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002296 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002297
Mathieu Chartier590fee92013-09-13 13:46:47 -07002298 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002299 mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor));
Ian Rogersc114b5f2014-07-21 08:55:01 -07002300 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002301 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2302 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002303 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002304 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002305
Brian Carlstromaded5f72011-10-07 17:15:04 -07002306 // Finish loading (if necessary) by finding parents
2307 CHECK(!klass->IsLoaded());
2308 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2309 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002310 if (!klass->IsErroneous()) {
2311 klass->SetStatus(mirror::Class::kStatusError, self);
2312 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002313 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002314 }
2315 CHECK(klass->IsLoaded());
2316 // Link the class (if necessary)
2317 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002318 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002319 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002320
2321 mirror::Class* new_class = nullptr;
2322 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002323 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002324 if (!klass->IsErroneous()) {
2325 klass->SetStatus(mirror::Class::kStatusError, self);
2326 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002327 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002328 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002329 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002330 CHECK(new_class != nullptr) << descriptor;
2331 CHECK(new_class->IsResolved()) << descriptor;
2332
2333 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002334
2335 /*
2336 * We send CLASS_PREPARE events to the debugger from here. The
2337 * definition of "preparation" is creating the static fields for a
2338 * class and initializing them to the standard default values, but not
2339 * executing any code (that comes later, during "initialization").
2340 *
2341 * We did the static preparation in LinkClass.
2342 *
2343 * The class has been prepared and resolved but possibly not yet verified
2344 * at this point.
2345 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002346 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002347
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002348 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002349}
2350
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002351uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2352 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002353 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002354 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002355 size_t num_8 = 0;
2356 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002357 size_t num_32 = 0;
2358 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002359 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002360 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2361 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002362 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002363 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002364 switch (c) {
2365 case 'L':
2366 case '[':
2367 num_ref++;
2368 break;
2369 case 'J':
2370 case 'D':
2371 num_64++;
2372 break;
2373 case 'I':
2374 case 'F':
2375 num_32++;
2376 break;
2377 case 'S':
2378 case 'C':
2379 num_16++;
2380 break;
2381 case 'B':
2382 case 'Z':
2383 num_8++;
2384 break;
2385 default:
2386 LOG(FATAL) << "Unknown descriptor: " << c;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002387 }
2388 }
2389 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002390 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002391}
2392
Ian Rogers97b52f82014-08-14 11:34:07 -07002393OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2394 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002395 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002396 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2397 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002398 *found = false;
2399 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002400 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002401 *found = true;
2402 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002403}
2404
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002405static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2406 uint32_t method_idx) {
2407 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002408 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002409 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002410 ClassDataItemIterator it(dex_file, class_data);
2411 // Skip fields
2412 while (it.HasNextStaticField()) {
2413 it.Next();
2414 }
2415 while (it.HasNextInstanceField()) {
2416 it.Next();
2417 }
2418 // Process methods
2419 size_t class_def_method_index = 0;
2420 while (it.HasNextDirectMethod()) {
2421 if (it.GetMemberIndex() == method_idx) {
2422 return class_def_method_index;
2423 }
2424 class_def_method_index++;
2425 it.Next();
2426 }
2427 while (it.HasNextVirtualMethod()) {
2428 if (it.GetMemberIndex() == method_idx) {
2429 return class_def_method_index;
2430 }
2431 class_def_method_index++;
2432 it.Next();
2433 }
2434 DCHECK(!it.HasNext());
2435 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2436 return 0;
2437}
2438
Ian Rogers97b52f82014-08-14 11:34:07 -07002439const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002440 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002441 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002442 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002443 size_t oat_method_index;
2444 if (method->IsStatic() || method->IsDirect()) {
2445 // Simple case where the oat method index was stashed at load time.
2446 oat_method_index = method->GetMethodIndex();
2447 } else {
2448 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2449 // by search for its position in the declared virtual methods.
2450 oat_method_index = declaring_class->NumDirectMethods();
2451 size_t end = declaring_class->NumVirtualMethods();
2452 bool found = false;
2453 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002454 // Check method index instead of identity in case of duplicate method definitions.
2455 if (method->GetDexMethodIndex() ==
2456 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08002457 found = true;
2458 break;
2459 }
Ian Rogersf320b632012-03-13 18:47:47 -07002460 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002461 }
2462 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2463 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002464 DCHECK_EQ(oat_method_index,
2465 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002466 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002467 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002468 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2469 declaring_class->GetDexClassDefIndex(),
2470 found);
2471 if (!found) {
2472 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002473 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002474 *found = true;
2475 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002476}
2477
2478// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002479const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002480 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002481 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002482 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002483 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002484 bool found;
2485 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002486 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002487 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002488 result = oat_method.GetQuickCode();
2489 }
2490
Ian Rogersef7d42f2014-01-06 12:55:46 -08002491 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002492 if (method->IsNative()) {
2493 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002494 result = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002495 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002496 // No code? Do we expect portable code?
2497 result = GetQuickToPortableBridge();
2498 } else {
2499 // No code? You must mean to go into the interpreter.
2500 result = GetQuickToInterpreterBridge();
2501 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002502 }
2503 return result;
TDYa12785321912012-04-01 15:24:56 -07002504}
2505
Ian Rogersef7d42f2014-01-06 12:55:46 -08002506const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2507 bool* have_portable_code) {
2508 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2509 *have_portable_code = false;
2510 if (method->IsProxyMethod()) {
2511 return GetPortableProxyInvokeHandler();
2512 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002513 bool found;
2514 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002515 const void* result = nullptr;
2516 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002517 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002518 result = oat_method.GetPortableCode();
2519 quick_code = oat_method.GetQuickCode();
2520 }
2521
Ian Rogersef7d42f2014-01-06 12:55:46 -08002522 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002523 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002524 // No code? You must mean to go into the interpreter.
2525 result = GetPortableToInterpreterBridge();
2526 } else {
2527 // No code? But there's quick code, so use a bridge.
2528 result = GetPortableToQuickBridge();
2529 }
2530 } else {
2531 *have_portable_code = true;
2532 }
2533 return result;
2534}
2535
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002536const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2537 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2538 return nullptr;
2539 }
2540 bool found;
2541 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2542 return found ? oat_method.GetQuickCode() : nullptr;
2543}
2544
2545const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2546 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2547 return nullptr;
2548 }
2549 bool found;
2550 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2551 return found ? oat_method.GetPortableCode() : nullptr;
2552}
2553
Ian Rogersef7d42f2014-01-06 12:55:46 -08002554const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2555 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002556 bool found;
2557 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2558 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002559 return nullptr;
2560 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002561 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002562 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002563}
2564
2565const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2566 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002567 bool found;
2568 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2569 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002570 return nullptr;
2571 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002572 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002573 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002574}
2575
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002576// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002577static bool NeedsInterpreter(
2578 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2579 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002580 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002581 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002582 // May return true for native code, in the case of generic JNI
2583 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002584 return true;
2585 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002586#ifdef ART_SEA_IR_MODE
2587 ScopedObjectAccess soa(Thread::Current());
2588 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2589 LOG(INFO) << "Found " << PrettyMethod(method);
2590 return false;
2591 }
2592#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002593 // If interpreter mode is enabled, every method (except native and proxy) must
2594 // be run with interpreter.
2595 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2596 !method->IsNative() && !method->IsProxyMethod();
2597}
2598
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002599void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002600 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002601 if (klass->NumDirectMethods() == 0) {
2602 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002603 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002604 Runtime* runtime = Runtime::Current();
2605 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002606 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2607 return; // OAT file unavailable.
2608 }
Ian Rogers19846512012-02-24 11:42:47 -08002609 }
Alex Light64ad14d2014-08-19 14:23:13 -07002610
Mathieu Chartierf8322842014-05-16 10:59:25 -07002611 const DexFile& dex_file = klass->GetDexFile();
2612 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002613 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002614 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002615 // There should always be class data if there were direct methods.
2616 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002617 ClassDataItemIterator it(dex_file, class_data);
2618 // Skip fields
2619 while (it.HasNextStaticField()) {
2620 it.Next();
2621 }
2622 while (it.HasNextInstanceField()) {
2623 it.Next();
2624 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002625 bool has_oat_class;
2626 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2627 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002628 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002629 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002630 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002631 if (!method->IsStatic()) {
2632 // Only update static methods.
2633 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002634 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002635 const void* portable_code = nullptr;
2636 const void* quick_code = nullptr;
2637 if (has_oat_class) {
2638 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2639 portable_code = oat_method.GetPortableCode();
2640 quick_code = oat_method.GetQuickCode();
2641 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002642 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2643 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002644 if (enter_interpreter) {
2645 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002646 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002647 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002648 quick_code = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002649 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002650 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002651 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002652 quick_code = GetQuickToInterpreterBridge();
2653 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002654 } else {
2655 if (portable_code == nullptr) {
2656 portable_code = GetPortableToQuickBridge();
2657 } else {
2658 have_portable_code = true;
2659 }
2660 if (quick_code == nullptr) {
2661 quick_code = GetQuickToPortableBridge();
2662 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002663 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002664 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2665 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002666 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002667 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002668}
2669
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002670void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002671 const OatFile::OatClass* oat_class,
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002672 const DexFile& dex_file, uint32_t dex_method_index,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002673 uint32_t method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002674 Runtime* runtime = Runtime::Current();
2675 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002676 // The following code only applies to a non-compiler runtime.
2677 return;
2678 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002679 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002680 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2681 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002682 if (oat_class != nullptr) {
2683 // Every kind of method should at least get an invoke stub from the oat_method.
2684 // non-abstract methods also get their code pointers.
2685 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
2686 oat_method.LinkMethod(method.Get());
2687 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002688
Jeff Hao16743632013-05-08 10:59:04 -07002689 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002690 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002691 method->GetEntryPointFromQuickCompiledCode(),
2692 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002693 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002694 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002695 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002696 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002697 }
2698
Brian Carlstrom92827a52011-10-10 15:50:01 -07002699 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002700 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2701 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002702 return;
2703 }
Ian Rogers19846512012-02-24 11:42:47 -08002704
Ian Rogersef7d42f2014-01-06 12:55:46 -08002705 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002706 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002707 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002708 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2709 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002710 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2711 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002712 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002713 if (!method->IsNative()) {
2714 // Set entry point from compiled code if there's no code or in interpreter only mode.
2715 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2716 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2717 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002718 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002719 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2720 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002721 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2722 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2723 have_portable_code = true;
2724 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2725 } else {
2726 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2727 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002728 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002729
Ian Rogers62d6c772013-02-27 08:32:07 -08002730 if (method->IsNative()) {
2731 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002732 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002733
2734 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002735 // We have a native method here without code. Then it should have either the generic JNI
2736 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2737 // TODO: this doesn't handle all the cases where trampolines may be installed.
2738 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2739 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002740 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002741 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002742
Ian Rogers62d6c772013-02-27 08:32:07 -08002743 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002744 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002745 method->GetEntryPointFromQuickCompiledCode(),
2746 method->GetEntryPointFromPortableCompiledCode(),
2747 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002748}
2749
Fred Shih37f05ef2014-07-16 18:38:08 -07002750
Fred Shih37f05ef2014-07-16 18:38:08 -07002751
Ian Rogers7b078e82014-09-10 14:44:24 -07002752void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002753 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002754 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002755 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002756 CHECK(klass.Get() != nullptr);
2757 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002758 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002759 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002760 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002761
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002762 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002763 if (kUseBakerOrBrooksReadBarrier) {
2764 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002765 }
Andreas Gampe51829322014-08-25 15:05:04 -07002766 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002767 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002768 klass->SetAccessFlags(access_flags);
2769 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002770 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002771 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002772
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002773 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002774 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002775
Ian Rogers13735952014-10-08 12:43:28 -07002776 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002777 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002778 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002779 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002780
Ian Rogers97b52f82014-08-14 11:34:07 -07002781
2782 bool has_oat_class = false;
2783 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2784 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2785 &has_oat_class);
2786 if (has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002787 LoadClassMembers(self, dex_file, class_data, klass, class_loader, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002788 }
2789 }
2790 if (!has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002791 LoadClassMembers(self, dex_file, class_data, klass, class_loader, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002792 }
2793}
2794
Ian Rogers7b078e82014-09-10 14:44:24 -07002795void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002796 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002797 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002798 mirror::ClassLoader* class_loader,
2799 const OatFile::OatClass* oat_class) {
2800 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002801 ClassDataItemIterator it(dex_file, class_data);
2802 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002803 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002804 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002805 CHECK(self->IsExceptionPending()); // OOME.
2806 return;
2807 }
2808 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002809 }
2810 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002811 mirror::ObjectArray<mirror::ArtField>* fields =
2812 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002813 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002814 CHECK(self->IsExceptionPending()); // OOME.
2815 return;
2816 }
2817 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002818 }
2819 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002820 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002821 StackHandleScope<1> hs(self);
2822 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002823 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002824 CHECK(self->IsExceptionPending()); // OOME.
2825 return;
2826 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002827 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002828 LoadField(dex_file, it, klass, sfield);
2829 }
2830 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002831 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002832 StackHandleScope<1> hs(self);
2833 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002834 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002835 CHECK(self->IsExceptionPending()); // OOME.
2836 return;
2837 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002838 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002839 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002840 }
2841
Ian Rogers0571d352011-11-03 19:51:38 -07002842 // Load methods.
2843 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002844 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002845 mirror::ObjectArray<mirror::ArtMethod>* directs =
2846 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002847 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002848 CHECK(self->IsExceptionPending()); // OOME.
2849 return;
2850 }
2851 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002852 }
Ian Rogers0571d352011-11-03 19:51:38 -07002853 if (it.NumVirtualMethods() != 0) {
2854 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002855 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2856 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002857 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002858 CHECK(self->IsExceptionPending()); // OOME.
2859 return;
2860 }
2861 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002862 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002863 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002864 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2865 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002866 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002867 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002868 StackHandleScope<1> hs(self);
2869 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002870 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002871 CHECK(self->IsExceptionPending()); // OOME.
2872 return;
2873 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002874 klass->SetDirectMethod(i, method.Get());
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002875 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002876 uint32_t it_method_index = it.GetMemberIndex();
2877 if (last_dex_method_index == it_method_index) {
2878 // duplicate case
2879 method->SetMethodIndex(last_class_def_method_index);
2880 } else {
2881 method->SetMethodIndex(class_def_method_index);
2882 last_dex_method_index = it_method_index;
2883 last_class_def_method_index = class_def_method_index;
2884 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002885 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002886 }
2887 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002888 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002889 StackHandleScope<1> hs(self);
2890 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002891 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002892 CHECK(self->IsExceptionPending()); // OOME.
2893 return;
2894 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002895 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002896 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002897 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002898 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002899 }
2900 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002901}
2902
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002903void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002904 Handle<mirror::Class> klass,
2905 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002906 uint32_t field_idx = it.GetMemberIndex();
2907 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002908 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002909 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002910}
2911
Brian Carlstromea46f952013-07-30 01:26:50 -07002912mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002913 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002914 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002915 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002916 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002917 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002918
Brian Carlstromea46f952013-07-30 01:26:50 -07002919 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002920 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002921 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002922 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002923 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002924 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002925
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002926 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002927 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002928 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002929 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002930
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002931 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002932 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002933 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002934
Andreas Gampe51829322014-08-25 15:05:04 -07002935 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002936
Ian Rogersdfb325e2013-10-30 01:00:44 -07002937 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002938 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002939 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2940 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002941 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002942 klass->SetFinalizable();
2943 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002944 std::string temp;
2945 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002946 // The Enum class declares a "final" finalize() method to prevent subclasses from
2947 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2948 // subclasses, so we exclude it here.
2949 // We also want to avoid setting the flag on Object, where we know that finalize() is
2950 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002951 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2952 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002953 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002954 }
2955 }
2956 }
2957 } else if (method_name[0] == '<') {
2958 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002959 bool is_init = (strcmp("<init>", method_name) == 0);
2960 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002961 if (UNLIKELY(!is_init && !is_clinit)) {
2962 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2963 } else {
2964 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2965 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002966 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002967 access_flags |= kAccConstructor;
2968 }
2969 }
2970 }
2971 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002972
Mathieu Chartier66f19252012-09-18 08:57:04 -07002973 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002974}
2975
Ian Rogers7b078e82014-09-10 14:44:24 -07002976void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002977 StackHandleScope<1> hs(self);
2978 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002979 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2980 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002981 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002982}
2983
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002984void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002985 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002986 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002987 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002988 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002989}
2990
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002991bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002992 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002993 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002994 mirror::DexCache* dex_cache = GetDexCache(i);
2995 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002996 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002997 }
2998 }
2999 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07003000}
3001
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003002bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003003 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07003004 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003005}
3006
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003007void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003008 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003009 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003010 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003011 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3012 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003013 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003014 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003015 if (log_new_dex_caches_roots_) {
3016 // TODO: This is not safe if we can remove dex caches.
3017 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3018 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003019}
3020
Brian Carlstromaded5f72011-10-07 17:15:04 -07003021void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003022 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003023 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003024 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003025 if (IsDexFileRegisteredLocked(dex_file)) {
3026 return;
3027 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003028 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003029 // Don't alloc while holding the lock, since allocation may need to
3030 // suspend all threads and another thread may need the dex_lock_ to
3031 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003032 StackHandleScope<1> hs(self);
3033 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003034 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3035 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003036 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003037 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003038 if (IsDexFileRegisteredLocked(dex_file)) {
3039 return;
3040 }
3041 RegisterDexFileLocked(dex_file, dex_cache);
3042 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003043}
3044
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003045void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003046 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003047 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003048 RegisterDexFileLocked(dex_file, dex_cache);
3049}
3050
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003051mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003052 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003053 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003054 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003055 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003056 if (dex_cache->GetDexFile() == &dex_file) {
3057 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003058 }
3059 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003060 // Search matching by location name.
3061 std::string location(dex_file.GetLocation());
3062 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003063 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003064 if (dex_cache->GetDexFile()->GetLocation() == location) {
3065 return dex_cache;
3066 }
3067 }
3068 // Failure, dump diagnostic and abort.
3069 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003070 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003071 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3072 }
3073 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003074 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003075}
3076
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003077void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003078 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003079 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003080 mirror::DexCache* dex_cache = GetDexCache(i);
3081 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003082 }
3083}
3084
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003085mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003086 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003087 if (UNLIKELY(klass == nullptr)) {
3088 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003089 }
3090 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003091}
3092
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003093mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3094 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003095 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003096 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003097 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003098 StackHandleScope<1> hs(self);
3099 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003100 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003101 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003102 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003103 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3104 const char* descriptor = Primitive::Descriptor(type);
3105 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003106 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003107 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003108}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003109
Brian Carlstrombe977852011-07-19 14:54:54 -07003110// Create an array class (i.e. the class object for the array, not the
3111// array itself). "descriptor" looks like "[C" or "[[[[B" or
3112// "[Ljava/lang/String;".
3113//
3114// If "descriptor" refers to an array of primitives, look up the
3115// primitive type's internally-generated class object.
3116//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003117// "class_loader" is the class loader of the class that's referring to
3118// us. It's used to ensure that we're looking for the element type in
3119// the right context. It does NOT become the class loader for the
3120// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003121//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003122// Returns nullptr with an exception raised on failure.
Ian Rogers98379392014-02-24 16:53:16 -08003123mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003124 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003125 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003126 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003127 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003128 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3129 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003130 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003131 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003132 // We need to accept erroneous classes as component types.
Ian Rogers7b078e82014-09-10 14:44:24 -07003133 component_type.Assign(LookupClass(self, descriptor + 1, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003134 if (component_type.Get() == nullptr) {
3135 DCHECK(self->IsExceptionPending());
3136 return nullptr;
3137 } else {
3138 self->ClearException();
3139 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003140 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003141 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3142 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3143 return nullptr;
3144 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003145 // See if the component type is already loaded. Array classes are
3146 // always associated with the class loader of their underlying
3147 // element type -- an array of Strings goes with the loader for
3148 // java/lang/String -- so we need to look for it there. (The
3149 // caller should have checked for the existence of the class
3150 // before calling here, but they did so with *their* class loader,
3151 // not the component type's loader.)
3152 //
3153 // If we find it, the caller adds "loader" to the class' initiating
3154 // loader list, which should prevent us from going through this again.
3155 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003156 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003157 // are the same, because our caller (FindClass) just did the
3158 // lookup. (Even if we get this wrong we still have correct behavior,
3159 // because we effectively do this lookup again when we add the new
3160 // class to the hash table --- necessary because of possible races with
3161 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003162 if (class_loader.Get() != component_type->GetClassLoader()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003163 mirror::Class* new_class = LookupClass(self, descriptor, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003164 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003165 return new_class;
3166 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003167 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003168
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003169 // Fill out the fields in the Class.
3170 //
3171 // It is possible to execute some methods against arrays, because
3172 // all arrays are subclasses of java_lang_Object_, so we need to set
3173 // up a vtable. We can just point at the one in java_lang_Object_.
3174 //
3175 // Array classes are simple enough that we don't need to do a full
3176 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003177 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003178 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003179 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003180 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003181 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003182 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003183 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003184 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003185 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003186 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003187 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003188 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003189 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003190 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003191 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003192 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003193 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003194 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003195 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003196 }
3197 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003198 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003199 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003200 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003201 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003202 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003203 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003204 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003205 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003206 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003207 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003208 new_class->SetSuperClass(java_lang_Object);
3209 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003210 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003211 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003212 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003213 {
3214 StackHandleScope<mirror::Class::kImtSize> hs(self,
3215 Runtime::Current()->GetImtUnimplementedMethod());
3216 new_class->PopulateEmbeddedImtAndVTable(&hs);
3217 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003218 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003219 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003220 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003221
3222
3223 // All arrays have java/lang/Cloneable and java/io/Serializable as
3224 // interfaces. We need to set that up here, so that stuff like
3225 // "instanceof" works right.
3226 //
3227 // Note: The GC could run during the call to FindSystemClass,
3228 // so we need to make sure the class object is GC-valid while we're in
3229 // there. Do this by clearing the interface list so the GC will just
3230 // think that the entries are null.
3231
3232
3233 // Use the single, global copies of "interfaces" and "iftable"
3234 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003235 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003236 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003237 CHECK(array_iftable != nullptr);
3238 new_class->SetIfTable(array_iftable);
3239 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003240
Elliott Hughes00626c22013-06-14 15:04:14 -07003241 // Inherit access flags from the component type.
3242 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3243 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3244 access_flags &= kAccJavaFlagsMask;
3245 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003246 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003247 access_flags |= kAccAbstract | kAccFinal;
3248 access_flags &= ~kAccInterface;
3249
3250 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003251
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003252 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor));
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003253 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003254 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003255 }
3256 // Another thread must have loaded the class after we
3257 // started but before we finished. Abandon what we've
3258 // done.
3259 //
3260 // (Yes, this happens.)
3261
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003262 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003263}
3264
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003265mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003266 switch (type) {
3267 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003268 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003269 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003270 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003271 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003272 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003273 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003274 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003275 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003276 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003277 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003278 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003279 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003280 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003281 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003282 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003283 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003284 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003285 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003286 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003287 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003288 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003289 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003290 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003291}
3292
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003293mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3294 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003295 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003296 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003297 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003298 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003299 source += " from ";
3300 source += dex_cache->GetLocation()->ToModifiedUtf8();
3301 }
3302 LOG(INFO) << "Loaded class " << descriptor << source;
3303 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003304 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003305 mirror::Class* existing =
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003306 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003307 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003308 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003309 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003310 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003311 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003312 // Check a class loaded with the system class loader matches one in the image if the class
3313 // is in the image.
3314 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003315 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003316 CHECK(klass == existing);
3317 }
3318 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003319 VerifyObject(klass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003320 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003321 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003322 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003323 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003324 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003325}
3326
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003327mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3328 size_t hash) {
3329 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3330 mirror::Class* existing =
3331 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
3332
3333 if (existing == nullptr) {
3334 CHECK(klass->IsProxyClass());
3335 return nullptr;
3336 }
3337
3338 CHECK_NE(existing, klass) << descriptor;
3339 CHECK(!existing->IsResolved()) << descriptor;
3340 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3341
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003342 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3343 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003344 mirror::Class* klass = it->second.Read();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07003345 if (klass == existing) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003346 class_table_.erase(it);
3347 break;
3348 }
3349 }
3350
3351 CHECK(!klass->IsTemp()) << descriptor;
3352 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3353 dex_cache_image_class_lookup_required_) {
3354 // Check a class loaded with the system class loader matches one in the image if the class
3355 // is in the image.
3356 existing = LookupClassFromImage(descriptor);
3357 if (existing != nullptr) {
3358 CHECK(klass == existing) << descriptor;
3359 }
3360 }
3361 VerifyObject(klass);
3362
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003363 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003364 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003365 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003366 }
3367
3368 return existing;
3369}
3370
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003371bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003372 size_t hash = Hash(descriptor);
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003373 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstromf3632832014-05-20 15:36:53 -07003374 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3375 it != end && it->first == hash;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003376 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003377 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003378 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003379 class_table_.erase(it);
Brian Carlstromae826982011-11-09 01:33:42 -08003380 return true;
3381 }
3382 }
3383 return false;
3384}
3385
Ian Rogers7b078e82014-09-10 14:44:24 -07003386mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003387 const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003388 size_t hash = Hash(descriptor);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003389 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003390 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003391 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003392 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003393 return result;
3394 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003395 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003396 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3397 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003398 } else {
3399 // Lookup failed but need to search dex_caches_.
3400 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003401 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003402 InsertClass(descriptor, result, hash);
3403 } else {
3404 // Searching the image dex files/caches failed, we don't want to get into this situation
3405 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3406 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003407 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003408 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3409 MoveImageClassesToClassTable();
3410 }
3411 }
3412 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003413 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003414}
3415
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003416mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
3417 const mirror::ClassLoader* class_loader,
3418 size_t hash) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003419 auto end = class_table_.end();
3420 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003421 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003422 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003423 if (kIsDebugBuild) {
3424 // Check for duplicates in the table.
3425 for (++it; it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003426 mirror::Class* klass2 = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003427 CHECK(!(klass2->GetClassLoader() == class_loader &&
3428 klass2->DescriptorEquals(descriptor)))
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003429 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
3430 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003431 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003432 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003433 return klass;
3434 }
3435 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003436 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003437}
3438
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003439static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3440 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3441 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003442 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003443 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3444 return root->AsObjectArray<mirror::DexCache>();
3445}
3446
3447void ClassLinker::MoveImageClassesToClassTable() {
3448 Thread* self = Thread::Current();
3449 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3450 if (!dex_cache_image_class_lookup_required_) {
3451 return; // All dex cache classes are already in the class table.
3452 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003453 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003454 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003455 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003456 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3457 mirror::DexCache* dex_cache = dex_caches->Get(i);
3458 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3459 for (int32_t j = 0; j < types->GetLength(); j++) {
3460 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003461 if (klass != nullptr) {
3462 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003463 const char* descriptor = klass->GetDescriptor(&temp);
3464 size_t hash = Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003465 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3466 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003467 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
3468 << PrettyClassAndClassLoader(klass);
3469 } else {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003470 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003471 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003472 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003473 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003474 }
3475 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003476 }
3477 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003478 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003479}
3480
3481mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003482 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003483 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3484 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3485 mirror::DexCache* dex_cache = dex_caches->Get(i);
3486 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003487 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003488 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003489 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003490 const DexFile::TypeId* type_id =
3491 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003492 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003493 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3494 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003495 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003496 return klass;
3497 }
3498 }
3499 }
3500 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003501 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003502}
3503
3504void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3505 result.clear();
3506 if (dex_cache_image_class_lookup_required_) {
3507 MoveImageClassesToClassTable();
3508 }
3509 size_t hash = Hash(descriptor);
3510 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003511 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
Mathieu Chartier02e25112013-08-14 16:14:24 -07003512 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003513 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003514 if (klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003515 result.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003516 }
3517 }
3518}
3519
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003520void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003521 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003522 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003523
Ian Rogers9ffb0392012-09-10 11:56:50 -07003524 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003525 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003526 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003527 return;
3528 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003529 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3530 return;
3531 }
jeffhao98eacac2011-09-14 16:11:53 -07003532
Ian Rogers9ffb0392012-09-10 11:56:50 -07003533 // The class might already be erroneous, for example at compile time if we attempted to verify
3534 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003535 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003536 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003537 return;
3538 }
3539
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003540 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003541 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003542 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003543 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003544 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003545 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003546 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003547 }
jeffhao98eacac2011-09-14 16:11:53 -07003548
Jeff Hao4a200f52014-04-01 14:58:49 -07003549 // Skip verification if disabled.
3550 if (!Runtime::Current()->IsVerificationEnabled()) {
3551 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003552 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003553 return;
3554 }
3555
Ian Rogers9ffb0392012-09-10 11:56:50 -07003556 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003557 StackHandleScope<2> hs(self);
3558 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003559 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003560 // Acquire lock to prevent races on verifying the super class.
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003561 ObjectLock<mirror::Class> lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003562
3563 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003564 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003565 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003566 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003567 std::string error_msg(
3568 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3569 PrettyDescriptor(klass.Get()).c_str(),
3570 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003571 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003572 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3573 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003574 self->ClearException();
3575 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003576 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3577 if (cause.Get() != nullptr) {
3578 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003579 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003580 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003581 if (Runtime::Current()->IsCompiler()) {
3582 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3583 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003584 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003585 return;
3586 }
3587 }
3588
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003589 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003590 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003591 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003592 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003593 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003594 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003595 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003596 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003597 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3598 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003599 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003600 return;
3601 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003602 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003603 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003604 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003605 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003606 Runtime::Current()->IsCompiler(),
3607 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003608 }
3609 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003610 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003611 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003612 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3613 << " because: " << error_msg;
3614 }
Ian Rogers1f539342012-10-03 21:09:42 -07003615 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003616 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003617 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003618 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003619 // Even though there were no verifier failures we need to respect whether the super-class
3620 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003621 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003622 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003623 } else {
3624 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003625 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003626 // Pretend a soft failure occured so that we don't consider the class verified below.
3627 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003628 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003629 } else {
3630 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3631 // Soft failures at compile time should be retried at runtime. Soft
3632 // failures at runtime will be handled by slow paths in the generated
3633 // code. Set status accordingly.
3634 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003635 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003636 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003637 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003638 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3639 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003640 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003641 }
3642 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003643 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003644 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003645 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3646 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003647 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003648 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003649 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003650 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003651 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003652 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003653 // Let the interpreter know it by setting the kAccPreverified flag onto each
3654 // method.
3655 // Note: we're going here during compilation and at runtime. When we set the
3656 // kAccPreverified flag when compiling image classes, the flag is recorded
3657 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003658 EnsurePreverifiedMethods(klass);
3659 }
3660}
3661
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003662void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003663 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003664 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003665 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003666 }
jeffhao98eacac2011-09-14 16:11:53 -07003667}
3668
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003669bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3670 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003671 // If we're compiling, we can only verify the class using the oat file if
3672 // we are not compiling the image or if the class we're verifying is not part of
3673 // the app. In other words, we will only check for preverification of bootclasspath
3674 // classes.
3675 if (Runtime::Current()->IsCompiler()) {
3676 // Are we compiling the bootclasspath?
3677 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3678 return false;
3679 }
3680 // We are compiling an app (not the image).
3681
3682 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003683 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003684 return false;
3685 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003686 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003687
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003688 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003689 // In case we run without an image there won't be a backing oat file.
3690 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003691 return false;
3692 }
3693
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003694 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003695 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003696 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3697 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003698 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003699 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003700 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003701 // Compile time verification failed with a soft error. Compile time verification can fail
3702 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003703 // class ... {
3704 // Foo x;
3705 // .... () {
3706 // if (...) {
3707 // v1 gets assigned a type of resolved class Foo
3708 // } else {
3709 // v1 gets assigned a type of unresolved class Bar
3710 // }
3711 // iput x = v1
3712 // } }
3713 // when we merge v1 following the if-the-else it results in Conflict
3714 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3715 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3716 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3717 // at compile time).
3718 return false;
3719 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003720 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003721 // Compile time verification failed with a hard error. This is caused by invalid instructions
3722 // in the class. These errors are unrecoverable.
3723 return false;
3724 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003725 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003726 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3727 // not loading the class.
3728 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3729 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003730 return false;
3731 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003732 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003733 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003734 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003735 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003736
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003737 return false;
3738}
3739
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003740void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003741 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003742 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3743 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3744 }
3745 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3746 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3747 }
3748}
3749
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003750void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003751 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003752 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3753 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003754 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003755 return; // native or abstract method
3756 }
3757 if (code_item->tries_size_ == 0) {
3758 return; // nothing to process
3759 }
Ian Rogers13735952014-10-08 12:43:28 -07003760 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003761 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3762 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3763 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3764 CatchHandlerIterator iterator(handlers_ptr);
3765 for (; iterator.HasNext(); iterator.Next()) {
3766 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3767 // unresolved exception types will be ignored by exception delivery
3768 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003769 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003770 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003771 DCHECK(Thread::Current()->IsExceptionPending());
3772 Thread::Current()->ClearException();
3773 }
3774 }
3775 }
3776 handlers_ptr = iterator.EndDataPointer();
3777 }
3778}
3779
Brian Carlstromea46f952013-07-30 01:26:50 -07003780static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003781static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3782 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003783
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003784mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003785 jobjectArray interfaces, jobject loader,
3786 jobjectArray methods, jobjectArray throws) {
3787 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003788 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003789 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003790 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003791 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003792 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003793 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003794 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003795 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003796 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003797 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3798 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003799 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003800 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003801 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003802 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003803 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003804 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003805
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003806 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003807 {
3808 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003809 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003810 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003811 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003812 }
3813 klass->SetSFields(sfields);
3814 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003815 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3816 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003817 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3818 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003819 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003820 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003821 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003822 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003823 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003824 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003825 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3826 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003827 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3828 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003829 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003830 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003831 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003832 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003833 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003834 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003835 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003836
Ian Rogers466bb252011-10-14 03:29:56 -07003837 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003838 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003839 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003840 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003841 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003842 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003843 }
3844 klass->SetDirectMethods(directs);
3845 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003846 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003847 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003848 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003849 }
3850 klass->SetDirectMethod(0, constructor);
3851 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003852
Mathieu Chartier590fee92013-09-13 13:46:47 -07003853 // Create virtual method using specified prototypes.
3854 size_t num_virtual_methods =
3855 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003856 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003857 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3858 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003859 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003860 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003861 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003862 }
3863 klass->SetVirtualMethods(virtuals);
3864 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003865 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003866 StackHandleScope<1> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003867 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3868 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003869 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003870 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003871 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003872 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003873 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003874 }
3875 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003876 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003877
3878 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003879 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003880 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003881
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003882 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3883 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003884 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003885 // Must hold lock on object when resolved.
3886 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003887 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003888 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003889 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003890 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003891 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003892 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003893 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003894 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003895
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003896 CHECK(klass->IsRetired());
3897 CHECK_NE(klass.Get(), new_class);
3898 klass.Assign(new_class);
3899
3900 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003901 interfaces_sfield->SetObject<false>(klass.Get(),
3902 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003903 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003904 throws_sfield->SetObject<false>(klass.Get(),
3905 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003906
3907 {
3908 // Lock on klass is released. Lock new class object.
3909 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003910 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003911 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003912
3913 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003914 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003915 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003916 CheckProxyConstructor(klass->GetDirectMethod(0));
3917 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003918 StackHandleScope<2> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003919 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3920 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003921 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003922 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3923 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003924 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003925
Mathieu Chartier590fee92013-09-13 13:46:47 -07003926 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003927 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003928 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003929 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3930
3931 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003932 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003933 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003934
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003935 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003936 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003937 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003938 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003939 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003940 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003941 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003942 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003943}
3944
Ian Rogersef7d42f2014-01-06 12:55:46 -08003945std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003946 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003947 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003948 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003949 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3950}
3951
Ian Rogersef7d42f2014-01-06 12:55:46 -08003952mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3953 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003954 DCHECK(proxy_class->IsProxyClass());
3955 DCHECK(proxy_method->IsProxyMethod());
3956 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003957 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003958 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003959 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003960 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003961 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003962 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003963 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003964 break;
3965 }
3966 }
3967 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003968 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003969 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003970 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003971 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003972 return resolved_method;
3973}
3974
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003975
Brian Carlstromea46f952013-07-30 01:26:50 -07003976mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003977 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003978 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003979 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003980 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003981 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003982 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3983 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003984 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3985 // constructor method.
3986 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3987 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003988 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3989 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003990 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3991 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003992 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003993 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003994 }
Ian Rogers466bb252011-10-14 03:29:56 -07003995 // Make this constructor public and fix the class to be our Proxy version
3996 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003997 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003998 return constructor;
3999}
4000
Brian Carlstromea46f952013-07-30 01:26:50 -07004001static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004002 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004003 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004004 CHECK_STREQ(constructor->GetName(), "<init>");
4005 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4006 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004007 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004008}
4009
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004010mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004011 Handle<mirror::Class> klass,
4012 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004013 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4014 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004015 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004016 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004017 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004018 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004019 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004020 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004021 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004022 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004023 }
Ian Rogers466bb252011-10-14 03:29:56 -07004024
4025 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4026 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004027 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004028 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004029
Ian Rogers466bb252011-10-14 03:29:56 -07004030 // At runtime the method looks like a reference and argument saving method, clone the code
4031 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004032 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4033 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004034 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004035
Ian Rogersc2b44472011-12-14 21:17:17 -08004036 return method;
4037}
Jesse Wilson95caa792011-10-12 18:14:17 -04004038
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004039static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4040 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004041 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004042 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004043 CHECK(!prototype->IsFinal());
4044 CHECK(method->IsFinal());
4045 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004046
4047 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4048 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
4049 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
Andreas Gampe58a5af82014-07-31 16:23:49 -07004050 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4051 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004052 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4053
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004054 CHECK_STREQ(method->GetName(), prototype->GetName());
4055 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004056 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004057 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004058}
4059
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004060static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4061 bool can_init_parents)
4062 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004063 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004064 return true;
4065 }
4066 if (!can_init_statics) {
4067 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004068 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004069 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004070 return false;
4071 }
4072 // Check if there are encoded static values needing initialization.
4073 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004074 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004075 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004076 if (dex_class_def->static_values_off_ != 0) {
4077 return false;
4078 }
4079 }
4080 }
4081 if (!klass->IsInterface() && klass->HasSuperClass()) {
4082 mirror::Class* super_class = klass->GetSuperClass();
4083 if (!can_init_parents && !super_class->IsInitialized()) {
4084 return false;
4085 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004086 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004087 return false;
4088 }
4089 }
4090 }
4091 return true;
4092}
4093
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004094bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004095 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004096 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4097
4098 // Are we already initialized and therefore done?
4099 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4100 // an initialized class will never change its state.
4101 if (klass->IsInitialized()) {
4102 return true;
4103 }
4104
4105 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004106 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004107 return false;
4108 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004109
Ian Rogers7b078e82014-09-10 14:44:24 -07004110 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004111 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004112 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004113 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004114
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004115 // Re-check under the lock in case another thread initialized ahead of us.
4116 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004117 return true;
4118 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004119
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004120 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004121 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004122 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004123 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004124 return false;
4125 }
4126
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004127 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004128
4129 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004130 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004131 if (!klass->IsVerified()) {
4132 // We failed to verify, expect either the klass to be erroneous or verification failed at
4133 // compile time.
4134 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004135 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004136 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004137 } else {
4138 CHECK(Runtime::Current()->IsCompiler());
4139 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004140 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004141 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004142 } else {
4143 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004144 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004145 }
4146
Brian Carlstromd1422f82011-09-28 11:37:09 -07004147 // If the class is kStatusInitializing, either this thread is
4148 // initializing higher up the stack or another thread has beat us
4149 // to initializing and we need to wait. Either way, this
4150 // invocation of InitializeClass will not be responsible for
4151 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004152 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004153 // Could have got an exception during verification.
4154 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004155 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004156 return false;
4157 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004158 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004159 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004160 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004161 return true;
4162 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004163 // No. That's fine. Wait for another thread to finish initializing.
4164 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004165 }
4166
4167 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004168 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004169 return false;
4170 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004171 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004172
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004173 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004174
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004175 // From here out other threads may observe that we're initializing and so changes of state
4176 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004177 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004178 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004179
4180 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004181 }
4182
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004183 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004184 if (!klass->IsInterface() && klass->HasSuperClass()) {
4185 mirror::Class* super_class = klass->GetSuperClass();
4186 if (!super_class->IsInitialized()) {
4187 CHECK(!super_class->IsInterface());
4188 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004189 StackHandleScope<1> hs(self);
4190 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004191 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004192 if (!super_initialized) {
4193 // The super class was verified ahead of entering initializing, we should only be here if
4194 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004195 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004196 << "Super class initialization failed for "
4197 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004198 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004199 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004200 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004201 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004202 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004203 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004204 return false;
4205 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004206 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004207 }
4208
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004209 if (klass->NumStaticFields() > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004210 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004211 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004212 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004213 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004214 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004215 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004216 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4217 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004218 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004219 ClassDataItemIterator field_it(dex_file, class_data);
4220 if (value_it.HasNext()) {
4221 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004222 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004223 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004224 StackHandleScope<1> hs(self);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004225 Handle<mirror::ArtField> field(hs.NewHandle(
4226 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004227 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004228 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004229 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004230 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004231 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004232 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004233 }
4234 }
4235 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004236
Ian Rogersd91d6d62013-09-25 20:26:14 -07004237 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004238 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004239 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004240 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004241 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004242 }
4243
Ian Rogers7b078e82014-09-10 14:44:24 -07004244 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004245 uint64_t t1 = NanoTime();
4246
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004247 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004248 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004249 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004250
4251 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004252 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004253 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004254 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004255 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004256 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4257 RuntimeStats* thread_stats = self->GetStats();
4258 ++global_stats->class_init_count;
4259 ++thread_stats->class_init_count;
4260 global_stats->class_init_time_ns += (t1 - t0);
4261 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004262 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004263 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004264 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004265 std::string temp;
4266 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004267 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004268 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004269 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004270 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004271 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004272 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004273 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004274}
4275
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004276bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004277 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004278 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004279 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004280 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004281 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004282 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004283
4284 // When we wake up, repeat the test for init-in-progress. If
4285 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004286 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004287 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004288 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004289 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004290 return false;
4291 }
4292 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004293 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004294 continue;
4295 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004296 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004297 // Compile time initialization failed.
4298 return false;
4299 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004300 if (klass->IsErroneous()) {
4301 // The caller wants an exception, but it was thrown in a
4302 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004303 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004304 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004305 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004306 return false;
4307 }
4308 if (klass->IsInitialized()) {
4309 return true;
4310 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004311 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004312 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004313 }
Ian Rogers07140832014-09-30 15:43:59 -07004314 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004315}
4316
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004317bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004318 if (klass->IsInterface()) {
4319 return true;
4320 }
Ian Rogers151f2212014-05-06 11:27:27 -07004321 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004322 Thread* self = Thread::Current();
4323 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004324 MutableMethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4325 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004326 if (klass->HasSuperClass() &&
4327 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004328 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4329 mh.ChangeMethod(klass->GetVTableEntry(i));
4330 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004331 if (mh.GetMethod() != super_mh.GetMethod() &&
Ian Rogersded66a02014-10-28 18:12:55 -07004332 !mh.HasSameSignatureWithDifferentClassLoaders(self, &super_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004333 ThrowLinkageError(klass.Get(),
4334 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004335 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004336 PrettyMethod(mh.GetMethod()).c_str(),
4337 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004338 return false;
4339 }
4340 }
4341 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004342 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004343 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4344 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4345 for (uint32_t j = 0; j < num_methods; ++j) {
4346 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4347 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004348 if (mh.GetMethod() != super_mh.GetMethod() &&
Ian Rogersded66a02014-10-28 18:12:55 -07004349 !mh.HasSameSignatureWithDifferentClassLoaders(self, &super_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004350 ThrowLinkageError(klass.Get(),
4351 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004352 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004353 PrettyMethod(mh.GetMethod()).c_str(),
4354 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004355 return false;
4356 }
4357 }
4358 }
4359 }
4360 return true;
4361}
4362
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004363bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4364 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004365 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004366 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004367 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004368 return true;
4369 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004370 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004371 if (!success) {
4372 if (can_init_fields && can_init_parents) {
4373 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4374 }
4375 } else {
4376 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004377 }
4378 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004379}
4380
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004381void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4382 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4383 if (fields != nullptr) {
4384 for (int index = 0; index < fields->GetLength(); index ++) {
4385 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4386 fields->Get(index)->SetDeclaringClass(new_class);
4387 }
4388 }
4389 }
4390
4391 fields = new_class->GetSFields();
4392 if (fields != nullptr) {
4393 for (int index = 0; index < fields->GetLength(); index ++) {
4394 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4395 fields->Get(index)->SetDeclaringClass(new_class);
4396 }
4397 }
4398 }
4399
4400 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4401 if (methods != nullptr) {
4402 for (int index = 0; index < methods->GetLength(); index ++) {
4403 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4404 methods->Get(index)->SetDeclaringClass(new_class);
4405 }
4406 }
4407 }
4408
4409 methods = new_class->GetVirtualMethods();
4410 if (methods != nullptr) {
4411 for (int index = 0; index < methods->GetLength(); index ++) {
4412 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4413 methods->Get(index)->SetDeclaringClass(new_class);
4414 }
4415 }
4416 }
4417}
4418
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004419bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4420 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004421 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004422 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004423
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004424 if (!LinkSuperClass(klass)) {
4425 return false;
4426 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004427 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4428 self, Runtime::Current()->GetImtUnimplementedMethod());
4429 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004430 return false;
4431 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004432 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004433 return false;
4434 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004435 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004436 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004437 return false;
4438 }
4439 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004440 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004441
4442 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4443 // We don't need to retire this class as it has no embedded tables or it was created the
4444 // correct size during class linker initialization.
4445 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4446
4447 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004448 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004449 }
4450
4451 // This will notify waiters on klass that saw the not yet resolved
4452 // class in the class_table_ during EnsureResolved.
4453 klass->SetStatus(mirror::Class::kStatusResolved, self);
4454 *new_class = klass.Get();
4455 } else {
4456 CHECK(!klass->IsResolved());
4457 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004458 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004459 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004460 CHECK(self->IsExceptionPending()); // Expect an OOME.
4461 klass->SetStatus(mirror::Class::kStatusError, self);
4462 return false;
4463 }
4464
4465 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4466 StackHandleScope<1> hs(self);
4467 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4468 ObjectLock<mirror::Class> lock(self, new_class_h);
4469
4470 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4471
4472 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004473 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004474
4475 // This will notify waiters on temp class that saw the not yet resolved class in the
4476 // class_table_ during EnsureResolved.
4477 klass->SetStatus(mirror::Class::kStatusRetired, self);
4478
4479 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4480 // This will notify waiters on new_class that saw the not yet resolved
4481 // class in the class_table_ during EnsureResolved.
4482 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004483 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004484 return true;
4485}
4486
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004487bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004488 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004489 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4490 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004491 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004492 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004493 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004494 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004495 return false;
4496 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004497 // Verify
4498 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004499 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004500 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004501 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004502 return false;
4503 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004504 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004505 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004506 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004507 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004508 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004509 for (size_t i = 0; i < interfaces->Size(); i++) {
4510 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004511 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004512 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004513 DCHECK(Thread::Current()->IsExceptionPending());
4514 return false;
4515 }
4516 // Verify
4517 if (!klass->CanAccess(interface)) {
4518 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004519 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004520 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004521 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004522 return false;
4523 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004524 }
4525 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004526 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004527 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004528 return true;
4529}
4530
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004531bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004532 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004533 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004534 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004535 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004536 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004537 return false;
4538 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004539 return true;
4540 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004541 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004542 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4543 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004544 return false;
4545 }
4546 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004547 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004548 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004549 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004550 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004551 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004552 return false;
4553 }
4554 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004555 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004556 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004557 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004558 return false;
4559 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004560
Brian Carlstromf3632832014-05-20 15:36:53 -07004561 // Inherit kAccClassIsFinalizable from the superclass in case this
4562 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004563 if (super->IsFinalizable()) {
4564 klass->SetFinalizable();
4565 }
4566
Elliott Hughes2da50362011-10-10 16:57:08 -07004567 // Inherit reference flags (if any) from the superclass.
4568 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4569 if (reference_flags != 0) {
4570 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4571 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004572 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004573 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004574 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004575 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004576 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004577 return false;
4578 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004579
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004580 if (kIsDebugBuild) {
4581 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004582 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004583 CHECK(super->IsResolved());
4584 super = super->GetSuperClass();
4585 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004586 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004587 return true;
4588}
4589
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004590// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004591bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004592 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4593 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004594 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004595 if (klass->IsInterface()) {
4596 // No vtable.
4597 size_t count = klass->NumVirtualMethods();
4598 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004599 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004600 return false;
4601 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004602 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004603 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004604 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004605 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4606 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004607 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004608 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004609}
4610
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004611// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4612// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4613// caches in the implementation below.
4614class MethodNameAndSignatureComparator FINAL : public ValueObject {
4615 public:
4616 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4617 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4618 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4619 name_(nullptr), name_len_(0) {
4620 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4621 }
4622
4623 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4624 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4625 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4626 const DexFile* other_dex_file = other->GetDexFile();
4627 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4628 if (dex_file_ == other_dex_file) {
4629 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4630 }
4631 if (name_ == nullptr) {
4632 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4633 }
4634 uint32_t other_name_len;
4635 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4636 &other_name_len);
4637 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4638 return false;
4639 }
4640 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4641 }
4642
4643 private:
4644 // Dex file for the method to compare against.
4645 const DexFile* const dex_file_;
4646 // MethodId for the method to compare against.
4647 const DexFile::MethodId* const mid_;
4648 // Lazily computed name from the dex file's strings.
4649 const char* name_;
4650 // Lazily computed name length.
4651 uint32_t name_len_;
4652};
4653
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004654bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004655 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004656 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004657 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4658 const size_t max_count = num_virtual_methods + super_vtable_length;
4659 size_t actual_count = super_vtable_length;
4660 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004661 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004662 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004663 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4664 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4665 if (UNLIKELY(vtable.Get() == nullptr)) {
4666 CHECK(self->IsExceptionPending()); // OOME.
4667 return false;
4668 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004669 for (size_t i = 0; i < super_vtable_length; i++) {
4670 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004671 }
4672 } else {
Mingyao Yang38eecb02014-08-13 14:51:03 -07004673 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class.Get());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004674 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count));
4675 if (UNLIKELY(vtable.Get() == nullptr)) {
4676 CHECK(self->IsExceptionPending()); // OOME.
4677 return false;
4678 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004679 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004680
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004681 // See if any of our virtual methods override the superclass.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004682 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004683 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004684 MethodNameAndSignatureComparator
4685 virtual_method_name_comparator(local_method->GetInterfaceMethodIfProxy());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004686 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004687 for (; j < actual_count; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004688 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004689 if (super_method->GetDeclaringClass() == klass.Get()) {
4690 continue; // A previously overridden method.
4691 }
4692 if (virtual_method_name_comparator.HasSameNameAndSignature(super_method)) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004693 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4694 super_method->GetAccessFlags())) {
Elliott Hughes39717372012-07-13 16:21:23 -07004695 if (super_method->IsFinal()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004696 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
Elliott Hughes39717372012-07-13 16:21:23 -07004697 PrettyMethod(local_method).c_str(),
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004698 super_method->GetDeclaringClassDescriptor());
Elliott Hughes39717372012-07-13 16:21:23 -07004699 return false;
4700 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004701 vtable->SetWithoutChecks<false>(j, local_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004702 local_method->SetMethodIndex(j);
4703 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004704 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004705 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
4706 << " would have incorrectly overridden the package-private method in "
4707 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004708 }
4709 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004710 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004711 // Not overriding, append.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004712 vtable->SetWithoutChecks<false>(actual_count, local_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004713 local_method->SetMethodIndex(actual_count);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004714 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004715 }
4716 }
4717 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004718 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004719 return false;
4720 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004721 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004722 CHECK_LE(actual_count, max_count);
4723 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004724 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004725 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004726 CHECK(self->IsExceptionPending()); // OOME.
4727 return false;
4728 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004729 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004730 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004731 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004732 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004733 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004734 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4735 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004736 return false;
4737 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004738 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4739 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004740 CHECK(self->IsExceptionPending()); // OOME.
4741 return false;
4742 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004743 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004744 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004745 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004746 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004747 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004748 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004749 }
4750 return true;
4751}
4752
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004753bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4754 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4755 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004756 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004757 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004758 const bool has_superclass = klass->HasSuperClass();
4759 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4760 const bool have_interfaces = interfaces.Get() != nullptr;
4761 const size_t num_interfaces =
4762 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4763 if (num_interfaces == 0) {
4764 if (super_ifcount == 0) {
4765 // Class implements no interfaces.
4766 DCHECK_EQ(klass->GetIfTableCount(), 0);
4767 DCHECK(klass->GetIfTable() == nullptr);
4768 return true;
4769 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004770 // Class implements same interfaces as parent, are any of these not marker interfaces?
4771 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004772 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004773 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004774 if (super_iftable->GetMethodArrayCount(i) > 0) {
4775 has_non_marker_interface = true;
4776 break;
4777 }
4778 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004779 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004780 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004781 klass->SetIfTable(super_iftable);
4782 return true;
4783 }
4784 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004785 size_t ifcount = super_ifcount + num_interfaces;
4786 for (size_t i = 0; i < num_interfaces; i++) {
4787 mirror::Class* interface = have_interfaces ?
4788 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4789 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004790 if (UNLIKELY(!interface->IsInterface())) {
4791 std::string temp;
4792 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4793 PrettyDescriptor(klass.Get()).c_str(),
4794 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4795 return false;
4796 }
4797 ifcount += interface->GetIfTableCount();
4798 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004799 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004800 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004801 CHECK(self->IsExceptionPending()); // OOME.
4802 return false;
4803 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004804 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004805 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004806 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004807 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004808 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004809 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004810 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004811 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004812 // Flatten the interface inheritance hierarchy.
4813 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004814 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004815 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4816 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004817 // Check if interface is already in iftable
4818 bool duplicate = false;
4819 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004820 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004821 if (existing_interface == interface) {
4822 duplicate = true;
4823 break;
4824 }
4825 }
4826 if (!duplicate) {
4827 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004828 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004829 // Add this interface's non-duplicate super-interfaces.
4830 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004831 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004832 bool super_duplicate = false;
4833 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004834 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004835 if (existing_interface == super_interface) {
4836 super_duplicate = true;
4837 break;
4838 }
4839 }
4840 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004841 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004842 }
4843 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004844 }
4845 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004846 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004847 // Shrink iftable in case duplicates were found
4848 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004849 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004850 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004851 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004852 CHECK(self->IsExceptionPending()); // OOME.
4853 return false;
4854 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004855 ifcount = idx;
4856 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004857 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004858 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004859 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004860 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004861 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004862 return true;
4863 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004864 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004865 size_t max_miranda_methods = 0; // The max size of miranda_list.
4866 for (size_t i = 0; i < ifcount; ++i) {
4867 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4868 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004869 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004870 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004871 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4872 hs.NewHandle(klass->GetVTableDuringLinking()));
4873 // Copy the IMT from the super class if possible.
4874 bool extend_super_iftable = false;
4875 if (has_superclass) {
4876 mirror::Class* super_class = klass->GetSuperClass();
4877 extend_super_iftable = true;
4878 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4879 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4880 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
4881 }
4882 } else {
4883 // No imt in the super class, need to reconstruct from the iftable.
4884 mirror::IfTable* if_table = super_class->GetIfTable();
4885 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4886 const size_t length = super_class->GetIfTableCount();
4887 for (size_t i = 0; i < length; ++i) {
4888 mirror::Class* interface = iftable->GetInterface(i);
4889 const size_t num_virtuals = interface->NumVirtualMethods();
4890 const size_t method_array_count = if_table->GetMethodArrayCount(i);
4891 DCHECK_EQ(num_virtuals, method_array_count);
4892 if (method_array_count == 0) {
4893 continue;
4894 }
4895 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
4896 for (size_t j = 0; j < num_virtuals; ++j) {
4897 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
4898 if (method->IsMiranda()) {
4899 continue;
4900 }
4901 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
4902 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4903 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4904 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4905 out_imt->SetReference(imt_index, method);
4906 } else if (imt_ref != conflict_method) {
4907 out_imt->SetReference(imt_index, conflict_method);
4908 }
4909 }
4910 }
4911 }
4912 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004913 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004914 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004915 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004916 if (num_methods > 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004917 StackHandleScope<2> hs(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004918 const bool is_super = i < super_ifcount;
4919 const bool super_interface = is_super && extend_super_iftable;
4920 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
4921 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
4922 if (super_interface) {
4923 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
4924 DCHECK(if_table != nullptr);
4925 DCHECK(if_table->GetMethodArray(i) != nullptr);
4926 // If we are working on a super interface, try extending the existing method array.
4927 method_array = hs.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
4928 AsObjectArray<mirror::ArtMethod>());
4929 // We are overwriting a super class interface, try to only virtual methods instead of the
4930 // whole vtable.
4931 input_array = hs.NewHandle(klass->GetVirtualMethods());
4932 } else {
4933 method_array = hs.NewHandle(AllocArtMethodArray(self, num_methods));
4934 // A new interface, we need the whole vtable incase a new interface method is implemented
4935 // in the whole superclass.
4936 input_array = vtable;
4937 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004938 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004939 CHECK(self->IsExceptionPending()); // OOME.
4940 return false;
4941 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004942 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004943 if (input_array.Get() == nullptr) {
4944 // If the added virtual methods is empty, do nothing.
4945 DCHECK(super_interface);
4946 continue;
4947 }
Ian Rogers62d6c772013-02-27 08:32:07 -08004948 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004949 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004950 MethodNameAndSignatureComparator interface_name_comparator(interface_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004951 int32_t k;
4952 // For each method listed in the interface's method list, find the
4953 // matching method in our class's method list. We want to favor the
4954 // subclass over the superclass, which just requires walking
4955 // back from the end of the vtable. (This only matters if the
4956 // superclass defines a private method and this class redefines
4957 // it -- otherwise it would use the same vtable slot. In .dex files
4958 // those don't end up in the virtual method table, so it shouldn't
4959 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004960 for (k = input_array->GetLength() - 1; k >= 0; --k) {
4961 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004962 mirror::ArtMethod* vtable_method_for_name_comparison =
4963 vtable_method->GetInterfaceMethodIfProxy();
4964 if (interface_name_comparator.HasSameNameAndSignature(
4965 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004966 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004967 ThrowIllegalAccessError(
4968 klass.Get(),
4969 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004970 PrettyMethod(vtable_method).c_str(),
4971 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004972 return false;
4973 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004974 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004975 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004976 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4977 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4978 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4979 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4980 out_imt->SetReference(imt_index, vtable_method);
4981 } else if (imt_ref != conflict_method) {
4982 // If we are not a conflict and we have the same signature and name as the imt entry,
4983 // it must be that we overwrote a superclass vtable entry.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004984 MethodNameAndSignatureComparator
4985 imt_ref_name_comparator(imt_ref->GetInterfaceMethodIfProxy());
4986 if (imt_ref_name_comparator.HasSameNameAndSignature(
4987 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004988 out_imt->SetReference(imt_index, vtable_method);
4989 } else {
4990 out_imt->SetReference(imt_index, conflict_method);
4991 }
Jeff Hao88474b42013-10-23 16:24:40 -07004992 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004993 break;
4994 }
4995 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004996 if (k < 0 && !super_interface) {
4997 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004998 for (size_t l = 0; l < miranda_list_size; ++l) {
4999 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005000 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005001 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005002 break;
5003 }
5004 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005005 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005006 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005007 miranda_method = interface_method->Clone(self)->AsArtMethod();
5008 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005009 CHECK(self->IsExceptionPending()); // OOME.
5010 return false;
5011 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005012 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005013 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005014 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005015 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005016 }
5017 }
5018 }
5019 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005020 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005021 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005022 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005023 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5024 if (old_method_count == 0) {
5025 virtuals = AllocArtMethodArray(self, new_method_count);
5026 } else {
5027 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5028 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005029 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005030 CHECK(self->IsExceptionPending()); // OOME.
5031 return false;
5032 }
5033 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005034
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005035 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005036 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005037 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005038 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005039 CHECK(self->IsExceptionPending()); // OOME.
5040 return false;
5041 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005042 for (size_t i = 0; i < miranda_list_size; ++i) {
5043 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005044 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005045 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5046 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5047 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005048 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005049 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005050 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005051 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005052 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005053
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005054 if (kIsDebugBuild) {
5055 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
5056 for (int i = 0; i < vtable->GetLength(); ++i) {
5057 CHECK(vtable->GetWithoutChecks(i) != nullptr);
5058 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005059 }
5060
Ian Rogers7b078e82014-09-10 14:44:24 -07005061 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005062 return true;
5063}
5064
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005065bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005066 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005067 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005068}
5069
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005070bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005071 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005072 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005073}
5074
Brian Carlstromdbc05252011-09-09 01:59:59 -07005075struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005076 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5077 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005078 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005079 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005080 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005081 // 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 -07005082 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5083 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005084 if (type1 != type2) {
5085 bool is_primitive1 = type1 != Primitive::kPrimNot;
5086 bool is_primitive2 = type2 != Primitive::kPrimNot;
Fred Shih37f05ef2014-07-16 18:38:08 -07005087 if (type1 != type2) {
5088 if (is_primitive1 && is_primitive2) {
5089 // Larger primitive types go first.
5090 return Primitive::ComponentSize(type1) > Primitive::ComponentSize(type2);
5091 } else {
5092 // Reference always goes first.
5093 return !is_primitive1;
5094 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08005095 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005096 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005097 // same basic group? then sort by string.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005098 return strcmp(field1->GetName(), field2->GetName()) < 0;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005099 }
5100};
5101
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005102bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005103 size_t* class_size) {
5104 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005105 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005106 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005107
Brian Carlstromea46f952013-07-30 01:26:50 -07005108 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005109 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005110
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005111 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005112 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005113 if (is_static) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005114 uint32_t base = sizeof(mirror::Class); // Static fields come after the class.
5115 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
5116 // Static fields come after the embedded tables.
5117 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
Fred Shih37f05ef2014-07-16 18:38:08 -07005118 0, 0, 0, 0, 0);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005119 }
5120 field_offset = MemberOffset(base);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005121 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005122 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005123 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005124 CHECK(super_class->IsResolved())
5125 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005126 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005127 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005128 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005129
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005130 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005131
Brian Carlstromdbc05252011-09-09 01:59:59 -07005132 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005133 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005134 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005135 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005136 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005137 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005138 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005139 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005140 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005141 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005142 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5143 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005144
Fred Shih381e4ca2014-08-25 17:24:27 -07005145 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005146 size_t current_field = 0;
5147 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005148 FieldGaps gaps;
5149
Brian Carlstromdbc05252011-09-09 01:59:59 -07005150 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005151 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005152 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005153 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005154 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005155 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005156 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005157 if (UNLIKELY(!IsAligned<4>(field_offset.Uint32Value()))) {
5158 MemberOffset old_offset = field_offset;
5159 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5160 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5161 }
5162 DCHECK(IsAligned<4>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005163 grouped_and_sorted_fields.pop_front();
5164 num_reference_fields++;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005165 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005166 field->SetOffset(field_offset);
5167 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005168 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005169 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5170 // otherwise we could end up with suboptimal gap fills.
5171 ShuffleForward<8>(num_fields, &current_field, &field_offset,
5172 fields, &grouped_and_sorted_fields, &gaps);
5173 ShuffleForward<4>(num_fields, &current_field, &field_offset,
5174 fields, &grouped_and_sorted_fields, &gaps);
5175 ShuffleForward<2>(num_fields, &current_field, &field_offset,
5176 fields, &grouped_and_sorted_fields, &gaps);
5177 ShuffleForward<1>(num_fields, &current_field, &field_offset,
5178 fields, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005179 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5180 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005181 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005182
Elliott Hughesadb460d2011-10-05 17:02:34 -07005183 // 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 -07005184 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005185 // We know there are no non-reference fields in the Reference classes, and we know
5186 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005187 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005188 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005189 --num_reference_fields;
5190 }
5191
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005192 if (kIsDebugBuild) {
5193 // Make sure that all reference fields appear before
5194 // non-reference fields, and all double-wide fields are aligned.
5195 bool seen_non_ref = false;
5196 for (size_t i = 0; i < num_fields; i++) {
5197 mirror::ArtField* field = fields->Get(i);
Ian Rogerscf7f1912014-10-22 22:06:39 -07005198 if ((false)) { // enable to debug field layout
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005199 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005200 << " class=" << PrettyClass(klass.Get())
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005201 << " field=" << PrettyField(field)
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07005202 << " offset="
5203 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005204 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005205 Primitive::Type type = field->GetTypeAsPrimitiveType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005206 bool is_primitive = type != Primitive::kPrimNot;
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005207 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005208 strcmp("referent", field->GetName()) == 0) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005209 is_primitive = true; // We lied above, so we have to expect a lie here.
5210 }
5211 if (is_primitive) {
5212 if (!seen_non_ref) {
5213 seen_non_ref = true;
Brian Carlstromf3632832014-05-20 15:36:53 -07005214 DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005215 }
5216 } else {
Brian Carlstromf3632832014-05-20 15:36:53 -07005217 DCHECK(!seen_non_ref) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005218 }
5219 }
5220 if (!seen_non_ref) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005221 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005222 }
5223 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005224
5225 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005226 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005227 if (is_static) {
5228 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005229 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005230 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005231 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005232 if (!klass->IsVariableSize()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005233 std::string temp;
5234 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005235 size_t previous_size = klass->GetObjectSize();
5236 if (previous_size != 0) {
5237 // Make sure that we didn't originally have an incorrect size.
Ian Rogers1ff3c982014-08-12 02:30:58 -07005238 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005239 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005240 klass->SetObjectSize(size);
5241 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005242 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005243 return true;
5244}
5245
5246// Set the bitmap of reference offsets, refOffsets, from the ifields
5247// list.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005248void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005249 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005250 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005251 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005252 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005253 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005254 // Compute reference offsets unless our superclass overflowed.
5255 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5256 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
5257 mirror::ObjectArray<mirror::ArtField>* fields = klass->GetIFields();
5258 // All of the fields that contain object references are guaranteed
5259 // to be at the beginning of the fields list.
5260 for (size_t i = 0; i < num_reference_fields; ++i) {
5261 // Note that byte_offset is the offset from the beginning of
5262 // object, not the offset into instance data
5263 mirror::ArtField* field = fields->Get(i);
5264 MemberOffset byte_offset = field->GetOffsetDuringLinking();
5265 uint32_t displaced_bitmap_position =
5266 (byte_offset.Uint32Value() - mirror::kObjectHeaderSize) /
5267 sizeof(mirror::HeapReference<mirror::Object>);
5268 if (displaced_bitmap_position >= 32) {
5269 // Can't encode offset so fall back on slow-path.
5270 reference_offsets = mirror::Class::kClassWalkSuper;
5271 break;
5272 } else {
5273 reference_offsets |= (1 << displaced_bitmap_position);
5274 }
5275 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005276 }
5277 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005278 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005279}
5280
Mathieu Chartier590fee92013-09-13 13:46:47 -07005281mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005282 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005283 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005284 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005285 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005286 return resolved;
5287 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005288 uint32_t utf16_length;
5289 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005290 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005291 dex_cache->SetResolvedString(string_idx, string);
5292 return string;
5293}
5294
Mathieu Chartier590fee92013-09-13 13:46:47 -07005295mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005296 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005297 StackHandleScope<2> hs(Thread::Current());
5298 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5299 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005300 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5301}
5302
5303mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005304 Handle<mirror::DexCache> dex_cache,
5305 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005306 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005307 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005308 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005309 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005310 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005311 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005312 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005313 // TODO: we used to throw here if resolved's class loader was not the
5314 // boot class loader. This was to permit different classes with the
5315 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005316 dex_cache->SetResolvedType(type_idx, resolved);
5317 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005318 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005319 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005320 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005321 StackHandleScope<1> hs(self);
5322 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005323 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005324 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005325 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005326 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005327 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005328 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005329 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005330 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005331 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005332 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005333 return resolved;
5334}
5335
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005336mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005337 Handle<mirror::DexCache> dex_cache,
5338 Handle<mirror::ClassLoader> class_loader,
5339 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005340 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005341 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005342 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005343 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005344 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005345 return resolved;
5346 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005347 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005348 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005349 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005350 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005351 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005352 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005353 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005354 // Scan using method_idx, this saves string compares but will only hit for matching dex
5355 // caches/files.
5356 switch (type) {
5357 case kDirect: // Fall-through.
5358 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005359 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005360 break;
5361 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005362 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005363 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005364 break;
5365 case kSuper: // Fall-through.
5366 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005367 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005368 break;
5369 default:
5370 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005371 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005372 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005373 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005374 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005375 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005376 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005377 switch (type) {
5378 case kDirect: // Fall-through.
5379 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005380 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005381 break;
5382 case kInterface:
5383 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005384 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005385 break;
5386 case kSuper: // Fall-through.
5387 case kVirtual:
5388 resolved = klass->FindVirtualMethod(name, signature);
5389 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005390 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005391 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005392 // If we found a method, check for incompatible class changes.
5393 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005394 // Be a good citizen and update the dex cache to speed subsequent calls.
5395 dex_cache->SetResolvedMethod(method_idx, resolved);
5396 return resolved;
5397 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005398 // If we had a method, it's an incompatible-class-change error.
5399 if (resolved != nullptr) {
5400 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5401 } else {
5402 // We failed to find the method which means either an access error, an incompatible class
5403 // change, or no such method. First try to find the method among direct and virtual methods.
5404 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5405 const Signature signature = dex_file.GetMethodSignature(method_id);
5406 switch (type) {
5407 case kDirect:
5408 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005409 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005410 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5411 // have had a resolved method before, which triggers the "true" branch above.
5412 break;
5413 case kInterface:
5414 case kVirtual:
5415 case kSuper:
5416 resolved = klass->FindDirectMethod(name, signature);
5417 break;
5418 }
5419
5420 // If we found something, check that it can be accessed by the referrer.
5421 if (resolved != nullptr && referrer.Get() != nullptr) {
5422 mirror::Class* methods_class = resolved->GetDeclaringClass();
5423 mirror::Class* referring_class = referrer->GetDeclaringClass();
5424 if (!referring_class->CanAccess(methods_class)) {
5425 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5426 resolved, type);
5427 return nullptr;
5428 } else if (!referring_class->CanAccessMember(methods_class,
5429 resolved->GetAccessFlags())) {
5430 ThrowIllegalAccessErrorMethod(referring_class, resolved);
5431 return nullptr;
5432 }
5433 }
5434
5435 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5436 // methods and throw if we find the method there. If we find nothing, throw a
5437 // NoSuchMethodError.
5438 switch (type) {
5439 case kDirect:
5440 case kStatic:
5441 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005442 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005443 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005444 resolved = klass->FindInterfaceMethod(name, signature);
5445 if (resolved != nullptr) {
5446 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5447 } else {
5448 ThrowNoSuchMethodError(type, klass, name, signature);
5449 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005450 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005451 break;
5452 case kInterface:
5453 if (resolved != nullptr) {
5454 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005455 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005456 resolved = klass->FindVirtualMethod(name, signature);
5457 if (resolved != nullptr) {
5458 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5459 } else {
5460 ThrowNoSuchMethodError(type, klass, name, signature);
5461 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005462 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005463 break;
5464 case kSuper:
Andreas Gampedf733752014-08-25 20:55:01 -07005465 if (resolved != nullptr) {
5466 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5467 } else {
5468 ThrowNoSuchMethodError(type, klass, name, signature);
5469 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005470 break;
5471 case kVirtual:
5472 if (resolved != nullptr) {
5473 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5474 } else {
5475 resolved = klass->FindInterfaceMethod(name, signature);
5476 if (resolved != nullptr) {
5477 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5478 } else {
5479 ThrowNoSuchMethodError(type, klass, name, signature);
5480 }
5481 }
5482 break;
5483 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005484 }
5485 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005486 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005487 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005488}
5489
Mathieu Chartier590fee92013-09-13 13:46:47 -07005490mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005491 Handle<mirror::DexCache> dex_cache,
5492 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005493 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005494 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005495 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005496 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005497 return resolved;
5498 }
5499 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005500 Thread* const self = Thread::Current();
5501 StackHandleScope<1> hs(self);
5502 Handle<mirror::Class> klass(
5503 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005504 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005505 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005506 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005507 }
5508
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005509 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005510 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005511 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005512 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005513 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005514
Andreas Gampe58a5af82014-07-31 16:23:49 -07005515 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005516 const char* name = dex_file.GetFieldName(field_id);
5517 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5518 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005519 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005520 } else {
5521 resolved = klass->FindInstanceField(name, type);
5522 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005523 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005524 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005525 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005526 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005527 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005528 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005529 return resolved;
5530}
5531
Brian Carlstromea46f952013-07-30 01:26:50 -07005532mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005533 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005534 Handle<mirror::DexCache> dex_cache,
5535 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005536 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005537 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005538 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005539 return resolved;
5540 }
5541 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005542 Thread* self = Thread::Current();
5543 StackHandleScope<1> hs(self);
5544 Handle<mirror::Class> klass(
5545 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005546 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005547 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005548 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005549 }
5550
Ian Rogersdfb325e2013-10-30 01:00:44 -07005551 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5552 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005553 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005554 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005555 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005556 dex_cache->SetResolvedField(field_idx, resolved);
5557 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005558 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005559 }
5560 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005561}
5562
Brian Carlstromea46f952013-07-30 01:26:50 -07005563const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005564 uint32_t* length) {
5565 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5566 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005567 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005568 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005569 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005570}
5571
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005572void ClassLinker::DumpAllClasses(int flags) {
5573 if (dex_cache_image_class_lookup_required_) {
5574 MoveImageClassesToClassTable();
5575 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005576 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5577 // 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 -08005578 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005579 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005580 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005581 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
5582 mirror::Class* klass = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07005583 all_classes.push_back(klass);
Ian Rogers5d76c432011-10-31 21:42:49 -07005584 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005585 }
5586
5587 for (size_t i = 0; i < all_classes.size(); ++i) {
5588 all_classes[i]->DumpClass(std::cerr, flags);
5589 }
5590}
5591
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005592static OatFile::OatMethod CreateOatMethod(const void* code, const uint8_t* gc_map,
5593 bool is_portable) {
5594 CHECK_EQ(kUsePortableCompiler, is_portable);
5595 CHECK(code != nullptr);
5596 const uint8_t* base;
5597 uint32_t code_offset, gc_map_offset;
5598 if (gc_map == nullptr) {
5599 base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5600 base -= sizeof(void*); // Move backward so that code_offset != 0.
5601 code_offset = sizeof(void*);
5602 gc_map_offset = 0;
5603 } else {
5604 // TODO: 64bit support.
5605 base = nullptr; // Base of data in oat file, ie 0.
5606 code_offset = PointerToLowMemUInt32(code);
5607 gc_map_offset = PointerToLowMemUInt32(gc_map);
5608 }
5609 return OatFile::OatMethod(base, code_offset, gc_map_offset);
5610}
5611
5612bool ClassLinker::IsPortableResolutionStub(const void* entry_point) const {
5613 return (entry_point == GetPortableResolutionStub()) ||
5614 (portable_resolution_trampoline_ == entry_point);
5615}
5616
5617bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5618 return (entry_point == GetQuickResolutionStub()) ||
5619 (quick_resolution_trampoline_ == entry_point);
5620}
5621
5622bool ClassLinker::IsPortableToInterpreterBridge(const void* entry_point) const {
5623 return (entry_point == GetPortableToInterpreterBridge());
5624 // TODO: portable_to_interpreter_bridge_trampoline_ == entry_point;
5625}
5626
5627bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5628 return (entry_point == GetQuickToInterpreterBridge()) ||
5629 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5630}
5631
5632bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5633 return (entry_point == GetQuickGenericJniStub()) ||
5634 (quick_generic_jni_trampoline_ == entry_point);
5635}
5636
5637const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5638 return GetQuickGenericJniStub();
5639}
5640
5641void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method, const void* method_code,
5642 bool is_portable) const {
5643 OatFile::OatMethod oat_method = CreateOatMethod(method_code, nullptr, is_portable);
5644 oat_method.LinkMethod(method);
5645 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5646 // Create bridges to transition between different kinds of compiled bridge.
5647 if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
5648 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5649 } else {
5650 CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
5651 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
5652 method->SetIsPortableCompiled();
5653 }
5654}
5655
5656void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5657 if (!method->IsNative()) {
5658 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
5659 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
5660 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5661 } else {
5662 const void* quick_method_code = GetQuickGenericJniStub();
5663 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code, nullptr, false);
5664 oat_method.LinkMethod(method);
5665 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5666 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5667 }
5668}
5669
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005670void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005671 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005672 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005673 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005674 MoveImageClassesToClassTable();
5675 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005676 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005677 os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005678}
5679
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005680size_t ClassLinker::NumLoadedClasses() {
5681 if (dex_cache_image_class_lookup_required_) {
5682 MoveImageClassesToClassTable();
5683 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005684 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005685 return class_table_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005686}
5687
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005688pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005689 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005690}
5691
5692pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005693 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005694}
5695
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005696void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005697 DCHECK(!init_done_);
5698
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005699 DCHECK(klass != nullptr);
5700 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005701
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005702 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005703 DCHECK(class_roots != nullptr);
5704 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005705 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005706}
5707
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005708const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5709 static const char* class_roots_descriptors[] = {
5710 "Ljava/lang/Class;",
5711 "Ljava/lang/Object;",
5712 "[Ljava/lang/Class;",
5713 "[Ljava/lang/Object;",
5714 "Ljava/lang/String;",
5715 "Ljava/lang/DexCache;",
5716 "Ljava/lang/ref/Reference;",
5717 "Ljava/lang/reflect/ArtField;",
5718 "Ljava/lang/reflect/ArtMethod;",
5719 "Ljava/lang/reflect/Proxy;",
5720 "[Ljava/lang/String;",
5721 "[Ljava/lang/reflect/ArtField;",
5722 "[Ljava/lang/reflect/ArtMethod;",
5723 "Ljava/lang/ClassLoader;",
5724 "Ljava/lang/Throwable;",
5725 "Ljava/lang/ClassNotFoundException;",
5726 "Ljava/lang/StackTraceElement;",
5727 "Z",
5728 "B",
5729 "C",
5730 "D",
5731 "F",
5732 "I",
5733 "J",
5734 "S",
5735 "V",
5736 "[Z",
5737 "[B",
5738 "[C",
5739 "[D",
5740 "[F",
5741 "[I",
5742 "[J",
5743 "[S",
5744 "[Ljava/lang/StackTraceElement;",
5745 };
5746 COMPILE_ASSERT(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5747 mismatch_between_class_descriptors_and_class_root_enum);
5748
5749 const char* descriptor = class_roots_descriptors[class_root];
5750 CHECK(descriptor != nullptr);
5751 return descriptor;
5752}
5753
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005754} // namespace art