blob: 27163266297dc8661aaf42d79e691a9ab5fc5953 [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();
Igor Murashkin96e83932014-10-29 19:45:42 -07001164 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1165
1166 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1167 if (!oat_file->IsPic()) {
1168 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1169 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1170 }
Alex Light6e183f22014-07-18 14:57:04 -07001171 if (!ret) {
1172 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1173 oat_file->GetLocation().c_str(),
1174 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1175 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1176 oat_file->GetOatHeader().GetImagePatchDelta(),
1177 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1178 }
1179 return ret;
1180}
1181
1182bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1183 const char* dex_location,
1184 uint32_t dex_location_checksum,
1185 const InstructionSet instruction_set,
1186 std::string* error_msg) {
1187 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1188 return false;
1189 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001190
Brian Carlstromf3632832014-05-20 15:36:53 -07001191 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1192 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001193 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001194 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1195 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001196 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1197 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001198 oat_file->GetLocation().c_str(),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001199 oat_dex_file->GetDexFileLocation().c_str(),
1200 oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001201 }
1202 return false;
1203 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001204
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001205 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001206 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001207}
1208
Alex Lighta59dd802014-07-02 16:28:08 -07001209bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1210 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001211 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001212 std::string* error_msg) {
1213 CHECK(oat_file != nullptr);
1214 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001215 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001216 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001217 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1218 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1219 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001220 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001221 if (oat_dex_file == nullptr) {
1222 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001223 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001224 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001225 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001226 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001227 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001228 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001229 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001230 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001231 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001232 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001233 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001234 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001235 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001236 }
Alex Lighta59dd802014-07-02 16:28:08 -07001237 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001238}
1239
Andreas Gampe833a4852014-05-21 18:46:59 -07001240const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001241 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001242 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001243 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001244 std::vector<std::string>* error_msgs,
1245 bool* obsolete_file_cleanup_failed) {
1246 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001247 bool already_opened = false;
1248 std::string dex_location_str(dex_location);
1249 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1250 &already_opened,
1251 obsolete_file_cleanup_failed,
1252 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001253 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001254 if (oat_file.get() == nullptr) {
1255 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1256 dex_location));
1257 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001258 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001259 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1260 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001261 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1262 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001263 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001264 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001265 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001266 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001267 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1268 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1269 "dex location '%s'. Image checksum incorrect.",
1270 oat_file->GetLocation().c_str(), dex_location));
1271 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001272 } else {
1273 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001274 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001275}
1276
Brian Carlstromae826982011-11-09 01:33:42 -08001277const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001278 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001279 for (size_t i = 0; i < oat_files_.size(); i++) {
1280 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001281 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001282 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001283 return oat_file;
1284 }
1285 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001286 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001287}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001288
Alex Lighta59dd802014-07-02 16:28:08 -07001289const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1290 InstructionSet isa,
1291 bool *already_opened,
1292 bool *obsolete_file_cleanup_failed,
1293 std::vector<std::string>* error_msgs) {
1294 // Find out if we've already opened the file
1295 const OatFile* ret = nullptr;
1296 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1297 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1298 if (ret != nullptr) {
1299 *already_opened = true;
1300 return ret;
1301 }
1302
1303 std::string dalvik_cache;
1304 bool have_android_data = false;
1305 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001306 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001307 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001308 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001309 std::string cache_filename;
1310 if (have_dalvik_cache) {
1311 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1312 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1313 if (ret != nullptr) {
1314 *already_opened = true;
1315 return ret;
1316 }
1317 } else {
1318 // If we need to relocate we should just place odex back where it started.
1319 cache_filename = odex_filename;
1320 }
1321
1322 ret = nullptr;
1323
1324 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1325 //
1326 // Now we do the following:
1327 // 1) Try and open the odex version
1328 // 2) If present, checksum-verified & relocated correctly return it
1329 // 3) Close the odex version to free up its address space.
1330 // 4) Try and open the cache version
1331 // 5) If present, checksum-verified & relocated correctly return it
1332 // 6) Close the cache version to free up its address space.
1333 // 7) If we should relocate:
1334 // a) If we have opened and checksum-verified the odex version relocate it to
1335 // 'cache_filename' and return it
1336 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1337 // it. This should not happen often (I think only the run-test's will hit this case).
1338 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1339 // this point.
1340 // 9) Return nullptr
1341
1342 *already_opened = false;
1343 const Runtime* runtime = Runtime::Current();
1344 CHECK(runtime != nullptr);
1345 bool executable = !runtime->IsCompiler();
1346
1347 std::string odex_error_msg;
1348 bool should_patch_system = false;
1349 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001350 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001351 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001352 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001353 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001354 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001355 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001356 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001357 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001358 &odex_checksum_verified,
1359 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001360 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001361 } else {
1362 if (odex_checksum_verified) {
1363 // We can just relocate
1364 should_patch_system = true;
1365 odex_error_msg = "Image Patches are incorrect";
1366 }
1367 if (odex_oat_file.get() != nullptr) {
1368 have_system_odex = true;
1369 }
Alex Lighta59dd802014-07-02 16:28:08 -07001370 }
1371 }
1372
Alex Lighta59dd802014-07-02 16:28:08 -07001373 std::string cache_error_msg;
1374 bool should_patch_cache = false;
1375 bool cache_checksum_verified = false;
1376 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001377 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001378 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001379 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001380 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001381 &cache_checksum_verified,
1382 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001383 return cache_oat_file.release();
1384 } else if (cache_checksum_verified) {
1385 // We can just relocate
1386 should_patch_cache = true;
1387 cache_error_msg = "Image Patches are incorrect";
1388 }
1389 } else if (have_android_data) {
1390 // dalvik_cache does not exist but android data does. This means we should be able to create
1391 // it, so we should try.
1392 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1393 }
1394
1395 ret = nullptr;
1396 std::string error_msg;
1397 if (runtime->CanRelocate()) {
1398 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001399 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1400 if (space != nullptr) {
1401 const std::string& image_location = space->GetImageLocation();
1402 if (odex_checksum_verified && should_patch_system) {
1403 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1404 } else if (cache_checksum_verified && should_patch_cache) {
1405 CHECK(have_dalvik_cache);
1406 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1407 }
Alex Light84d76052014-08-22 17:49:35 -07001408 } else if (have_system_odex) {
1409 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001410 }
1411 }
1412 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1413 // implicitly: were able to fine where the cached version is but we were unable to use it,
1414 // either as a destination for relocation or to open a file. We should delete it if it is
1415 // there.
1416 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1417 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1418 "searching for dex file %s: %s",
1419 cache_filename.c_str(), dex_location.c_str(),
1420 strerror(errno));
1421 error_msgs->push_back(rm_error_msg);
1422 VLOG(class_linker) << rm_error_msg;
1423 // Let the caller know that we couldn't remove the obsolete file.
1424 // This is a good indication that further writes may fail as well.
1425 *obsolete_file_cleanup_failed = true;
1426 }
1427 }
1428 if (ret == nullptr) {
1429 VLOG(class_linker) << error_msg;
1430 error_msgs->push_back(error_msg);
1431 std::string relocation_msg;
1432 if (runtime->CanRelocate()) {
1433 relocation_msg = StringPrintf(" and relocation failed");
1434 }
1435 if (have_dalvik_cache && cache_checksum_verified) {
1436 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1437 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1438 cache_filename.c_str(), cache_error_msg.c_str(),
1439 relocation_msg.c_str());
1440 } else {
1441 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1442 "dalvik_cache availible)%s.", odex_filename.c_str(),
1443 odex_error_msg.c_str(), relocation_msg.c_str());
1444 }
1445 VLOG(class_linker) << error_msg;
1446 error_msgs->push_back(error_msg);
1447 }
1448 return ret;
1449}
1450
Alex Light9dcc4572014-08-14 14:16:26 -07001451const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1452 InstructionSet isa,
1453 std::string* error_msg) {
1454 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001455 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001456 if (output.get() == nullptr) {
1457 return nullptr;
1458 }
Alex Light84d76052014-08-22 17:49:35 -07001459 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1460 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001461 return output.release();
1462 } else {
1463 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1464 oat_path.c_str());
1465 return nullptr;
1466 }
1467}
1468
Alex Lighta59dd802014-07-02 16:28:08 -07001469const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1470 const std::string& output_oat,
1471 const std::string& image_location,
1472 InstructionSet isa,
1473 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001474 Runtime* runtime = Runtime::Current();
1475 DCHECK(runtime != nullptr);
1476 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001477 // We don't have an image space so there is no point in trying to patchoat.
1478 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1479 << "running without an image. Attempting to use oat file for interpretation.";
1480 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1481 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001482 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001483 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1484 // input_oat but make sure we only do interpretation on it's dex files.
1485 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1486 << "disabled. Attempting to use oat file for interpretation";
1487 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1488 }
Alex Lighta59dd802014-07-02 16:28:08 -07001489 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001490 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001491
1492 std::string isa_arg("--instruction-set=");
1493 isa_arg += GetInstructionSetString(isa);
1494 std::string input_oat_filename_arg("--input-oat-file=");
1495 input_oat_filename_arg += input_oat;
1496 std::string output_oat_filename_arg("--output-oat-file=");
1497 output_oat_filename_arg += output_oat;
1498 std::string patched_image_arg("--patched-image-location=");
1499 patched_image_arg += image_location;
1500
1501 std::vector<std::string> argv;
1502 argv.push_back(patchoat);
1503 argv.push_back(isa_arg);
1504 argv.push_back(input_oat_filename_arg);
1505 argv.push_back(output_oat_filename_arg);
1506 argv.push_back(patched_image_arg);
1507
1508 std::string command_line(Join(argv, ' '));
1509 LOG(INFO) << "Relocate Oat File: " << command_line;
1510 bool success = Exec(argv, error_msg);
1511 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001512 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gampe7ba64962014-10-23 11:37:40 -07001513 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001514 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001515 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1516 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001517 return output.release();
1518 } else if (output.get() != nullptr) {
1519 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1520 "but output file '%s' failed verifcation: %s",
1521 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1522 } else {
1523 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1524 "but was unable to open output file '%s': %s",
1525 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1526 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001527 } else if (!runtime->IsCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001528 // patchoat failed which means we probably don't have enough room to place the output oat file,
1529 // instead of failing we should just run the interpreter from the dex files in the input oat.
1530 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1531 << "for interpretation. patchoat failure was: " << *error_msg;
1532 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001533 } else {
1534 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1535 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1536 error_msg->c_str());
1537 }
1538 return nullptr;
1539}
1540
Andreas Gampe7ba64962014-10-23 11:37:40 -07001541bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001542 bool* checksum_verified,
1543 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001544 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001545 if (image_space == nullptr) {
1546 *error_msg = "No image space present";
1547 return false;
1548 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001549 uint32_t real_image_checksum;
1550 void* real_image_oat_offset;
1551 int32_t real_patch_delta;
1552 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001553 const ImageHeader& image_header = image_space->GetImageHeader();
1554 real_image_checksum = image_header.GetOatChecksum();
1555 real_image_oat_offset = image_header.GetOatDataBegin();
1556 real_patch_delta = image_header.GetPatchDelta();
1557 } else {
1558 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1559 image_space->GetImageLocation().c_str(), isa));
1560 real_image_checksum = image_header->GetOatChecksum();
1561 real_image_oat_offset = image_header->GetOatDataBegin();
1562 real_patch_delta = image_header->GetPatchDelta();
1563 }
1564
1565 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001566 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001567
1568 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1569 *checksum_verified = oat_image_checksum == real_image_checksum;
1570 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001571 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1572 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001573 }
1574
Andreas Gampe7ba64962014-10-23 11:37:40 -07001575 bool offset_verified;
1576 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001577
Andreas Gampe7ba64962014-10-23 11:37:40 -07001578 if (!oat_file->IsPic()) {
1579 // If an oat file is not PIC, we need to check that the image is at the expected location and
1580 // patched in the same way.
1581 void* oat_image_oat_offset =
1582 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1583 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1584 if (!offset_verified) {
1585 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1586 real_image_oat_offset, oat_image_oat_offset);
1587 }
1588
1589 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1590 patch_delta_verified = oat_patch_delta == real_patch_delta;
1591 if (!patch_delta_verified) {
1592 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1593 "received 0x%x)", real_patch_delta, oat_patch_delta);
1594 }
1595 } else {
1596 // If an oat file is PIC, we ignore offset and patching delta.
1597 offset_verified = true;
1598 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001599 }
1600
1601 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001602 if (!ret) {
1603 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001604 }
1605 return ret;
1606}
1607
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001608const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1609 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001610 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001611 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001612 return oat_file;
1613 }
1614
Igor Murashkin46774762014-10-22 11:37:02 -07001615 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001616 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001617}
1618
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001619static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001620 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001621 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1622
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001623 DCHECK(obj != nullptr);
1624 DCHECK(class_linker != nullptr);
Ian Rogers848871b2013-08-05 10:56:33 -07001625
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001626 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001627 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001628 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001629 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers848871b2013-08-05 10:56:33 -07001630 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001631 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1632 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001633 }
1634 }
1635 }
1636}
1637
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001638void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001639 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001640 CHECK(!init_done_);
1641
Mathieu Chartier590fee92013-09-13 13:46:47 -07001642 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001643 gc::Heap* heap = Runtime::Current()->GetHeap();
1644 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001645 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001646 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001647 OatFile& oat_file = GetImageOatFile(space);
1648 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1649 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001650 const char* image_file_location = oat_file.GetOatHeader().
1651 GetStoreValueByKey(OatHeader::kImageLocationKey);
1652 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001653 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1654 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001655 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1656 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001657 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001658 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001659 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1660 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1661 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001662
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001663 StackHandleScope<1> hs(self);
1664 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1665 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1666 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001667 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001668
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001669 // Special case of setting up the String class early so that we can test arbitrary objects
1670 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001671 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001672
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001673 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001674 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001675 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001676 StackHandleScope<1> hs(self);
1677 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001678 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001679 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1680 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001681 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001682 std::string error_msg;
1683 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001684 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001685 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001686 << " from within oat file " << oat_file.GetLocation()
1687 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001688 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001689
1690 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1691
1692 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001693 }
1694
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001695 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1696 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001697 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001698
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001699 // Set entry point to interpreter if in InterpretOnly mode.
1700 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001701 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001702 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001703 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001704
1705 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001706 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001707 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001708
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001709 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001710 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1711 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001712 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001713 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001714 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001715 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1716 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1717 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1718 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1719 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1720 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1721 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1722 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1723 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1724 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001725
Ian Rogers98379392014-02-24 16:53:16 -08001726 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001727
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001728 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001729}
1730
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001731void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1732 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1733 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001734 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1735 it.second.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001736 }
1737 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1738 for (auto& pair : new_class_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001739 mirror::Class* old_ref = pair.second.Read<kWithoutReadBarrier>();
1740 pair.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1741 mirror::Class* new_ref = pair.second.Read<kWithoutReadBarrier>();
1742 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001743 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1744 // corresponding object. This is slow, but luckily for us, this may only happen with a
1745 // concurrent moving GC.
1746 for (auto it = class_table_.lower_bound(pair.first), end = class_table_.end();
1747 it != end && it->first == pair.first; ++it) {
1748 // If the class stored matches the old class, update it to the new value.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001749 if (old_ref == it->second.Read<kWithoutReadBarrier>()) {
1750 it->second = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001751 }
1752 }
1753 }
1754 }
1755 }
1756 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1757 new_class_roots_.clear();
1758 }
1759 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1760 log_new_class_table_roots_ = true;
1761 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1762 log_new_class_table_roots_ = false;
1763 }
1764 // We deliberately ignore the class roots in the image since we
1765 // handle image roots by using the MS/CMS rescanning of dirty cards.
1766}
1767
Brian Carlstroma663ea52011-08-19 23:33:41 -07001768// Keep in sync with InitCallback. Anything we visit, we need to
1769// reinit references to when reinitializing a ClassLinker from a
1770// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001771void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001772 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001773 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001774 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001775 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001776 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001777 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1778 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001779 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001780 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1781 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001782 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001783 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001784 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001785 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1786 new_dex_cache_roots_.clear();
1787 }
1788 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1789 log_new_dex_caches_roots_ = true;
1790 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1791 log_new_dex_caches_roots_ = false;
1792 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001793 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001794 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001795 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1796 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001797 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001798 if (!find_array_class_cache_[i].IsNull()) {
1799 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001800 }
1801 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001802}
1803
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001804void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1805 if (dex_cache_image_class_lookup_required_) {
1806 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001807 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001808 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001809 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001810 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1811 mirror::Class* c = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07001812 if (!visitor(c, arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001813 return;
1814 }
1815 }
1816}
1817
Ian Rogersdbf3be02014-08-29 15:40:08 -07001818static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001819 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001820 classes->insert(c);
1821 return true;
1822}
1823
Ian Rogersdbf3be02014-08-29 15:40:08 -07001824struct GetClassesVisitorArrayArg {
1825 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1826 int32_t index;
1827 bool success;
1828};
1829
1830static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1831 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1832 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1833 if (arg->index < (*arg->classes)->GetLength()) {
1834 (*arg->classes)->Set(arg->index, c);
1835 arg->index++;
1836 return true;
1837 } else {
1838 arg->success = false;
1839 return false;
1840 }
1841}
1842
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001843void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001844 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1845 // is avoiding duplicates.
1846 if (!kMovingClasses) {
1847 std::set<mirror::Class*> classes;
1848 VisitClasses(GetClassesVisitorSet, &classes);
1849 for (mirror::Class* klass : classes) {
1850 if (!visitor(klass, arg)) {
1851 return;
1852 }
1853 }
1854 } else {
1855 Thread* self = Thread::Current();
1856 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001857 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001858 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1859 GetClassesVisitorArrayArg local_arg;
1860 local_arg.classes = &classes;
1861 local_arg.success = false;
1862 // We size the array assuming classes won't be added to the class table during the visit.
1863 // If this assumption fails we iterate again.
1864 while (!local_arg.success) {
1865 size_t class_table_size;
1866 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001867 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogersdbf3be02014-08-29 15:40:08 -07001868 class_table_size = class_table_.size();
1869 }
1870 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1871 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1872 classes.Assign(
1873 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1874 CHECK(classes.Get() != nullptr); // OOME.
1875 local_arg.index = 0;
1876 local_arg.success = true;
1877 VisitClasses(GetClassesVisitorArray, &local_arg);
1878 }
1879 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1880 // If the class table shrank during creation of the clases array we expect null elements. If
1881 // the class table grew then the loop repeats. If classes are created after the loop has
1882 // finished then we don't visit.
1883 mirror::Class* klass = classes->Get(i);
1884 if (klass != nullptr && !visitor(klass, arg)) {
1885 return;
1886 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001887 }
1888 }
1889}
1890
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001891ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001892 mirror::Class::ResetClass();
1893 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001894 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001895 mirror::ArtField::ResetClass();
1896 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001897 mirror::BooleanArray::ResetArrayClass();
1898 mirror::ByteArray::ResetArrayClass();
1899 mirror::CharArray::ResetArrayClass();
1900 mirror::DoubleArray::ResetArrayClass();
1901 mirror::FloatArray::ResetArrayClass();
1902 mirror::IntArray::ResetArrayClass();
1903 mirror::LongArray::ResetArrayClass();
1904 mirror::ShortArray::ResetArrayClass();
1905 mirror::Throwable::ResetClass();
1906 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001907 STLDeleteElements(&boot_class_path_);
1908 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001909}
1910
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001911mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001912 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001913 StackHandleScope<16> hs(self);
1914 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1915 Handle<mirror::DexCache> dex_cache(
1916 hs.NewHandle(down_cast<mirror::DexCache*>(
1917 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1918 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001919 if (dex_cache.Get() == nullptr) {
1920 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001921 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001922 Handle<mirror::String>
1923 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001924 if (location.Get() == nullptr) {
1925 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001926 }
Ian Rogers700a4022014-05-19 16:49:03 -07001927 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001928 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001929 if (strings.Get() == nullptr) {
1930 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001931 }
Ian Rogers700a4022014-05-19 16:49:03 -07001932 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001933 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001934 if (types.Get() == nullptr) {
1935 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001936 }
Ian Rogers700a4022014-05-19 16:49:03 -07001937 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001938 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001939 if (methods.Get() == nullptr) {
1940 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001941 }
Ian Rogers700a4022014-05-19 16:49:03 -07001942 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001943 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001944 if (fields.Get() == nullptr) {
1945 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001946 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001947 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1948 fields.Get());
1949 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001950}
1951
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001952mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001953 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001954 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001955 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001956 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001957 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001958 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1959 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001960 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001961 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001962 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001963 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001964 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001965}
1966
Ian Rogers6fac4472014-02-25 17:01:10 -08001967mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001968 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001969}
1970
Brian Carlstromea46f952013-07-30 01:26:50 -07001971mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001972 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001973 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001974}
1975
Brian Carlstromea46f952013-07-30 01:26:50 -07001976mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001977 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001978 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001979}
1980
Mathieu Chartier590fee92013-09-13 13:46:47 -07001981mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1982 Thread* self, size_t length) {
1983 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1984 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001985}
1986
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001987mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1988 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001989 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001990
1991 // For temporary classes we must wait for them to be retired.
1992 if (init_done_ && klass->IsTemp()) {
1993 CHECK(!klass->IsResolved());
1994 if (klass->IsErroneous()) {
1995 ThrowEarlierClassFailure(klass);
1996 return nullptr;
1997 }
1998 StackHandleScope<1> hs(self);
1999 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2000 ObjectLock<mirror::Class> lock(self, h_class);
2001 // Loop and wait for the resolving thread to retire this class.
2002 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2003 lock.WaitIgnoringInterrupts();
2004 }
2005 if (h_class->IsErroneous()) {
2006 ThrowEarlierClassFailure(h_class.Get());
2007 return nullptr;
2008 }
2009 CHECK(h_class->IsRetired());
2010 // Get the updated class from class table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002011 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002012 }
2013
Brian Carlstromaded5f72011-10-07 17:15:04 -07002014 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002015 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002016 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002017 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2018 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002019 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002020 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2021 ThrowClassCircularityError(h_class.Get());
2022 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002023 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002024 }
2025 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002026 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002027 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002028 }
2029 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002030
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002031 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002032 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002033 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002034 }
2035 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002036 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002037 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002038 return klass;
2039}
2040
Ian Rogers68b56852014-08-29 20:19:11 -07002041typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2042
2043// Search a collection of DexFiles for a descriptor
2044ClassPathEntry FindInClassPath(const char* descriptor,
2045 const std::vector<const DexFile*>& class_path) {
2046 for (size_t i = 0; i != class_path.size(); ++i) {
2047 const DexFile* dex_file = class_path[i];
2048 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002049 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002050 return ClassPathEntry(dex_file, dex_class_def);
2051 }
2052 }
2053 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002054 return ClassPathEntry(static_cast<const DexFile*>(nullptr),
2055 static_cast<const DexFile::ClassDef*>(nullptr));
Ian Rogers68b56852014-08-29 20:19:11 -07002056}
2057
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002058mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2059 Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002060 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002061 if (class_loader->GetClass() !=
2062 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2063 class_loader->GetParent()->GetClass() !=
2064 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2065 return nullptr;
2066 }
2067 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2068 // Check if this would be found in the parent boot class loader.
2069 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002070 mirror::Class* klass = LookupClass(self, descriptor, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002071 if (klass != nullptr) {
2072 return EnsureResolved(self, descriptor, klass);
2073 }
Ian Rogers7b078e82014-09-10 14:44:24 -07002074 klass = DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002075 *pair.second);
2076 if (klass != nullptr) {
2077 return klass;
2078 }
2079 CHECK(self->IsExceptionPending()) << descriptor;
2080 self->ClearException();
2081 } else {
2082 // RegisterDexFile may allocate dex caches (and cause thread suspension).
2083 StackHandleScope<3> hs(self);
2084 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2085 // We need to get the DexPathList and loop through it.
2086 Handle<mirror::ArtField> cookie_field =
2087 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2088 Handle<mirror::ArtField> dex_file_field =
2089 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002090 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002091 mirror::Object* dex_path_list =
2092 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2093 GetObject(class_loader.Get());
2094 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2095 cookie_field.Get() != nullptr) {
2096 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2097 mirror::Object* dex_elements_obj =
2098 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2099 GetObject(dex_path_list);
2100 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2101 // at the mCookie which is a DexFile vector.
2102 if (dex_elements_obj != nullptr) {
2103 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2104 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2105 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2106 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2107 if (element == nullptr) {
2108 // Should never happen, fall back to java code to throw a NPE.
2109 break;
2110 }
2111 mirror::Object* dex_file = dex_file_field->GetObject(element);
2112 if (dex_file != nullptr) {
2113 const uint64_t cookie = cookie_field->GetLong(dex_file);
2114 auto* dex_files =
2115 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2116 if (dex_files == nullptr) {
2117 // This should never happen so log a warning.
2118 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2119 break;
2120 }
2121 for (const DexFile* dex_file : *dex_files) {
2122 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
2123 if (dex_class_def != nullptr) {
2124 RegisterDexFile(*dex_file);
2125 mirror::Class* klass =
Ian Rogers7b078e82014-09-10 14:44:24 -07002126 DefineClass(self, descriptor, class_loader, *dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002127 if (klass == nullptr) {
2128 CHECK(self->IsExceptionPending()) << descriptor;
2129 self->ClearException();
2130 return nullptr;
2131 }
2132 return klass;
2133 }
2134 }
2135 }
2136 }
2137 }
2138 }
2139 }
2140 return nullptr;
2141}
2142
Ian Rogers98379392014-02-24 16:53:16 -08002143mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002144 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002145 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002146 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002147 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002148 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002149 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2150 // for primitive classes that aren't backed by dex files.
2151 return FindPrimitiveClass(descriptor[0]);
2152 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002153 // Find the class in the loaded classes table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002154 mirror::Class* klass = LookupClass(self, descriptor, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002155 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002156 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002157 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002158 // Class is not yet loaded.
2159 if (descriptor[0] == '[') {
Ian Rogers98379392014-02-24 16:53:16 -08002160 return CreateArrayClass(self, descriptor, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002161 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002162 // The boot class loader, search the boot class path.
Ian Rogers68b56852014-08-29 20:19:11 -07002163 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2164 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002165 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2166 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002167 } else {
2168 // The boot class loader is searched ahead of the application class loader, failures are
2169 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2170 // trigger the chaining with a proper stack trace.
2171 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2172 self->SetException(ThrowLocation(), pre_allocated);
2173 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002174 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002175 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002176 // First try with the bootstrap class loader.
2177 if (class_loader.Get() != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002178 klass = LookupClass(self, descriptor, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002179 if (klass != nullptr) {
2180 return EnsureResolved(self, descriptor, klass);
2181 }
2182 }
Ian Rogers63557452014-06-04 16:57:15 -07002183 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2184 // a NoClassDefFoundError being allocated.
Ian Rogers68b56852014-08-29 20:19:11 -07002185 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2186 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002187 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2188 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002189 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002190 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002191 const std::vector<const DexFile*>* class_path;
2192 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002193 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002194 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002195 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002196 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2197 }
Ian Rogers68b56852014-08-29 20:19:11 -07002198 pair = FindInClassPath(descriptor, *class_path);
2199 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002200 return DefineClass(self, descriptor, class_loader, *pair.first, *pair.second);
2201 } else {
2202 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2203 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2204 self->SetException(ThrowLocation(), pre_allocated);
2205 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002206 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002207 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002208 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002209 mirror::Class* klass = FindClassInPathClassLoader(soa, self, descriptor, class_loader);
2210 if (klass != nullptr) {
2211 return klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002212 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002213 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002214 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002215 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002216 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002217 {
2218 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002219 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2220 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002221 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002222 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002223 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002224 }
Ian Rogers68b56852014-08-29 20:19:11 -07002225 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002226 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2227 WellKnownClasses::java_lang_ClassLoader_loadClass,
2228 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002229 }
Ian Rogers98379392014-02-24 16:53:16 -08002230 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002231 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002232 return nullptr;
2233 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002234 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002235 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002236 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002237 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002238 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002239 // success, return mirror::Class*
2240 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002241 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002242 }
Ian Rogers07140832014-09-30 15:43:59 -07002243 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002244}
2245
Ian Rogers7b078e82014-09-10 14:44:24 -07002246mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002247 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002248 const DexFile& dex_file,
2249 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002250 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002251 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002252 bool should_allocate = false;
2253
Brian Carlstromaded5f72011-10-07 17:15:04 -07002254 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002255 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002256 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002257 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002258 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002259 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002260 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002261 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002262 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002263 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2264 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002265 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002266 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002267 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002268 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002269 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002270 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002271 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002272 should_allocate = true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002273 }
2274 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002275 should_allocate = true;
2276 }
2277
2278 if (should_allocate) {
2279 // Allocate a class with the status of not ready.
2280 // Interface object should get the right size here. Regular class will
2281 // figure out the right size later and be replaced with one of the right
2282 // size when the class becomes resolved.
2283 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002284 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002285 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002286 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002287 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002288 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002289 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002290 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002291 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002292 if (self->IsExceptionPending()) {
2293 // An exception occured during load, set status to erroneous while holding klass' lock in case
2294 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002295 if (!klass->IsErroneous()) {
2296 klass->SetStatus(mirror::Class::kStatusError, self);
2297 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002298 return nullptr;
2299 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002300 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002301
Mathieu Chartier590fee92013-09-13 13:46:47 -07002302 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002303 mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor));
Ian Rogersc114b5f2014-07-21 08:55:01 -07002304 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002305 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2306 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002307 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002308 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002309
Brian Carlstromaded5f72011-10-07 17:15:04 -07002310 // Finish loading (if necessary) by finding parents
2311 CHECK(!klass->IsLoaded());
2312 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2313 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002314 if (!klass->IsErroneous()) {
2315 klass->SetStatus(mirror::Class::kStatusError, self);
2316 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002317 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002318 }
2319 CHECK(klass->IsLoaded());
2320 // Link the class (if necessary)
2321 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002322 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002323 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002324
2325 mirror::Class* new_class = nullptr;
2326 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002327 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002328 if (!klass->IsErroneous()) {
2329 klass->SetStatus(mirror::Class::kStatusError, self);
2330 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002331 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002332 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002333 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002334 CHECK(new_class != nullptr) << descriptor;
2335 CHECK(new_class->IsResolved()) << descriptor;
2336
2337 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002338
2339 /*
2340 * We send CLASS_PREPARE events to the debugger from here. The
2341 * definition of "preparation" is creating the static fields for a
2342 * class and initializing them to the standard default values, but not
2343 * executing any code (that comes later, during "initialization").
2344 *
2345 * We did the static preparation in LinkClass.
2346 *
2347 * The class has been prepared and resolved but possibly not yet verified
2348 * at this point.
2349 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002350 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002351
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002352 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002353}
2354
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002355uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2356 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002357 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002358 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002359 size_t num_8 = 0;
2360 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002361 size_t num_32 = 0;
2362 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002363 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002364 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2365 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002366 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002367 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002368 switch (c) {
2369 case 'L':
2370 case '[':
2371 num_ref++;
2372 break;
2373 case 'J':
2374 case 'D':
2375 num_64++;
2376 break;
2377 case 'I':
2378 case 'F':
2379 num_32++;
2380 break;
2381 case 'S':
2382 case 'C':
2383 num_16++;
2384 break;
2385 case 'B':
2386 case 'Z':
2387 num_8++;
2388 break;
2389 default:
2390 LOG(FATAL) << "Unknown descriptor: " << c;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002391 }
2392 }
2393 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002394 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002395}
2396
Ian Rogers97b52f82014-08-14 11:34:07 -07002397OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2398 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002399 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002400 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2401 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002402 *found = false;
2403 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002404 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002405 *found = true;
2406 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002407}
2408
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002409static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2410 uint32_t method_idx) {
2411 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002412 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002413 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002414 ClassDataItemIterator it(dex_file, class_data);
2415 // Skip fields
2416 while (it.HasNextStaticField()) {
2417 it.Next();
2418 }
2419 while (it.HasNextInstanceField()) {
2420 it.Next();
2421 }
2422 // Process methods
2423 size_t class_def_method_index = 0;
2424 while (it.HasNextDirectMethod()) {
2425 if (it.GetMemberIndex() == method_idx) {
2426 return class_def_method_index;
2427 }
2428 class_def_method_index++;
2429 it.Next();
2430 }
2431 while (it.HasNextVirtualMethod()) {
2432 if (it.GetMemberIndex() == method_idx) {
2433 return class_def_method_index;
2434 }
2435 class_def_method_index++;
2436 it.Next();
2437 }
2438 DCHECK(!it.HasNext());
2439 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2440 return 0;
2441}
2442
Ian Rogers97b52f82014-08-14 11:34:07 -07002443const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002444 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002445 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002446 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002447 size_t oat_method_index;
2448 if (method->IsStatic() || method->IsDirect()) {
2449 // Simple case where the oat method index was stashed at load time.
2450 oat_method_index = method->GetMethodIndex();
2451 } else {
2452 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2453 // by search for its position in the declared virtual methods.
2454 oat_method_index = declaring_class->NumDirectMethods();
2455 size_t end = declaring_class->NumVirtualMethods();
2456 bool found = false;
2457 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002458 // Check method index instead of identity in case of duplicate method definitions.
2459 if (method->GetDexMethodIndex() ==
2460 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08002461 found = true;
2462 break;
2463 }
Ian Rogersf320b632012-03-13 18:47:47 -07002464 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002465 }
2466 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2467 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002468 DCHECK_EQ(oat_method_index,
2469 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002470 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002471 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002472 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2473 declaring_class->GetDexClassDefIndex(),
2474 found);
2475 if (!found) {
2476 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002477 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002478 *found = true;
2479 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002480}
2481
2482// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002483const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002484 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002485 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002486 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002487 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002488 bool found;
2489 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002490 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002491 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002492 result = oat_method.GetQuickCode();
2493 }
2494
Ian Rogersef7d42f2014-01-06 12:55:46 -08002495 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002496 if (method->IsNative()) {
2497 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002498 result = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002499 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002500 // No code? Do we expect portable code?
2501 result = GetQuickToPortableBridge();
2502 } else {
2503 // No code? You must mean to go into the interpreter.
2504 result = GetQuickToInterpreterBridge();
2505 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002506 }
2507 return result;
TDYa12785321912012-04-01 15:24:56 -07002508}
2509
Ian Rogersef7d42f2014-01-06 12:55:46 -08002510const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2511 bool* have_portable_code) {
2512 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2513 *have_portable_code = false;
2514 if (method->IsProxyMethod()) {
2515 return GetPortableProxyInvokeHandler();
2516 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002517 bool found;
2518 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002519 const void* result = nullptr;
2520 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002521 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002522 result = oat_method.GetPortableCode();
2523 quick_code = oat_method.GetQuickCode();
2524 }
2525
Ian Rogersef7d42f2014-01-06 12:55:46 -08002526 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002527 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002528 // No code? You must mean to go into the interpreter.
2529 result = GetPortableToInterpreterBridge();
2530 } else {
2531 // No code? But there's quick code, so use a bridge.
2532 result = GetPortableToQuickBridge();
2533 }
2534 } else {
2535 *have_portable_code = true;
2536 }
2537 return result;
2538}
2539
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002540const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2541 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2542 return nullptr;
2543 }
2544 bool found;
2545 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2546 return found ? oat_method.GetQuickCode() : nullptr;
2547}
2548
2549const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2550 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2551 return nullptr;
2552 }
2553 bool found;
2554 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2555 return found ? oat_method.GetPortableCode() : nullptr;
2556}
2557
Ian Rogersef7d42f2014-01-06 12:55:46 -08002558const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2559 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002560 bool found;
2561 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2562 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002563 return nullptr;
2564 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002565 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002566 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002567}
2568
2569const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2570 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002571 bool found;
2572 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2573 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002574 return nullptr;
2575 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002576 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002577 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002578}
2579
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002580// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002581static bool NeedsInterpreter(
2582 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2583 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002584 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002585 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002586 // May return true for native code, in the case of generic JNI
2587 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002588 return true;
2589 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002590#ifdef ART_SEA_IR_MODE
2591 ScopedObjectAccess soa(Thread::Current());
2592 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2593 LOG(INFO) << "Found " << PrettyMethod(method);
2594 return false;
2595 }
2596#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002597 // If interpreter mode is enabled, every method (except native and proxy) must
2598 // be run with interpreter.
2599 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2600 !method->IsNative() && !method->IsProxyMethod();
2601}
2602
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002603void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002604 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002605 if (klass->NumDirectMethods() == 0) {
2606 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002607 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002608 Runtime* runtime = Runtime::Current();
2609 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002610 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2611 return; // OAT file unavailable.
2612 }
Ian Rogers19846512012-02-24 11:42:47 -08002613 }
Alex Light64ad14d2014-08-19 14:23:13 -07002614
Mathieu Chartierf8322842014-05-16 10:59:25 -07002615 const DexFile& dex_file = klass->GetDexFile();
2616 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002617 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002618 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002619 // There should always be class data if there were direct methods.
2620 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002621 ClassDataItemIterator it(dex_file, class_data);
2622 // Skip fields
2623 while (it.HasNextStaticField()) {
2624 it.Next();
2625 }
2626 while (it.HasNextInstanceField()) {
2627 it.Next();
2628 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002629 bool has_oat_class;
2630 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2631 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002632 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002633 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002634 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002635 if (!method->IsStatic()) {
2636 // Only update static methods.
2637 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002638 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002639 const void* portable_code = nullptr;
2640 const void* quick_code = nullptr;
2641 if (has_oat_class) {
2642 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2643 portable_code = oat_method.GetPortableCode();
2644 quick_code = oat_method.GetQuickCode();
2645 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002646 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2647 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002648 if (enter_interpreter) {
2649 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002650 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002651 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002652 quick_code = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002653 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002654 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002655 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002656 quick_code = GetQuickToInterpreterBridge();
2657 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002658 } else {
2659 if (portable_code == nullptr) {
2660 portable_code = GetPortableToQuickBridge();
2661 } else {
2662 have_portable_code = true;
2663 }
2664 if (quick_code == nullptr) {
2665 quick_code = GetQuickToPortableBridge();
2666 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002667 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002668 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2669 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002670 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002671 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002672}
2673
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002674void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002675 const OatFile::OatClass* oat_class,
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002676 const DexFile& dex_file, uint32_t dex_method_index,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002677 uint32_t method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002678 Runtime* runtime = Runtime::Current();
2679 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002680 // The following code only applies to a non-compiler runtime.
2681 return;
2682 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002683 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002684 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2685 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002686 if (oat_class != nullptr) {
2687 // Every kind of method should at least get an invoke stub from the oat_method.
2688 // non-abstract methods also get their code pointers.
2689 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
2690 oat_method.LinkMethod(method.Get());
2691 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002692
Jeff Hao16743632013-05-08 10:59:04 -07002693 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002694 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002695 method->GetEntryPointFromQuickCompiledCode(),
2696 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002697 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002698 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002699 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002700 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002701 }
2702
Brian Carlstrom92827a52011-10-10 15:50:01 -07002703 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002704 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2705 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002706 return;
2707 }
Ian Rogers19846512012-02-24 11:42:47 -08002708
Ian Rogersef7d42f2014-01-06 12:55:46 -08002709 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002710 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002711 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002712 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2713 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002714 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2715 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002716 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002717 if (!method->IsNative()) {
2718 // Set entry point from compiled code if there's no code or in interpreter only mode.
2719 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2720 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2721 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002722 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002723 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2724 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002725 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2726 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2727 have_portable_code = true;
2728 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2729 } else {
2730 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2731 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002732 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002733
Ian Rogers62d6c772013-02-27 08:32:07 -08002734 if (method->IsNative()) {
2735 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002736 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002737
2738 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002739 // We have a native method here without code. Then it should have either the generic JNI
2740 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2741 // TODO: this doesn't handle all the cases where trampolines may be installed.
2742 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2743 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002744 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002745 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002746
Ian Rogers62d6c772013-02-27 08:32:07 -08002747 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002748 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002749 method->GetEntryPointFromQuickCompiledCode(),
2750 method->GetEntryPointFromPortableCompiledCode(),
2751 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002752}
2753
Fred Shih37f05ef2014-07-16 18:38:08 -07002754
Fred Shih37f05ef2014-07-16 18:38:08 -07002755
Ian Rogers7b078e82014-09-10 14:44:24 -07002756void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002757 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002758 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002759 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002760 CHECK(klass.Get() != nullptr);
2761 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002762 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002763 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002764 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002765
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002766 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002767 if (kUseBakerOrBrooksReadBarrier) {
2768 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002769 }
Andreas Gampe51829322014-08-25 15:05:04 -07002770 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002771 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002772 klass->SetAccessFlags(access_flags);
2773 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002774 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002775 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002776
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002777 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002778 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002779
Ian Rogers13735952014-10-08 12:43:28 -07002780 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002781 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002782 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002783 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002784
Ian Rogers97b52f82014-08-14 11:34:07 -07002785
2786 bool has_oat_class = false;
2787 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2788 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2789 &has_oat_class);
2790 if (has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002791 LoadClassMembers(self, dex_file, class_data, klass, class_loader, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002792 }
2793 }
2794 if (!has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002795 LoadClassMembers(self, dex_file, class_data, klass, class_loader, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002796 }
2797}
2798
Ian Rogers7b078e82014-09-10 14:44:24 -07002799void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002800 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002801 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002802 mirror::ClassLoader* class_loader,
2803 const OatFile::OatClass* oat_class) {
2804 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002805 ClassDataItemIterator it(dex_file, class_data);
2806 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002807 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002808 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002809 CHECK(self->IsExceptionPending()); // OOME.
2810 return;
2811 }
2812 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002813 }
2814 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002815 mirror::ObjectArray<mirror::ArtField>* fields =
2816 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002817 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002818 CHECK(self->IsExceptionPending()); // OOME.
2819 return;
2820 }
2821 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002822 }
2823 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002824 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002825 StackHandleScope<1> hs(self);
2826 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002827 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002828 CHECK(self->IsExceptionPending()); // OOME.
2829 return;
2830 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002831 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002832 LoadField(dex_file, it, klass, sfield);
2833 }
2834 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002835 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002836 StackHandleScope<1> hs(self);
2837 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002838 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002839 CHECK(self->IsExceptionPending()); // OOME.
2840 return;
2841 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002842 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002843 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002844 }
2845
Ian Rogers0571d352011-11-03 19:51:38 -07002846 // Load methods.
2847 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002848 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002849 mirror::ObjectArray<mirror::ArtMethod>* directs =
2850 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002851 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002852 CHECK(self->IsExceptionPending()); // OOME.
2853 return;
2854 }
2855 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002856 }
Ian Rogers0571d352011-11-03 19:51:38 -07002857 if (it.NumVirtualMethods() != 0) {
2858 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002859 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2860 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002861 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002862 CHECK(self->IsExceptionPending()); // OOME.
2863 return;
2864 }
2865 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002866 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002867 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002868 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2869 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002870 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002871 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002872 StackHandleScope<1> hs(self);
2873 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002874 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002875 CHECK(self->IsExceptionPending()); // OOME.
2876 return;
2877 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002878 klass->SetDirectMethod(i, method.Get());
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002879 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002880 uint32_t it_method_index = it.GetMemberIndex();
2881 if (last_dex_method_index == it_method_index) {
2882 // duplicate case
2883 method->SetMethodIndex(last_class_def_method_index);
2884 } else {
2885 method->SetMethodIndex(class_def_method_index);
2886 last_dex_method_index = it_method_index;
2887 last_class_def_method_index = class_def_method_index;
2888 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002889 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002890 }
2891 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002892 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002893 StackHandleScope<1> hs(self);
2894 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002895 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002896 CHECK(self->IsExceptionPending()); // OOME.
2897 return;
2898 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002899 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002900 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002901 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002902 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002903 }
2904 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002905}
2906
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002907void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002908 Handle<mirror::Class> klass,
2909 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002910 uint32_t field_idx = it.GetMemberIndex();
2911 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002912 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002913 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002914}
2915
Brian Carlstromea46f952013-07-30 01:26:50 -07002916mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002917 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002918 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002919 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002920 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002921 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002922
Brian Carlstromea46f952013-07-30 01:26:50 -07002923 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002924 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002925 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002926 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002927 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002928 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002929
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002930 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002931 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002932 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002933 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002934
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002935 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002936 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002937 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002938
Andreas Gampe51829322014-08-25 15:05:04 -07002939 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002940
Ian Rogersdfb325e2013-10-30 01:00:44 -07002941 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002942 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002943 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2944 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002945 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002946 klass->SetFinalizable();
2947 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002948 std::string temp;
2949 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002950 // The Enum class declares a "final" finalize() method to prevent subclasses from
2951 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2952 // subclasses, so we exclude it here.
2953 // We also want to avoid setting the flag on Object, where we know that finalize() is
2954 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002955 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2956 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002957 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002958 }
2959 }
2960 }
2961 } else if (method_name[0] == '<') {
2962 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002963 bool is_init = (strcmp("<init>", method_name) == 0);
2964 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002965 if (UNLIKELY(!is_init && !is_clinit)) {
2966 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2967 } else {
2968 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2969 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002970 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002971 access_flags |= kAccConstructor;
2972 }
2973 }
2974 }
2975 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002976
Mathieu Chartier66f19252012-09-18 08:57:04 -07002977 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002978}
2979
Ian Rogers7b078e82014-09-10 14:44:24 -07002980void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002981 StackHandleScope<1> hs(self);
2982 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002983 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2984 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002985 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002986}
2987
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002988void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002989 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002990 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002991 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002992 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002993}
2994
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002995bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002996 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002997 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002998 mirror::DexCache* dex_cache = GetDexCache(i);
2999 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08003000 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003001 }
3002 }
3003 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07003004}
3005
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003006bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003007 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07003008 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003009}
3010
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003011void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003012 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003013 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003014 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003015 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3016 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003017 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003018 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003019 if (log_new_dex_caches_roots_) {
3020 // TODO: This is not safe if we can remove dex caches.
3021 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3022 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003023}
3024
Brian Carlstromaded5f72011-10-07 17:15:04 -07003025void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003026 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003027 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003028 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003029 if (IsDexFileRegisteredLocked(dex_file)) {
3030 return;
3031 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003032 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003033 // Don't alloc while holding the lock, since allocation may need to
3034 // suspend all threads and another thread may need the dex_lock_ to
3035 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003036 StackHandleScope<1> hs(self);
3037 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003038 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3039 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003040 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003041 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003042 if (IsDexFileRegisteredLocked(dex_file)) {
3043 return;
3044 }
3045 RegisterDexFileLocked(dex_file, dex_cache);
3046 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003047}
3048
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003049void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003050 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003051 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003052 RegisterDexFileLocked(dex_file, dex_cache);
3053}
3054
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003055mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003056 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003057 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003058 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003059 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003060 if (dex_cache->GetDexFile() == &dex_file) {
3061 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003062 }
3063 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003064 // Search matching by location name.
3065 std::string location(dex_file.GetLocation());
3066 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003067 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003068 if (dex_cache->GetDexFile()->GetLocation() == location) {
3069 return dex_cache;
3070 }
3071 }
3072 // Failure, dump diagnostic and abort.
3073 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003074 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003075 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3076 }
3077 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003078 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003079}
3080
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003081void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003082 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003083 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003084 mirror::DexCache* dex_cache = GetDexCache(i);
3085 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003086 }
3087}
3088
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003089mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003090 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003091 if (UNLIKELY(klass == nullptr)) {
3092 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003093 }
3094 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003095}
3096
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003097mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3098 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003099 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003100 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003101 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003102 StackHandleScope<1> hs(self);
3103 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003104 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003105 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003106 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003107 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3108 const char* descriptor = Primitive::Descriptor(type);
3109 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003110 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003111 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003112}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003113
Brian Carlstrombe977852011-07-19 14:54:54 -07003114// Create an array class (i.e. the class object for the array, not the
3115// array itself). "descriptor" looks like "[C" or "[[[[B" or
3116// "[Ljava/lang/String;".
3117//
3118// If "descriptor" refers to an array of primitives, look up the
3119// primitive type's internally-generated class object.
3120//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003121// "class_loader" is the class loader of the class that's referring to
3122// us. It's used to ensure that we're looking for the element type in
3123// the right context. It does NOT become the class loader for the
3124// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003125//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003126// Returns nullptr with an exception raised on failure.
Ian Rogers98379392014-02-24 16:53:16 -08003127mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003128 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003129 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003130 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003131 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003132 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3133 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003134 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003135 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003136 // We need to accept erroneous classes as component types.
Ian Rogers7b078e82014-09-10 14:44:24 -07003137 component_type.Assign(LookupClass(self, descriptor + 1, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003138 if (component_type.Get() == nullptr) {
3139 DCHECK(self->IsExceptionPending());
3140 return nullptr;
3141 } else {
3142 self->ClearException();
3143 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003144 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003145 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3146 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3147 return nullptr;
3148 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003149 // See if the component type is already loaded. Array classes are
3150 // always associated with the class loader of their underlying
3151 // element type -- an array of Strings goes with the loader for
3152 // java/lang/String -- so we need to look for it there. (The
3153 // caller should have checked for the existence of the class
3154 // before calling here, but they did so with *their* class loader,
3155 // not the component type's loader.)
3156 //
3157 // If we find it, the caller adds "loader" to the class' initiating
3158 // loader list, which should prevent us from going through this again.
3159 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003160 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003161 // are the same, because our caller (FindClass) just did the
3162 // lookup. (Even if we get this wrong we still have correct behavior,
3163 // because we effectively do this lookup again when we add the new
3164 // class to the hash table --- necessary because of possible races with
3165 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003166 if (class_loader.Get() != component_type->GetClassLoader()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003167 mirror::Class* new_class = LookupClass(self, descriptor, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003168 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003169 return new_class;
3170 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003171 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003172
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003173 // Fill out the fields in the Class.
3174 //
3175 // It is possible to execute some methods against arrays, because
3176 // all arrays are subclasses of java_lang_Object_, so we need to set
3177 // up a vtable. We can just point at the one in java_lang_Object_.
3178 //
3179 // Array classes are simple enough that we don't need to do a full
3180 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003181 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003182 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003183 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003184 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003185 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003186 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003187 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003188 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003189 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003190 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003191 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003192 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003193 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003194 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003195 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003196 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003197 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003198 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003199 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003200 }
3201 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003202 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003203 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003204 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003205 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003206 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003207 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003208 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003209 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003210 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003211 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003212 new_class->SetSuperClass(java_lang_Object);
3213 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003214 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003215 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003216 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003217 {
3218 StackHandleScope<mirror::Class::kImtSize> hs(self,
3219 Runtime::Current()->GetImtUnimplementedMethod());
3220 new_class->PopulateEmbeddedImtAndVTable(&hs);
3221 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003222 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003223 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003224 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003225
3226
3227 // All arrays have java/lang/Cloneable and java/io/Serializable as
3228 // interfaces. We need to set that up here, so that stuff like
3229 // "instanceof" works right.
3230 //
3231 // Note: The GC could run during the call to FindSystemClass,
3232 // so we need to make sure the class object is GC-valid while we're in
3233 // there. Do this by clearing the interface list so the GC will just
3234 // think that the entries are null.
3235
3236
3237 // Use the single, global copies of "interfaces" and "iftable"
3238 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003239 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003240 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003241 CHECK(array_iftable != nullptr);
3242 new_class->SetIfTable(array_iftable);
3243 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003244
Elliott Hughes00626c22013-06-14 15:04:14 -07003245 // Inherit access flags from the component type.
3246 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3247 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3248 access_flags &= kAccJavaFlagsMask;
3249 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003250 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003251 access_flags |= kAccAbstract | kAccFinal;
3252 access_flags &= ~kAccInterface;
3253
3254 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003255
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003256 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor));
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003257 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003258 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003259 }
3260 // Another thread must have loaded the class after we
3261 // started but before we finished. Abandon what we've
3262 // done.
3263 //
3264 // (Yes, this happens.)
3265
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003266 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003267}
3268
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003269mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003270 switch (type) {
3271 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003272 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003273 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003274 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003275 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003276 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003277 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003278 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003279 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003280 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003281 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003282 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003283 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003284 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003285 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003286 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003287 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003288 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003289 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003290 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003291 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003292 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003293 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003294 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003295}
3296
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003297mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3298 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003299 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003300 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003301 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003302 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003303 source += " from ";
3304 source += dex_cache->GetLocation()->ToModifiedUtf8();
3305 }
3306 LOG(INFO) << "Loaded class " << descriptor << source;
3307 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003308 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003309 mirror::Class* existing =
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003310 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003311 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003312 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003313 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003314 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003315 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003316 // Check a class loaded with the system class loader matches one in the image if the class
3317 // is in the image.
3318 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003319 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003320 CHECK(klass == existing);
3321 }
3322 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003323 VerifyObject(klass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003324 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003325 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003326 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003327 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003328 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003329}
3330
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003331mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3332 size_t hash) {
3333 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3334 mirror::Class* existing =
3335 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
3336
3337 if (existing == nullptr) {
3338 CHECK(klass->IsProxyClass());
3339 return nullptr;
3340 }
3341
3342 CHECK_NE(existing, klass) << descriptor;
3343 CHECK(!existing->IsResolved()) << descriptor;
3344 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3345
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003346 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3347 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003348 mirror::Class* klass = it->second.Read();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07003349 if (klass == existing) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003350 class_table_.erase(it);
3351 break;
3352 }
3353 }
3354
3355 CHECK(!klass->IsTemp()) << descriptor;
3356 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3357 dex_cache_image_class_lookup_required_) {
3358 // Check a class loaded with the system class loader matches one in the image if the class
3359 // is in the image.
3360 existing = LookupClassFromImage(descriptor);
3361 if (existing != nullptr) {
3362 CHECK(klass == existing) << descriptor;
3363 }
3364 }
3365 VerifyObject(klass);
3366
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003367 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003368 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003369 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003370 }
3371
3372 return existing;
3373}
3374
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003375bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003376 size_t hash = Hash(descriptor);
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003377 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstromf3632832014-05-20 15:36:53 -07003378 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3379 it != end && it->first == hash;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003380 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003381 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003382 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003383 class_table_.erase(it);
Brian Carlstromae826982011-11-09 01:33:42 -08003384 return true;
3385 }
3386 }
3387 return false;
3388}
3389
Ian Rogers7b078e82014-09-10 14:44:24 -07003390mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003391 const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003392 size_t hash = Hash(descriptor);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003393 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003394 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003395 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003396 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003397 return result;
3398 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003399 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003400 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3401 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003402 } else {
3403 // Lookup failed but need to search dex_caches_.
3404 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003405 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003406 InsertClass(descriptor, result, hash);
3407 } else {
3408 // Searching the image dex files/caches failed, we don't want to get into this situation
3409 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3410 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003411 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003412 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3413 MoveImageClassesToClassTable();
3414 }
3415 }
3416 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003417 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003418}
3419
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003420mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
3421 const mirror::ClassLoader* class_loader,
3422 size_t hash) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003423 auto end = class_table_.end();
3424 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003425 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003426 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003427 if (kIsDebugBuild) {
3428 // Check for duplicates in the table.
3429 for (++it; it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003430 mirror::Class* klass2 = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003431 CHECK(!(klass2->GetClassLoader() == class_loader &&
3432 klass2->DescriptorEquals(descriptor)))
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003433 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
3434 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003435 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003436 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003437 return klass;
3438 }
3439 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003440 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003441}
3442
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003443static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3444 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3445 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003446 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003447 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3448 return root->AsObjectArray<mirror::DexCache>();
3449}
3450
3451void ClassLinker::MoveImageClassesToClassTable() {
3452 Thread* self = Thread::Current();
3453 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3454 if (!dex_cache_image_class_lookup_required_) {
3455 return; // All dex cache classes are already in the class table.
3456 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003457 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003458 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003459 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003460 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3461 mirror::DexCache* dex_cache = dex_caches->Get(i);
3462 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3463 for (int32_t j = 0; j < types->GetLength(); j++) {
3464 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003465 if (klass != nullptr) {
3466 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003467 const char* descriptor = klass->GetDescriptor(&temp);
3468 size_t hash = Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003469 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3470 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003471 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
3472 << PrettyClassAndClassLoader(klass);
3473 } else {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003474 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003475 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003476 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003477 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003478 }
3479 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003480 }
3481 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003482 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003483}
3484
3485mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003486 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003487 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3488 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3489 mirror::DexCache* dex_cache = dex_caches->Get(i);
3490 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003491 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003492 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003493 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003494 const DexFile::TypeId* type_id =
3495 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003496 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003497 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3498 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003499 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003500 return klass;
3501 }
3502 }
3503 }
3504 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003505 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003506}
3507
3508void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3509 result.clear();
3510 if (dex_cache_image_class_lookup_required_) {
3511 MoveImageClassesToClassTable();
3512 }
3513 size_t hash = Hash(descriptor);
3514 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003515 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
Mathieu Chartier02e25112013-08-14 16:14:24 -07003516 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003517 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003518 if (klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003519 result.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003520 }
3521 }
3522}
3523
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003524void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003525 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003526 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003527
Ian Rogers9ffb0392012-09-10 11:56:50 -07003528 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003529 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003530 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003531 return;
3532 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003533 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3534 return;
3535 }
jeffhao98eacac2011-09-14 16:11:53 -07003536
Ian Rogers9ffb0392012-09-10 11:56:50 -07003537 // The class might already be erroneous, for example at compile time if we attempted to verify
3538 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003539 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003540 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003541 return;
3542 }
3543
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003544 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003545 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003546 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003547 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003548 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003549 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003550 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003551 }
jeffhao98eacac2011-09-14 16:11:53 -07003552
Jeff Hao4a200f52014-04-01 14:58:49 -07003553 // Skip verification if disabled.
3554 if (!Runtime::Current()->IsVerificationEnabled()) {
3555 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003556 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003557 return;
3558 }
3559
Ian Rogers9ffb0392012-09-10 11:56:50 -07003560 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003561 StackHandleScope<2> hs(self);
3562 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003563 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003564 // Acquire lock to prevent races on verifying the super class.
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003565 ObjectLock<mirror::Class> lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003566
3567 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003568 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003569 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003570 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003571 std::string error_msg(
3572 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3573 PrettyDescriptor(klass.Get()).c_str(),
3574 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003575 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003576 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3577 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003578 self->ClearException();
3579 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003580 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3581 if (cause.Get() != nullptr) {
3582 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003583 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003584 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003585 if (Runtime::Current()->IsCompiler()) {
3586 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3587 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003588 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003589 return;
3590 }
3591 }
3592
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003593 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003594 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003595 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003596 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003597 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003598 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003599 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003600 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003601 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3602 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003603 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003604 return;
3605 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003606 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003607 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003608 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003609 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003610 Runtime::Current()->IsCompiler(),
3611 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003612 }
3613 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003614 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003615 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003616 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3617 << " because: " << error_msg;
3618 }
Ian Rogers1f539342012-10-03 21:09:42 -07003619 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003620 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003621 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003622 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003623 // Even though there were no verifier failures we need to respect whether the super-class
3624 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003625 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003626 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003627 } else {
3628 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003629 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003630 // Pretend a soft failure occured so that we don't consider the class verified below.
3631 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003632 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003633 } else {
3634 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3635 // Soft failures at compile time should be retried at runtime. Soft
3636 // failures at runtime will be handled by slow paths in the generated
3637 // code. Set status accordingly.
3638 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003639 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003640 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003641 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003642 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3643 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003644 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003645 }
3646 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003647 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003648 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003649 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3650 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003651 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003652 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003653 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003654 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003655 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003656 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003657 // Let the interpreter know it by setting the kAccPreverified flag onto each
3658 // method.
3659 // Note: we're going here during compilation and at runtime. When we set the
3660 // kAccPreverified flag when compiling image classes, the flag is recorded
3661 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003662 EnsurePreverifiedMethods(klass);
3663 }
3664}
3665
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003666void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003667 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003668 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003669 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003670 }
jeffhao98eacac2011-09-14 16:11:53 -07003671}
3672
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003673bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3674 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003675 // If we're compiling, we can only verify the class using the oat file if
3676 // we are not compiling the image or if the class we're verifying is not part of
3677 // the app. In other words, we will only check for preverification of bootclasspath
3678 // classes.
3679 if (Runtime::Current()->IsCompiler()) {
3680 // Are we compiling the bootclasspath?
3681 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3682 return false;
3683 }
3684 // We are compiling an app (not the image).
3685
3686 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003687 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003688 return false;
3689 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003690 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003691
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003692 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003693 // In case we run without an image there won't be a backing oat file.
3694 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003695 return false;
3696 }
3697
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003698 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003699 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003700 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3701 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003702 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003703 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003704 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003705 // Compile time verification failed with a soft error. Compile time verification can fail
3706 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003707 // class ... {
3708 // Foo x;
3709 // .... () {
3710 // if (...) {
3711 // v1 gets assigned a type of resolved class Foo
3712 // } else {
3713 // v1 gets assigned a type of unresolved class Bar
3714 // }
3715 // iput x = v1
3716 // } }
3717 // when we merge v1 following the if-the-else it results in Conflict
3718 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3719 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3720 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3721 // at compile time).
3722 return false;
3723 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003724 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003725 // Compile time verification failed with a hard error. This is caused by invalid instructions
3726 // in the class. These errors are unrecoverable.
3727 return false;
3728 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003729 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003730 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3731 // not loading the class.
3732 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3733 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003734 return false;
3735 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003736 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003737 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003738 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003739 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003740
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003741 return false;
3742}
3743
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003744void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003745 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003746 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3747 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3748 }
3749 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3750 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3751 }
3752}
3753
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003754void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003755 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003756 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3757 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003758 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003759 return; // native or abstract method
3760 }
3761 if (code_item->tries_size_ == 0) {
3762 return; // nothing to process
3763 }
Ian Rogers13735952014-10-08 12:43:28 -07003764 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003765 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3766 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3767 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3768 CatchHandlerIterator iterator(handlers_ptr);
3769 for (; iterator.HasNext(); iterator.Next()) {
3770 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3771 // unresolved exception types will be ignored by exception delivery
3772 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003773 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003774 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003775 DCHECK(Thread::Current()->IsExceptionPending());
3776 Thread::Current()->ClearException();
3777 }
3778 }
3779 }
3780 handlers_ptr = iterator.EndDataPointer();
3781 }
3782}
3783
Brian Carlstromea46f952013-07-30 01:26:50 -07003784static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003785static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3786 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003787
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003788mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003789 jobjectArray interfaces, jobject loader,
3790 jobjectArray methods, jobjectArray throws) {
3791 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003792 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003793 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003794 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003795 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003796 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003797 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003798 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003799 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003800 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003801 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3802 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003803 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003804 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003805 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003806 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003807 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003808 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003809
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003810 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003811 {
3812 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003813 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003814 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003815 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003816 }
3817 klass->SetSFields(sfields);
3818 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003819 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3820 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003821 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3822 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003823 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003824 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003825 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003826 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003827 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003828 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003829 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3830 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003831 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3832 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003833 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003834 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003835 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003836 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003837 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003838 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003839 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003840
Ian Rogers466bb252011-10-14 03:29:56 -07003841 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003842 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003843 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003844 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003845 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003846 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003847 }
3848 klass->SetDirectMethods(directs);
3849 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003850 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003851 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003852 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003853 }
3854 klass->SetDirectMethod(0, constructor);
3855 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003856
Mathieu Chartier590fee92013-09-13 13:46:47 -07003857 // Create virtual method using specified prototypes.
3858 size_t num_virtual_methods =
3859 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003860 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003861 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3862 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003863 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003864 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003865 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003866 }
3867 klass->SetVirtualMethods(virtuals);
3868 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003869 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003870 StackHandleScope<1> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003871 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3872 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003873 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003874 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003875 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003876 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003877 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003878 }
3879 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003880 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003881
3882 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003883 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003884 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003885
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003886 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3887 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003888 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003889 // Must hold lock on object when resolved.
3890 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003891 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003892 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003893 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003894 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003895 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003896 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003897 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003898 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003899
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003900 CHECK(klass->IsRetired());
3901 CHECK_NE(klass.Get(), new_class);
3902 klass.Assign(new_class);
3903
3904 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003905 interfaces_sfield->SetObject<false>(klass.Get(),
3906 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003907 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003908 throws_sfield->SetObject<false>(klass.Get(),
3909 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003910
3911 {
3912 // Lock on klass is released. Lock new class object.
3913 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003914 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003915 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003916
3917 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003918 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003919 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003920 CheckProxyConstructor(klass->GetDirectMethod(0));
3921 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003922 StackHandleScope<2> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003923 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3924 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003925 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003926 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3927 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003928 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003929
Mathieu Chartier590fee92013-09-13 13:46:47 -07003930 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003931 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
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(0)), interfaces_field_name);
3934
3935 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003936 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003937 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003938
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003939 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003940 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003941 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003942 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003943 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003944 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003945 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003946 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003947}
3948
Ian Rogersef7d42f2014-01-06 12:55:46 -08003949std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003950 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003951 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003952 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003953 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3954}
3955
Ian Rogersef7d42f2014-01-06 12:55:46 -08003956mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3957 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003958 DCHECK(proxy_class->IsProxyClass());
3959 DCHECK(proxy_method->IsProxyMethod());
3960 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003961 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003962 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003963 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003964 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003965 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003966 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003967 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003968 break;
3969 }
3970 }
3971 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003972 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003973 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003974 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003975 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003976 return resolved_method;
3977}
3978
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003979
Brian Carlstromea46f952013-07-30 01:26:50 -07003980mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003981 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003982 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003983 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003984 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003985 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003986 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3987 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003988 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3989 // constructor method.
3990 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3991 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003992 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3993 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003994 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3995 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003996 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003997 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003998 }
Ian Rogers466bb252011-10-14 03:29:56 -07003999 // Make this constructor public and fix the class to be our Proxy version
4000 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004001 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004002 return constructor;
4003}
4004
Brian Carlstromea46f952013-07-30 01:26:50 -07004005static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004006 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004007 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004008 CHECK_STREQ(constructor->GetName(), "<init>");
4009 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4010 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004011 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004012}
4013
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004014mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004015 Handle<mirror::Class> klass,
4016 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004017 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4018 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004019 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004020 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004021 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004022 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004023 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004024 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004025 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004026 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004027 }
Ian Rogers466bb252011-10-14 03:29:56 -07004028
4029 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4030 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004031 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004032 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004033
Ian Rogers466bb252011-10-14 03:29:56 -07004034 // At runtime the method looks like a reference and argument saving method, clone the code
4035 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004036 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4037 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004038 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004039
Ian Rogersc2b44472011-12-14 21:17:17 -08004040 return method;
4041}
Jesse Wilson95caa792011-10-12 18:14:17 -04004042
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004043static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4044 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004045 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004046 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004047 CHECK(!prototype->IsFinal());
4048 CHECK(method->IsFinal());
4049 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004050
4051 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4052 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
4053 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
Andreas Gampe58a5af82014-07-31 16:23:49 -07004054 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4055 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004056 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4057
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004058 CHECK_STREQ(method->GetName(), prototype->GetName());
4059 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004060 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004061 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004062}
4063
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004064static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4065 bool can_init_parents)
4066 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004067 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004068 return true;
4069 }
4070 if (!can_init_statics) {
4071 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004072 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004073 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004074 return false;
4075 }
4076 // Check if there are encoded static values needing initialization.
4077 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004078 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004079 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004080 if (dex_class_def->static_values_off_ != 0) {
4081 return false;
4082 }
4083 }
4084 }
4085 if (!klass->IsInterface() && klass->HasSuperClass()) {
4086 mirror::Class* super_class = klass->GetSuperClass();
4087 if (!can_init_parents && !super_class->IsInitialized()) {
4088 return false;
4089 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004090 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004091 return false;
4092 }
4093 }
4094 }
4095 return true;
4096}
4097
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004098bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004099 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004100 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4101
4102 // Are we already initialized and therefore done?
4103 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4104 // an initialized class will never change its state.
4105 if (klass->IsInitialized()) {
4106 return true;
4107 }
4108
4109 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004110 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004111 return false;
4112 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004113
Ian Rogers7b078e82014-09-10 14:44:24 -07004114 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004115 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004116 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004117 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004118
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004119 // Re-check under the lock in case another thread initialized ahead of us.
4120 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004121 return true;
4122 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004123
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004124 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004125 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004126 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004127 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004128 return false;
4129 }
4130
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004131 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004132
4133 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004134 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004135 if (!klass->IsVerified()) {
4136 // We failed to verify, expect either the klass to be erroneous or verification failed at
4137 // compile time.
4138 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004139 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004140 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004141 } else {
4142 CHECK(Runtime::Current()->IsCompiler());
4143 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004144 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004145 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004146 } else {
4147 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004148 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004149 }
4150
Brian Carlstromd1422f82011-09-28 11:37:09 -07004151 // If the class is kStatusInitializing, either this thread is
4152 // initializing higher up the stack or another thread has beat us
4153 // to initializing and we need to wait. Either way, this
4154 // invocation of InitializeClass will not be responsible for
4155 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004156 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004157 // Could have got an exception during verification.
4158 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004159 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004160 return false;
4161 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004162 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004163 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004164 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004165 return true;
4166 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004167 // No. That's fine. Wait for another thread to finish initializing.
4168 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004169 }
4170
4171 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004172 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004173 return false;
4174 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004175 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004176
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004177 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004178
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004179 // From here out other threads may observe that we're initializing and so changes of state
4180 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004181 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004182 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004183
4184 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004185 }
4186
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004187 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004188 if (!klass->IsInterface() && klass->HasSuperClass()) {
4189 mirror::Class* super_class = klass->GetSuperClass();
4190 if (!super_class->IsInitialized()) {
4191 CHECK(!super_class->IsInterface());
4192 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004193 StackHandleScope<1> hs(self);
4194 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004195 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004196 if (!super_initialized) {
4197 // The super class was verified ahead of entering initializing, we should only be here if
4198 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004199 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004200 << "Super class initialization failed for "
4201 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004202 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004203 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004204 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004205 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004206 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004207 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004208 return false;
4209 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004210 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004211 }
4212
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004213 const size_t num_static_fields = klass->NumStaticFields();
4214 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004215 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004216 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004217 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004218 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004219 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004220 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004221
4222 // Eagerly fill in static fields so that the we don't have to do as many expensive
4223 // Class::FindStaticField in ResolveField.
4224 for (size_t i = 0; i < num_static_fields; ++i) {
4225 mirror::ArtField* field = klass->GetStaticField(i);
4226 const uint32_t field_idx = field->GetDexFieldIndex();
4227 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4228 if (resolved_field == nullptr) {
4229 dex_cache->SetResolvedField(field_idx, field);
4230 } else if (kIsDebugBuild) {
4231 CHECK_EQ(field, resolved_field);
4232 }
4233 }
4234
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004235 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4236 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004237 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004238 ClassDataItemIterator field_it(dex_file, class_data);
4239 if (value_it.HasNext()) {
4240 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004241 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004242 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004243 StackHandleScope<1> hs(self);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004244 Handle<mirror::ArtField> field(hs.NewHandle(
4245 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004246 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004247 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004248 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004249 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004250 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004251 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004252 }
4253 }
4254 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004255
Ian Rogersd91d6d62013-09-25 20:26:14 -07004256 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004257 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004258 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004259 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004260 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004261 }
4262
Ian Rogers7b078e82014-09-10 14:44:24 -07004263 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004264 uint64_t t1 = NanoTime();
4265
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004266 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004267 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004268 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004269
4270 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004271 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004272 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004273 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004274 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004275 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4276 RuntimeStats* thread_stats = self->GetStats();
4277 ++global_stats->class_init_count;
4278 ++thread_stats->class_init_count;
4279 global_stats->class_init_time_ns += (t1 - t0);
4280 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004281 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004282 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004283 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004284 std::string temp;
4285 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004286 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004287 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004288 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004289 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004290 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004291 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004292 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004293}
4294
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004295bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004296 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004297 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004298 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004299 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004300 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004301 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004302
4303 // When we wake up, repeat the test for init-in-progress. If
4304 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004305 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004306 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004307 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004308 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004309 return false;
4310 }
4311 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004312 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004313 continue;
4314 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004315 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004316 // Compile time initialization failed.
4317 return false;
4318 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004319 if (klass->IsErroneous()) {
4320 // The caller wants an exception, but it was thrown in a
4321 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004322 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004323 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004324 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004325 return false;
4326 }
4327 if (klass->IsInitialized()) {
4328 return true;
4329 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004330 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004331 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004332 }
Ian Rogers07140832014-09-30 15:43:59 -07004333 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004334}
4335
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004336bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004337 if (klass->IsInterface()) {
4338 return true;
4339 }
Ian Rogers151f2212014-05-06 11:27:27 -07004340 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004341 Thread* self = Thread::Current();
4342 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004343 MutableMethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4344 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004345 if (klass->HasSuperClass() &&
4346 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004347 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4348 mh.ChangeMethod(klass->GetVTableEntry(i));
4349 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004350 if (mh.GetMethod() != super_mh.GetMethod() &&
Ian Rogersded66a02014-10-28 18:12:55 -07004351 !mh.HasSameSignatureWithDifferentClassLoaders(self, &super_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004352 ThrowLinkageError(klass.Get(),
4353 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004354 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004355 PrettyMethod(mh.GetMethod()).c_str(),
4356 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004357 return false;
4358 }
4359 }
4360 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004361 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004362 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4363 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4364 for (uint32_t j = 0; j < num_methods; ++j) {
4365 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4366 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004367 if (mh.GetMethod() != super_mh.GetMethod() &&
Ian Rogersded66a02014-10-28 18:12:55 -07004368 !mh.HasSameSignatureWithDifferentClassLoaders(self, &super_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004369 ThrowLinkageError(klass.Get(),
4370 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004371 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004372 PrettyMethod(mh.GetMethod()).c_str(),
4373 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004374 return false;
4375 }
4376 }
4377 }
4378 }
4379 return true;
4380}
4381
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004382bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4383 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004384 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004385 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004386 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004387 return true;
4388 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004389 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004390 if (!success) {
4391 if (can_init_fields && can_init_parents) {
4392 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4393 }
4394 } else {
4395 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004396 }
4397 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004398}
4399
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004400void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4401 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4402 if (fields != nullptr) {
4403 for (int index = 0; index < fields->GetLength(); index ++) {
4404 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4405 fields->Get(index)->SetDeclaringClass(new_class);
4406 }
4407 }
4408 }
4409
4410 fields = new_class->GetSFields();
4411 if (fields != nullptr) {
4412 for (int index = 0; index < fields->GetLength(); index ++) {
4413 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4414 fields->Get(index)->SetDeclaringClass(new_class);
4415 }
4416 }
4417 }
4418
4419 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4420 if (methods != nullptr) {
4421 for (int index = 0; index < methods->GetLength(); index ++) {
4422 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4423 methods->Get(index)->SetDeclaringClass(new_class);
4424 }
4425 }
4426 }
4427
4428 methods = new_class->GetVirtualMethods();
4429 if (methods != nullptr) {
4430 for (int index = 0; index < methods->GetLength(); index ++) {
4431 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4432 methods->Get(index)->SetDeclaringClass(new_class);
4433 }
4434 }
4435 }
4436}
4437
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004438bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4439 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004440 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004441 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004442
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004443 if (!LinkSuperClass(klass)) {
4444 return false;
4445 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004446 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4447 self, Runtime::Current()->GetImtUnimplementedMethod());
4448 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004449 return false;
4450 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004451 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004452 return false;
4453 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004454 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004455 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004456 return false;
4457 }
4458 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004459 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004460
4461 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4462 // We don't need to retire this class as it has no embedded tables or it was created the
4463 // correct size during class linker initialization.
4464 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4465
4466 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004467 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004468 }
4469
4470 // This will notify waiters on klass that saw the not yet resolved
4471 // class in the class_table_ during EnsureResolved.
4472 klass->SetStatus(mirror::Class::kStatusResolved, self);
4473 *new_class = klass.Get();
4474 } else {
4475 CHECK(!klass->IsResolved());
4476 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004477 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004478 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004479 CHECK(self->IsExceptionPending()); // Expect an OOME.
4480 klass->SetStatus(mirror::Class::kStatusError, self);
4481 return false;
4482 }
4483
4484 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4485 StackHandleScope<1> hs(self);
4486 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4487 ObjectLock<mirror::Class> lock(self, new_class_h);
4488
4489 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4490
4491 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004492 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004493
4494 // This will notify waiters on temp class that saw the not yet resolved class in the
4495 // class_table_ during EnsureResolved.
4496 klass->SetStatus(mirror::Class::kStatusRetired, self);
4497
4498 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4499 // This will notify waiters on new_class that saw the not yet resolved
4500 // class in the class_table_ during EnsureResolved.
4501 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004502 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004503 return true;
4504}
4505
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004506bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004507 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004508 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4509 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004510 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004511 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004512 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004513 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004514 return false;
4515 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004516 // Verify
4517 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004518 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004519 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004520 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004521 return false;
4522 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004523 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004524 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004525 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004526 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004527 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004528 for (size_t i = 0; i < interfaces->Size(); i++) {
4529 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004530 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004531 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004532 DCHECK(Thread::Current()->IsExceptionPending());
4533 return false;
4534 }
4535 // Verify
4536 if (!klass->CanAccess(interface)) {
4537 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004538 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004539 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004540 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004541 return false;
4542 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004543 }
4544 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004545 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004546 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004547 return true;
4548}
4549
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004550bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004551 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004552 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004553 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004554 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004555 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004556 return false;
4557 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004558 return true;
4559 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004560 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004561 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4562 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004563 return false;
4564 }
4565 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004566 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004567 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004568 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004569 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004570 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004571 return false;
4572 }
4573 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004574 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004575 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004576 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004577 return false;
4578 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004579
Brian Carlstromf3632832014-05-20 15:36:53 -07004580 // Inherit kAccClassIsFinalizable from the superclass in case this
4581 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004582 if (super->IsFinalizable()) {
4583 klass->SetFinalizable();
4584 }
4585
Elliott Hughes2da50362011-10-10 16:57:08 -07004586 // Inherit reference flags (if any) from the superclass.
4587 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4588 if (reference_flags != 0) {
4589 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4590 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004591 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004592 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004593 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004594 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004595 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004596 return false;
4597 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004598
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004599 if (kIsDebugBuild) {
4600 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004601 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004602 CHECK(super->IsResolved());
4603 super = super->GetSuperClass();
4604 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004605 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004606 return true;
4607}
4608
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004609// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004610bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004611 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4612 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004613 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004614 if (klass->IsInterface()) {
4615 // No vtable.
4616 size_t count = klass->NumVirtualMethods();
4617 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004618 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004619 return false;
4620 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004621 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004622 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004623 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004624 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4625 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004626 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004627 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004628}
4629
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004630// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4631// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4632// caches in the implementation below.
4633class MethodNameAndSignatureComparator FINAL : public ValueObject {
4634 public:
4635 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4636 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4637 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4638 name_(nullptr), name_len_(0) {
4639 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4640 }
4641
4642 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4643 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4644 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4645 const DexFile* other_dex_file = other->GetDexFile();
4646 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4647 if (dex_file_ == other_dex_file) {
4648 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4649 }
4650 if (name_ == nullptr) {
4651 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4652 }
4653 uint32_t other_name_len;
4654 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4655 &other_name_len);
4656 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4657 return false;
4658 }
4659 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4660 }
4661
4662 private:
4663 // Dex file for the method to compare against.
4664 const DexFile* const dex_file_;
4665 // MethodId for the method to compare against.
4666 const DexFile::MethodId* const mid_;
4667 // Lazily computed name from the dex file's strings.
4668 const char* name_;
4669 // Lazily computed name length.
4670 uint32_t name_len_;
4671};
4672
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004673bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004674 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004675 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004676 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4677 const size_t max_count = num_virtual_methods + super_vtable_length;
4678 size_t actual_count = super_vtable_length;
4679 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004680 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004681 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004682 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4683 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4684 if (UNLIKELY(vtable.Get() == nullptr)) {
4685 CHECK(self->IsExceptionPending()); // OOME.
4686 return false;
4687 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004688 for (size_t i = 0; i < super_vtable_length; i++) {
4689 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004690 }
4691 } else {
Mingyao Yang38eecb02014-08-13 14:51:03 -07004692 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class.Get());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004693 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count));
4694 if (UNLIKELY(vtable.Get() == nullptr)) {
4695 CHECK(self->IsExceptionPending()); // OOME.
4696 return false;
4697 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004698 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004699
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004700 // See if any of our virtual methods override the superclass.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004701 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004702 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004703 MethodNameAndSignatureComparator
4704 virtual_method_name_comparator(local_method->GetInterfaceMethodIfProxy());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004705 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004706 for (; j < actual_count; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004707 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004708 if (super_method->GetDeclaringClass() == klass.Get()) {
4709 continue; // A previously overridden method.
4710 }
4711 if (virtual_method_name_comparator.HasSameNameAndSignature(super_method)) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004712 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4713 super_method->GetAccessFlags())) {
Elliott Hughes39717372012-07-13 16:21:23 -07004714 if (super_method->IsFinal()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004715 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
Elliott Hughes39717372012-07-13 16:21:23 -07004716 PrettyMethod(local_method).c_str(),
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004717 super_method->GetDeclaringClassDescriptor());
Elliott Hughes39717372012-07-13 16:21:23 -07004718 return false;
4719 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004720 vtable->SetWithoutChecks<false>(j, local_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004721 local_method->SetMethodIndex(j);
4722 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004723 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004724 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
4725 << " would have incorrectly overridden the package-private method in "
4726 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004727 }
4728 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004729 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004730 // Not overriding, append.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004731 vtable->SetWithoutChecks<false>(actual_count, local_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004732 local_method->SetMethodIndex(actual_count);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004733 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004734 }
4735 }
4736 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004737 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004738 return false;
4739 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004740 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004741 CHECK_LE(actual_count, max_count);
4742 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004743 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004744 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004745 CHECK(self->IsExceptionPending()); // OOME.
4746 return false;
4747 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004748 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004749 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004750 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004751 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004752 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004753 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4754 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004755 return false;
4756 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004757 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4758 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004759 CHECK(self->IsExceptionPending()); // OOME.
4760 return false;
4761 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004762 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004763 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004764 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004765 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004766 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004767 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004768 }
4769 return true;
4770}
4771
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004772bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4773 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4774 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004775 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004776 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004777 const bool has_superclass = klass->HasSuperClass();
4778 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4779 const bool have_interfaces = interfaces.Get() != nullptr;
4780 const size_t num_interfaces =
4781 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4782 if (num_interfaces == 0) {
4783 if (super_ifcount == 0) {
4784 // Class implements no interfaces.
4785 DCHECK_EQ(klass->GetIfTableCount(), 0);
4786 DCHECK(klass->GetIfTable() == nullptr);
4787 return true;
4788 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004789 // Class implements same interfaces as parent, are any of these not marker interfaces?
4790 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004791 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004792 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004793 if (super_iftable->GetMethodArrayCount(i) > 0) {
4794 has_non_marker_interface = true;
4795 break;
4796 }
4797 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004798 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004799 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004800 klass->SetIfTable(super_iftable);
4801 return true;
4802 }
4803 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004804 size_t ifcount = super_ifcount + num_interfaces;
4805 for (size_t i = 0; i < num_interfaces; i++) {
4806 mirror::Class* interface = have_interfaces ?
4807 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4808 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004809 if (UNLIKELY(!interface->IsInterface())) {
4810 std::string temp;
4811 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4812 PrettyDescriptor(klass.Get()).c_str(),
4813 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4814 return false;
4815 }
4816 ifcount += interface->GetIfTableCount();
4817 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004818 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004819 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004820 CHECK(self->IsExceptionPending()); // OOME.
4821 return false;
4822 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004823 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004824 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004825 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004826 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004827 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004828 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004829 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004830 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004831 // Flatten the interface inheritance hierarchy.
4832 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004833 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004834 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4835 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004836 // Check if interface is already in iftable
4837 bool duplicate = false;
4838 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004839 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004840 if (existing_interface == interface) {
4841 duplicate = true;
4842 break;
4843 }
4844 }
4845 if (!duplicate) {
4846 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004847 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004848 // Add this interface's non-duplicate super-interfaces.
4849 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004850 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004851 bool super_duplicate = false;
4852 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004853 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004854 if (existing_interface == super_interface) {
4855 super_duplicate = true;
4856 break;
4857 }
4858 }
4859 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004860 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004861 }
4862 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004863 }
4864 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004865 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004866 // Shrink iftable in case duplicates were found
4867 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004868 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004869 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004870 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004871 CHECK(self->IsExceptionPending()); // OOME.
4872 return false;
4873 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004874 ifcount = idx;
4875 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004876 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004877 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004878 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004879 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004880 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004881 return true;
4882 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004883 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004884 size_t max_miranda_methods = 0; // The max size of miranda_list.
4885 for (size_t i = 0; i < ifcount; ++i) {
4886 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4887 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004888 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004889 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004890 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4891 hs.NewHandle(klass->GetVTableDuringLinking()));
4892 // Copy the IMT from the super class if possible.
4893 bool extend_super_iftable = false;
4894 if (has_superclass) {
4895 mirror::Class* super_class = klass->GetSuperClass();
4896 extend_super_iftable = true;
4897 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4898 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4899 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
4900 }
4901 } else {
4902 // No imt in the super class, need to reconstruct from the iftable.
4903 mirror::IfTable* if_table = super_class->GetIfTable();
4904 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4905 const size_t length = super_class->GetIfTableCount();
4906 for (size_t i = 0; i < length; ++i) {
4907 mirror::Class* interface = iftable->GetInterface(i);
4908 const size_t num_virtuals = interface->NumVirtualMethods();
4909 const size_t method_array_count = if_table->GetMethodArrayCount(i);
4910 DCHECK_EQ(num_virtuals, method_array_count);
4911 if (method_array_count == 0) {
4912 continue;
4913 }
4914 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
4915 for (size_t j = 0; j < num_virtuals; ++j) {
4916 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
4917 if (method->IsMiranda()) {
4918 continue;
4919 }
4920 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
4921 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4922 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4923 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4924 out_imt->SetReference(imt_index, method);
4925 } else if (imt_ref != conflict_method) {
4926 out_imt->SetReference(imt_index, conflict_method);
4927 }
4928 }
4929 }
4930 }
4931 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004932 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004933 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004934 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004935 if (num_methods > 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004936 StackHandleScope<2> hs(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004937 const bool is_super = i < super_ifcount;
4938 const bool super_interface = is_super && extend_super_iftable;
4939 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
4940 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
4941 if (super_interface) {
4942 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
4943 DCHECK(if_table != nullptr);
4944 DCHECK(if_table->GetMethodArray(i) != nullptr);
4945 // If we are working on a super interface, try extending the existing method array.
4946 method_array = hs.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
4947 AsObjectArray<mirror::ArtMethod>());
4948 // We are overwriting a super class interface, try to only virtual methods instead of the
4949 // whole vtable.
4950 input_array = hs.NewHandle(klass->GetVirtualMethods());
4951 } else {
4952 method_array = hs.NewHandle(AllocArtMethodArray(self, num_methods));
4953 // A new interface, we need the whole vtable incase a new interface method is implemented
4954 // in the whole superclass.
4955 input_array = vtable;
4956 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004957 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004958 CHECK(self->IsExceptionPending()); // OOME.
4959 return false;
4960 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004961 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004962 if (input_array.Get() == nullptr) {
4963 // If the added virtual methods is empty, do nothing.
4964 DCHECK(super_interface);
4965 continue;
4966 }
Ian Rogers62d6c772013-02-27 08:32:07 -08004967 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004968 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004969 MethodNameAndSignatureComparator interface_name_comparator(interface_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004970 int32_t k;
4971 // For each method listed in the interface's method list, find the
4972 // matching method in our class's method list. We want to favor the
4973 // subclass over the superclass, which just requires walking
4974 // back from the end of the vtable. (This only matters if the
4975 // superclass defines a private method and this class redefines
4976 // it -- otherwise it would use the same vtable slot. In .dex files
4977 // those don't end up in the virtual method table, so it shouldn't
4978 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004979 for (k = input_array->GetLength() - 1; k >= 0; --k) {
4980 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004981 mirror::ArtMethod* vtable_method_for_name_comparison =
4982 vtable_method->GetInterfaceMethodIfProxy();
4983 if (interface_name_comparator.HasSameNameAndSignature(
4984 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004985 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004986 ThrowIllegalAccessError(
4987 klass.Get(),
4988 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004989 PrettyMethod(vtable_method).c_str(),
4990 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004991 return false;
4992 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004993 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004994 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004995 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4996 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4997 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4998 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4999 out_imt->SetReference(imt_index, vtable_method);
5000 } else if (imt_ref != conflict_method) {
5001 // If we are not a conflict and we have the same signature and name as the imt entry,
5002 // it must be that we overwrote a superclass vtable entry.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005003 MethodNameAndSignatureComparator
5004 imt_ref_name_comparator(imt_ref->GetInterfaceMethodIfProxy());
5005 if (imt_ref_name_comparator.HasSameNameAndSignature(
5006 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005007 out_imt->SetReference(imt_index, vtable_method);
5008 } else {
5009 out_imt->SetReference(imt_index, conflict_method);
5010 }
Jeff Hao88474b42013-10-23 16:24:40 -07005011 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005012 break;
5013 }
5014 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005015 if (k < 0 && !super_interface) {
5016 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005017 for (size_t l = 0; l < miranda_list_size; ++l) {
5018 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005019 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005020 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005021 break;
5022 }
5023 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005024 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005025 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005026 miranda_method = interface_method->Clone(self)->AsArtMethod();
5027 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005028 CHECK(self->IsExceptionPending()); // OOME.
5029 return false;
5030 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005031 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005032 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005033 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005034 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005035 }
5036 }
5037 }
5038 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005039 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005040 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005041 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005042 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5043 if (old_method_count == 0) {
5044 virtuals = AllocArtMethodArray(self, new_method_count);
5045 } else {
5046 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5047 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005048 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005049 CHECK(self->IsExceptionPending()); // OOME.
5050 return false;
5051 }
5052 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005053
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005054 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005055 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005056 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005057 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005058 CHECK(self->IsExceptionPending()); // OOME.
5059 return false;
5060 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005061 for (size_t i = 0; i < miranda_list_size; ++i) {
5062 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005063 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005064 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5065 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5066 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005067 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005068 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005069 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005070 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005071 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005072
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005073 if (kIsDebugBuild) {
5074 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
5075 for (int i = 0; i < vtable->GetLength(); ++i) {
5076 CHECK(vtable->GetWithoutChecks(i) != nullptr);
5077 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005078 }
5079
Ian Rogers7b078e82014-09-10 14:44:24 -07005080 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005081 return true;
5082}
5083
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005084bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005085 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005086 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005087}
5088
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005089bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005090 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005091 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005092}
5093
Brian Carlstromdbc05252011-09-09 01:59:59 -07005094struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005095 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5096 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005097 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005098 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005099 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005100 // 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 -07005101 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5102 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005103 if (type1 != type2) {
5104 bool is_primitive1 = type1 != Primitive::kPrimNot;
5105 bool is_primitive2 = type2 != Primitive::kPrimNot;
Fred Shih37f05ef2014-07-16 18:38:08 -07005106 if (type1 != type2) {
5107 if (is_primitive1 && is_primitive2) {
5108 // Larger primitive types go first.
5109 return Primitive::ComponentSize(type1) > Primitive::ComponentSize(type2);
5110 } else {
5111 // Reference always goes first.
5112 return !is_primitive1;
5113 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08005114 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005115 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005116 // same basic group? then sort by string.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005117 return strcmp(field1->GetName(), field2->GetName()) < 0;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005118 }
5119};
5120
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005121bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005122 size_t* class_size) {
5123 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005124 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005125 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005126
Brian Carlstromea46f952013-07-30 01:26:50 -07005127 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005128 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005129
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005130 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005131 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005132 if (is_static) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005133 uint32_t base = sizeof(mirror::Class); // Static fields come after the class.
5134 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
5135 // Static fields come after the embedded tables.
5136 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
Fred Shih37f05ef2014-07-16 18:38:08 -07005137 0, 0, 0, 0, 0);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005138 }
5139 field_offset = MemberOffset(base);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005140 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005141 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005142 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005143 CHECK(super_class->IsResolved())
5144 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005145 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005146 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005147 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005148
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005149 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005150
Brian Carlstromdbc05252011-09-09 01:59:59 -07005151 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005152 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005153 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005154 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005155 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005156 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005157 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005158 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005159 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005160 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005161 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5162 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005163
Fred Shih381e4ca2014-08-25 17:24:27 -07005164 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005165 size_t current_field = 0;
5166 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005167 FieldGaps gaps;
5168
Brian Carlstromdbc05252011-09-09 01:59:59 -07005169 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005170 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005171 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005172 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005173 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005174 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005175 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005176 if (UNLIKELY(!IsAligned<4>(field_offset.Uint32Value()))) {
5177 MemberOffset old_offset = field_offset;
5178 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5179 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5180 }
5181 DCHECK(IsAligned<4>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005182 grouped_and_sorted_fields.pop_front();
5183 num_reference_fields++;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005184 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005185 field->SetOffset(field_offset);
5186 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005187 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005188 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5189 // otherwise we could end up with suboptimal gap fills.
5190 ShuffleForward<8>(num_fields, &current_field, &field_offset,
5191 fields, &grouped_and_sorted_fields, &gaps);
5192 ShuffleForward<4>(num_fields, &current_field, &field_offset,
5193 fields, &grouped_and_sorted_fields, &gaps);
5194 ShuffleForward<2>(num_fields, &current_field, &field_offset,
5195 fields, &grouped_and_sorted_fields, &gaps);
5196 ShuffleForward<1>(num_fields, &current_field, &field_offset,
5197 fields, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005198 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5199 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005200 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005201
Elliott Hughesadb460d2011-10-05 17:02:34 -07005202 // 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 -07005203 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005204 // We know there are no non-reference fields in the Reference classes, and we know
5205 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005206 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005207 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005208 --num_reference_fields;
5209 }
5210
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005211 if (kIsDebugBuild) {
5212 // Make sure that all reference fields appear before
5213 // non-reference fields, and all double-wide fields are aligned.
5214 bool seen_non_ref = false;
5215 for (size_t i = 0; i < num_fields; i++) {
5216 mirror::ArtField* field = fields->Get(i);
Ian Rogerscf7f1912014-10-22 22:06:39 -07005217 if ((false)) { // enable to debug field layout
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005218 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005219 << " class=" << PrettyClass(klass.Get())
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005220 << " field=" << PrettyField(field)
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07005221 << " offset="
5222 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005223 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005224 Primitive::Type type = field->GetTypeAsPrimitiveType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005225 bool is_primitive = type != Primitive::kPrimNot;
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005226 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005227 strcmp("referent", field->GetName()) == 0) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005228 is_primitive = true; // We lied above, so we have to expect a lie here.
5229 }
5230 if (is_primitive) {
5231 if (!seen_non_ref) {
5232 seen_non_ref = true;
Brian Carlstromf3632832014-05-20 15:36:53 -07005233 DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005234 }
5235 } else {
Brian Carlstromf3632832014-05-20 15:36:53 -07005236 DCHECK(!seen_non_ref) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005237 }
5238 }
5239 if (!seen_non_ref) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005240 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005241 }
5242 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005243
5244 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005245 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005246 if (is_static) {
5247 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005248 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005249 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005250 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005251 if (!klass->IsVariableSize()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005252 std::string temp;
5253 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005254 size_t previous_size = klass->GetObjectSize();
5255 if (previous_size != 0) {
5256 // Make sure that we didn't originally have an incorrect size.
Ian Rogers1ff3c982014-08-12 02:30:58 -07005257 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005258 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005259 klass->SetObjectSize(size);
5260 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005261 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005262 return true;
5263}
5264
5265// Set the bitmap of reference offsets, refOffsets, from the ifields
5266// list.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005267void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005268 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005269 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005270 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005271 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005272 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005273 // Compute reference offsets unless our superclass overflowed.
5274 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5275 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
5276 mirror::ObjectArray<mirror::ArtField>* fields = klass->GetIFields();
5277 // All of the fields that contain object references are guaranteed
5278 // to be at the beginning of the fields list.
5279 for (size_t i = 0; i < num_reference_fields; ++i) {
5280 // Note that byte_offset is the offset from the beginning of
5281 // object, not the offset into instance data
5282 mirror::ArtField* field = fields->Get(i);
5283 MemberOffset byte_offset = field->GetOffsetDuringLinking();
5284 uint32_t displaced_bitmap_position =
5285 (byte_offset.Uint32Value() - mirror::kObjectHeaderSize) /
5286 sizeof(mirror::HeapReference<mirror::Object>);
5287 if (displaced_bitmap_position >= 32) {
5288 // Can't encode offset so fall back on slow-path.
5289 reference_offsets = mirror::Class::kClassWalkSuper;
5290 break;
5291 } else {
5292 reference_offsets |= (1 << displaced_bitmap_position);
5293 }
5294 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005295 }
5296 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005297 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005298}
5299
Mathieu Chartier590fee92013-09-13 13:46:47 -07005300mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005301 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005302 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005303 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005304 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005305 return resolved;
5306 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005307 uint32_t utf16_length;
5308 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005309 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005310 dex_cache->SetResolvedString(string_idx, string);
5311 return string;
5312}
5313
Mathieu Chartier590fee92013-09-13 13:46:47 -07005314mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005315 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005316 StackHandleScope<2> hs(Thread::Current());
5317 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5318 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005319 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5320}
5321
5322mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005323 Handle<mirror::DexCache> dex_cache,
5324 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005325 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005326 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005327 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005328 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005329 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005330 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005331 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005332 // TODO: we used to throw here if resolved's class loader was not the
5333 // boot class loader. This was to permit different classes with the
5334 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005335 dex_cache->SetResolvedType(type_idx, resolved);
5336 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005337 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005338 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005339 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005340 StackHandleScope<1> hs(self);
5341 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005342 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005343 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005344 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005345 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005346 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005347 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005348 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005349 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005350 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005351 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005352 return resolved;
5353}
5354
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005355mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005356 Handle<mirror::DexCache> dex_cache,
5357 Handle<mirror::ClassLoader> class_loader,
5358 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005359 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005360 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005361 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005362 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005363 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005364 return resolved;
5365 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005366 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005367 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005368 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005369 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005370 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005371 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005372 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005373 // Scan using method_idx, this saves string compares but will only hit for matching dex
5374 // caches/files.
5375 switch (type) {
5376 case kDirect: // Fall-through.
5377 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005378 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005379 break;
5380 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005381 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005382 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005383 break;
5384 case kSuper: // Fall-through.
5385 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005386 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005387 break;
5388 default:
5389 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005390 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005391 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005392 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005393 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005394 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005395 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005396 switch (type) {
5397 case kDirect: // Fall-through.
5398 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005399 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005400 break;
5401 case kInterface:
5402 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005403 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005404 break;
5405 case kSuper: // Fall-through.
5406 case kVirtual:
5407 resolved = klass->FindVirtualMethod(name, signature);
5408 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005409 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005410 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005411 // If we found a method, check for incompatible class changes.
5412 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005413 // Be a good citizen and update the dex cache to speed subsequent calls.
5414 dex_cache->SetResolvedMethod(method_idx, resolved);
5415 return resolved;
5416 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005417 // If we had a method, it's an incompatible-class-change error.
5418 if (resolved != nullptr) {
5419 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5420 } else {
5421 // We failed to find the method which means either an access error, an incompatible class
5422 // change, or no such method. First try to find the method among direct and virtual methods.
5423 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5424 const Signature signature = dex_file.GetMethodSignature(method_id);
5425 switch (type) {
5426 case kDirect:
5427 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005428 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005429 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5430 // have had a resolved method before, which triggers the "true" branch above.
5431 break;
5432 case kInterface:
5433 case kVirtual:
5434 case kSuper:
5435 resolved = klass->FindDirectMethod(name, signature);
5436 break;
5437 }
5438
5439 // If we found something, check that it can be accessed by the referrer.
5440 if (resolved != nullptr && referrer.Get() != nullptr) {
5441 mirror::Class* methods_class = resolved->GetDeclaringClass();
5442 mirror::Class* referring_class = referrer->GetDeclaringClass();
5443 if (!referring_class->CanAccess(methods_class)) {
5444 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5445 resolved, type);
5446 return nullptr;
5447 } else if (!referring_class->CanAccessMember(methods_class,
5448 resolved->GetAccessFlags())) {
5449 ThrowIllegalAccessErrorMethod(referring_class, resolved);
5450 return nullptr;
5451 }
5452 }
5453
5454 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5455 // methods and throw if we find the method there. If we find nothing, throw a
5456 // NoSuchMethodError.
5457 switch (type) {
5458 case kDirect:
5459 case kStatic:
5460 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005461 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005462 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005463 resolved = klass->FindInterfaceMethod(name, signature);
5464 if (resolved != nullptr) {
5465 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5466 } else {
5467 ThrowNoSuchMethodError(type, klass, name, signature);
5468 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005469 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005470 break;
5471 case kInterface:
5472 if (resolved != nullptr) {
5473 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005474 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005475 resolved = klass->FindVirtualMethod(name, signature);
5476 if (resolved != nullptr) {
5477 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5478 } else {
5479 ThrowNoSuchMethodError(type, klass, name, signature);
5480 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005481 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005482 break;
5483 case kSuper:
Andreas Gampedf733752014-08-25 20:55:01 -07005484 if (resolved != nullptr) {
5485 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5486 } else {
5487 ThrowNoSuchMethodError(type, klass, name, signature);
5488 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005489 break;
5490 case kVirtual:
5491 if (resolved != nullptr) {
5492 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5493 } else {
5494 resolved = klass->FindInterfaceMethod(name, signature);
5495 if (resolved != nullptr) {
5496 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5497 } else {
5498 ThrowNoSuchMethodError(type, klass, name, signature);
5499 }
5500 }
5501 break;
5502 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005503 }
5504 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005505 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005506 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005507}
5508
Mathieu Chartier590fee92013-09-13 13:46:47 -07005509mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005510 Handle<mirror::DexCache> dex_cache,
5511 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005512 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005513 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005514 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005515 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005516 return resolved;
5517 }
5518 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005519 Thread* const self = Thread::Current();
5520 StackHandleScope<1> hs(self);
5521 Handle<mirror::Class> klass(
5522 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005523 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005524 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005525 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005526 }
5527
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005528 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005529 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005530 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005531 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005532 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005533
Andreas Gampe58a5af82014-07-31 16:23:49 -07005534 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005535 const char* name = dex_file.GetFieldName(field_id);
5536 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5537 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005538 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005539 } else {
5540 resolved = klass->FindInstanceField(name, type);
5541 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005542 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005543 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005544 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005545 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005546 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005547 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005548 return resolved;
5549}
5550
Brian Carlstromea46f952013-07-30 01:26:50 -07005551mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005552 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005553 Handle<mirror::DexCache> dex_cache,
5554 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005555 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005556 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005557 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005558 return resolved;
5559 }
5560 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005561 Thread* self = Thread::Current();
5562 StackHandleScope<1> hs(self);
5563 Handle<mirror::Class> klass(
5564 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005565 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005566 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005567 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005568 }
5569
Ian Rogersdfb325e2013-10-30 01:00:44 -07005570 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5571 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005572 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005573 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005574 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005575 dex_cache->SetResolvedField(field_idx, resolved);
5576 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005577 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005578 }
5579 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005580}
5581
Brian Carlstromea46f952013-07-30 01:26:50 -07005582const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005583 uint32_t* length) {
5584 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5585 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005586 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005587 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005588 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005589}
5590
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005591void ClassLinker::DumpAllClasses(int flags) {
5592 if (dex_cache_image_class_lookup_required_) {
5593 MoveImageClassesToClassTable();
5594 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005595 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5596 // 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 -08005597 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005598 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005599 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005600 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
5601 mirror::Class* klass = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07005602 all_classes.push_back(klass);
Ian Rogers5d76c432011-10-31 21:42:49 -07005603 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005604 }
5605
5606 for (size_t i = 0; i < all_classes.size(); ++i) {
5607 all_classes[i]->DumpClass(std::cerr, flags);
5608 }
5609}
5610
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005611static OatFile::OatMethod CreateOatMethod(const void* code, const uint8_t* gc_map,
5612 bool is_portable) {
5613 CHECK_EQ(kUsePortableCompiler, is_portable);
5614 CHECK(code != nullptr);
5615 const uint8_t* base;
5616 uint32_t code_offset, gc_map_offset;
5617 if (gc_map == nullptr) {
5618 base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5619 base -= sizeof(void*); // Move backward so that code_offset != 0.
5620 code_offset = sizeof(void*);
5621 gc_map_offset = 0;
5622 } else {
5623 // TODO: 64bit support.
5624 base = nullptr; // Base of data in oat file, ie 0.
5625 code_offset = PointerToLowMemUInt32(code);
5626 gc_map_offset = PointerToLowMemUInt32(gc_map);
5627 }
5628 return OatFile::OatMethod(base, code_offset, gc_map_offset);
5629}
5630
5631bool ClassLinker::IsPortableResolutionStub(const void* entry_point) const {
5632 return (entry_point == GetPortableResolutionStub()) ||
5633 (portable_resolution_trampoline_ == entry_point);
5634}
5635
5636bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5637 return (entry_point == GetQuickResolutionStub()) ||
5638 (quick_resolution_trampoline_ == entry_point);
5639}
5640
5641bool ClassLinker::IsPortableToInterpreterBridge(const void* entry_point) const {
5642 return (entry_point == GetPortableToInterpreterBridge());
5643 // TODO: portable_to_interpreter_bridge_trampoline_ == entry_point;
5644}
5645
5646bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5647 return (entry_point == GetQuickToInterpreterBridge()) ||
5648 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5649}
5650
5651bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5652 return (entry_point == GetQuickGenericJniStub()) ||
5653 (quick_generic_jni_trampoline_ == entry_point);
5654}
5655
5656const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5657 return GetQuickGenericJniStub();
5658}
5659
5660void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method, const void* method_code,
5661 bool is_portable) const {
5662 OatFile::OatMethod oat_method = CreateOatMethod(method_code, nullptr, is_portable);
5663 oat_method.LinkMethod(method);
5664 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5665 // Create bridges to transition between different kinds of compiled bridge.
5666 if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
5667 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5668 } else {
5669 CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
5670 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
5671 method->SetIsPortableCompiled();
5672 }
5673}
5674
5675void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5676 if (!method->IsNative()) {
5677 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
5678 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
5679 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5680 } else {
5681 const void* quick_method_code = GetQuickGenericJniStub();
5682 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code, nullptr, false);
5683 oat_method.LinkMethod(method);
5684 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5685 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5686 }
5687}
5688
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005689void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005690 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005691 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005692 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005693 MoveImageClassesToClassTable();
5694 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005695 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005696 os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005697}
5698
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005699size_t ClassLinker::NumLoadedClasses() {
5700 if (dex_cache_image_class_lookup_required_) {
5701 MoveImageClassesToClassTable();
5702 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005703 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005704 return class_table_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005705}
5706
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005707pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005708 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005709}
5710
5711pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005712 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005713}
5714
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005715void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005716 DCHECK(!init_done_);
5717
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005718 DCHECK(klass != nullptr);
5719 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005720
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005721 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005722 DCHECK(class_roots != nullptr);
5723 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005724 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005725}
5726
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005727const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5728 static const char* class_roots_descriptors[] = {
5729 "Ljava/lang/Class;",
5730 "Ljava/lang/Object;",
5731 "[Ljava/lang/Class;",
5732 "[Ljava/lang/Object;",
5733 "Ljava/lang/String;",
5734 "Ljava/lang/DexCache;",
5735 "Ljava/lang/ref/Reference;",
5736 "Ljava/lang/reflect/ArtField;",
5737 "Ljava/lang/reflect/ArtMethod;",
5738 "Ljava/lang/reflect/Proxy;",
5739 "[Ljava/lang/String;",
5740 "[Ljava/lang/reflect/ArtField;",
5741 "[Ljava/lang/reflect/ArtMethod;",
5742 "Ljava/lang/ClassLoader;",
5743 "Ljava/lang/Throwable;",
5744 "Ljava/lang/ClassNotFoundException;",
5745 "Ljava/lang/StackTraceElement;",
5746 "Z",
5747 "B",
5748 "C",
5749 "D",
5750 "F",
5751 "I",
5752 "J",
5753 "S",
5754 "V",
5755 "[Z",
5756 "[B",
5757 "[C",
5758 "[D",
5759 "[F",
5760 "[I",
5761 "[J",
5762 "[S",
5763 "[Ljava/lang/StackTraceElement;",
5764 };
5765 COMPILE_ASSERT(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5766 mismatch_between_class_descriptors_and_class_root_enum);
5767
5768 const char* descriptor = class_roots_descriptors[class_root];
5769 CHECK(descriptor != nullptr);
5770 return descriptor;
5771}
5772
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005773} // namespace art