blob: f6717fb006dbc46085cdfb23cb80d1b17268542f [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());
438 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
439
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700440 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
441 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700442 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Alex Light64ad14d2014-08-19 14:23:13 -0700443 if (!runtime->IsCompiler()) {
444 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700445 quick_resolution_trampoline_ = GetQuickResolutionStub();
446 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
447 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700448 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700449
Mathieu Chartier66f19252012-09-18 08:57:04 -0700450 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700451 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800452 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700453 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700454 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700455 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800456 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700457 std::ostringstream os1, os2;
458 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
459 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
460 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
461 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700462 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800463 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700464 CHECK_EQ(java_lang_String.Get(), String_class);
465 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700466 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700467
Ian Rogers23435d02012-09-24 11:23:12 -0700468 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800469 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800470 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700471
Ian Rogers98379392014-02-24 16:53:16 -0800472 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800473 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700474
Ian Rogers98379392014-02-24 16:53:16 -0800475 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700476 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700477
Ian Rogers98379392014-02-24 16:53:16 -0800478 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800479 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700480
Ian Rogers98379392014-02-24 16:53:16 -0800481 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700482 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700483
Ian Rogers98379392014-02-24 16:53:16 -0800484 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800485 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700486
Ian Rogers98379392014-02-24 16:53:16 -0800487 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800488 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700489
Ian Rogers98379392014-02-24 16:53:16 -0800490 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800491 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700492
Ian Rogers98379392014-02-24 16:53:16 -0800493 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700494 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700495
Ian Rogers98379392014-02-24 16:53:16 -0800496 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700497 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700498
Ian Rogers23435d02012-09-24 11:23:12 -0700499 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800500 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700501 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800502 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700503 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700504 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
505 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700506 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700507 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700508 array_iftable->SetInterface(0, java_lang_Cloneable);
509 array_iftable->SetInterface(1, java_io_Serializable);
510 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700511
Ian Rogers23435d02012-09-24 11:23:12 -0700512 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700513 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
514 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
515 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
516 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700517 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700518 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800519 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700520 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700521
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700522 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800523 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700524 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700525
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700526 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800527 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700528 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700529
Brian Carlstromf3632832014-05-20 15:36:53 -0700530 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700531 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700532 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700533
Brian Carlstromea46f952013-07-30 01:26:50 -0700534 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700535 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700536 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700537
Brian Carlstromea46f952013-07-30 01:26:50 -0700538 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700539 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700540 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700541
Ian Rogers23435d02012-09-24 11:23:12 -0700542 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700543
Ian Rogers23435d02012-09-24 11:23:12 -0700544 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800545 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700546 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
547
Brian Carlstrom1f870082011-08-23 16:02:11 -0700548 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700549 // finish initializing Reference class
550 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
551 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
552 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
553 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
554 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700555 mirror::Class* java_lang_ref_FinalizerReference =
556 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700557 java_lang_ref_FinalizerReference->SetAccessFlags(
558 java_lang_ref_FinalizerReference->GetAccessFlags() |
559 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700560 mirror::Class* java_lang_ref_PhantomReference =
561 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700562 java_lang_ref_PhantomReference->SetAccessFlags(
563 java_lang_ref_PhantomReference->GetAccessFlags() |
564 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700565 mirror::Class* java_lang_ref_SoftReference =
566 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700567 java_lang_ref_SoftReference->SetAccessFlags(
568 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700569 mirror::Class* java_lang_ref_WeakReference =
570 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700571 java_lang_ref_WeakReference->SetAccessFlags(
572 java_lang_ref_WeakReference->GetAccessFlags() |
573 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700574
Ian Rogers23435d02012-09-24 11:23:12 -0700575 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800576 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700577 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700578 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
579
jeffhao8cd6dda2012-02-22 10:15:34 -0800580 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700581 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800582 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800583 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700584 SetClassRoot(kJavaLangClassNotFoundException,
585 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800586 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700587 SetClassRoot(kJavaLangStackTraceElementArrayClass,
588 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800589 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700590
Ian Rogers98379392014-02-24 16:53:16 -0800591 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700592
Brian Carlstroma004aa92012-02-08 18:05:09 -0800593 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700594}
595
Ian Rogers98379392014-02-24 16:53:16 -0800596void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800597 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700598
599 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700600 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700601 // as the types of the field can't be resolved prior to the runtime being
602 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800603 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700604 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800605 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800606
Brian Carlstromea46f952013-07-30 01:26:50 -0700607 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700608 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
609 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700610
Brian Carlstromea46f952013-07-30 01:26:50 -0700611 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700612 CHECK_STREQ(queue->GetName(), "queue");
613 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700614
Brian Carlstromea46f952013-07-30 01:26:50 -0700615 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700616 CHECK_STREQ(queueNext->GetName(), "queueNext");
617 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700618
Brian Carlstromea46f952013-07-30 01:26:50 -0700619 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700620 CHECK_STREQ(referent->GetName(), "referent");
621 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700622
Brian Carlstromea46f952013-07-30 01:26:50 -0700623 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700624 CHECK_STREQ(zombie->GetName(), "zombie");
625 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700626
Brian Carlstroma663ea52011-08-19 23:33:41 -0700627 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700628 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700629 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800630 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700631 CHECK(klass != nullptr);
632 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700633 // note SetClassRoot does additional validation.
634 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700635 }
636
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700637 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700638
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700639 // disable the slow paths in FindClass and CreatePrimitiveClass now
640 // that Object, Class, and Object[] are setup
641 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700642
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800643 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700644}
645
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700646void ClassLinker::RunRootClinits() {
647 Thread* self = Thread::Current();
648 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800649 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700650 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700651 StackHandleScope<1> hs(self);
652 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700653 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700654 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700655 }
656 }
657}
658
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700659bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800660 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000661 const char* oat_cache_filename,
662 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700663 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700664 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800665
Ian Rogers1d54e732013-05-02 21:10:01 -0700666 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800667 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700668 if (heap->GetImageSpace() == nullptr) {
669 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
670 // out of space anyway it might not matter.
671 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
672 "without an image.", dex_filename);
673 return false;
674 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700675 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800676
Brian Carlstrom6449c622014-02-10 23:48:36 -0800677 std::string dex_file_option("--dex-file=");
678 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800679
Brian Carlstrom6449c622014-02-10 23:48:36 -0800680 std::string oat_fd_option("--oat-fd=");
681 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800682
Brian Carlstrom6449c622014-02-10 23:48:36 -0800683 std::string oat_location_option("--oat-location=");
684 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800685
Brian Carlstrom6449c622014-02-10 23:48:36 -0800686 std::vector<std::string> argv;
687 argv.push_back(dex2oat);
688 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800689 argv.push_back("-classpath");
690 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800691 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800692
Ian Rogers8afeb852014-04-02 14:55:49 -0700693 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800694
Jeff Hao4a200f52014-04-01 14:58:49 -0700695 if (!Runtime::Current()->IsVerificationEnabled()) {
696 argv.push_back("--compiler-filter=verify-none");
697 }
698
Alex Light6e183f22014-07-18 14:57:04 -0700699 if (Runtime::Current()->MustRelocateIfPossible()) {
700 argv.push_back("--runtime-arg");
701 argv.push_back("-Xrelocate");
702 } else {
703 argv.push_back("--runtime-arg");
704 argv.push_back("-Xnorelocate");
705 }
706
Brian Carlstrom6449c622014-02-10 23:48:36 -0800707 if (!kIsTargetBuild) {
708 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700709 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700710
Brian Carlstrom6449c622014-02-10 23:48:36 -0800711 argv.push_back(boot_image_option);
712 argv.push_back(dex_file_option);
713 argv.push_back(oat_fd_option);
714 argv.push_back(oat_location_option);
715 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800716 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800717 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700718 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800719
720 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700721}
722
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700723const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700724 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800725 if (kIsDebugBuild) {
726 for (size_t i = 0; i < oat_files_.size(); ++i) {
727 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700728 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800729 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700730 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
731 oat_files_.push_back(oat_file);
732 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800733}
734
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700735OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
736 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700737 OatFile* oat_file = space->ReleaseOatFile();
738 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700739 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700740 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700741}
742
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100743const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800744 const char* dex_location = dex_file.GetLocation().c_str();
745 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100746 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800747}
748
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100749const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
750 const char* dex_location,
751 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700752 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100753 for (const OatFile* oat_file : oat_files_) {
754 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700755
756 if (oat_location != nullptr) {
757 if (oat_file->GetLocation() != oat_location) {
758 continue;
759 }
760 }
761
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700762 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800763 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700764 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100765 if (oat_dex_file != nullptr) {
766 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800767 }
768 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100769 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800770}
771
Calin Juravle621962a2014-09-02 15:53:55 +0100772
773// Loads all multi dex files from the given oat file returning true on success.
774//
775// Parameters:
776// oat_file - the oat file to load from
777// dex_location - the dex location used to generate the oat file
778// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
779// generated - whether or not the oat_file existed before or was just (re)generated
780// error_msgs - any error messages will be appended here
781// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
782static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
783 const char* dex_location,
784 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700785 bool generated,
786 std::vector<std::string>* error_msgs,
787 std::vector<const DexFile*>* dex_files) {
788 if (oat_file == nullptr) {
789 return false;
790 }
791
792 size_t old_size = dex_files->size(); // To rollback on error.
793
794 bool success = true;
795 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100796 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700797 const char* next_name = next_name_str.c_str();
798
Calin Juravle621962a2014-09-02 15:53:55 +0100799 uint32_t next_location_checksum;
800 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700801 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100802 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
803 // When i=0 the multidex name should be the same as the location name. We already have the
804 // checksum it so we don't need to recompute it.
805 if (dex_location_checksum == nullptr) {
806 next_location_checksum_pointer = nullptr;
807 } else {
808 next_location_checksum = *dex_location_checksum;
809 }
810 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700811 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100812 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700813 }
814
815 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
816
817 if (oat_dex_file == nullptr) {
818 if (i == 0 && generated) {
819 std::string error_msg;
820 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100821 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700822 oat_file->GetLocation().c_str());
823 error_msgs->push_back(error_msg);
824 }
825 break; // Not found, done.
826 }
827
828 // Checksum test. Test must succeed when generated.
829 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100830 if (next_location_checksum_pointer != nullptr) {
831 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700832 }
833
834 if (success) {
835 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
836 if (dex_file == nullptr) {
837 success = false;
838 error_msgs->push_back(error_msg);
839 } else {
840 dex_files->push_back(dex_file);
841 }
842 }
843
844 // When we generated the file, we expect success, or something is terribly wrong.
845 CHECK_EQ(false, generated && !success)
846 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100847 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700848 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
849 }
850
851 if (dex_files->size() == old_size) {
852 success = false; // We did not even find classes.dex
853 }
854
855 if (success) {
856 return true;
857 } else {
858 // Free all the dex files we have loaded.
859 auto it = dex_files->begin() + old_size;
860 auto it_end = dex_files->end();
861 for (; it != it_end; it++) {
862 delete *it;
863 }
864 dex_files->erase(dex_files->begin() + old_size, it_end);
865
866 return false;
867 }
868}
869
870// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
871// complicates the loading process, as we should not use an iterative loading process, because that
872// would register the oat file and dex files that come before the broken one. Instead, check all
873// multidex ahead of time.
874bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
875 std::vector<std::string>* error_msgs,
876 std::vector<const DexFile*>* dex_files) {
877 // 1) Check whether we have an open oat file.
878 // This requires a dex checksum, use the "primary" one.
879 uint32_t dex_location_checksum;
880 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
881 bool have_checksum = true;
882 std::string checksum_error_msg;
883 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100884 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700885 dex_location_checksum_pointer = nullptr;
886 have_checksum = false;
887 }
888
889 bool needs_registering = false;
890
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100891 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
892 dex_location_checksum_pointer);
893 std::unique_ptr<const OatFile> open_oat_file(
894 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700895
896 // 2) If we do not have an open one, maybe there's one on disk already.
897
898 // In case the oat file is not open, we play a locking game here so
899 // that if two different processes race to load and register or generate
900 // (or worse, one tries to open a partial generated file) we will be okay.
901 // This is actually common with apps that use DexClassLoader to work
902 // around the dex method reference limit and that have a background
903 // service running in a separate process.
904 ScopedFlock scoped_flock;
905
906 if (open_oat_file.get() == nullptr) {
907 if (oat_location != nullptr) {
908 // Can only do this if we have a checksum, else error.
909 if (!have_checksum) {
910 error_msgs->push_back(checksum_error_msg);
911 return false;
912 }
913
914 std::string error_msg;
915
916 // We are loading or creating one in the future. Time to set up the file lock.
917 if (!scoped_flock.Init(oat_location, &error_msg)) {
918 error_msgs->push_back(error_msg);
919 return false;
920 }
921
Alex Lighta59dd802014-07-02 16:28:08 -0700922 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700923 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
924 oat_location, &error_msg));
925
926 if (open_oat_file.get() == nullptr) {
927 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
928 dex_location, oat_location, error_msg.c_str());
929 VLOG(class_linker) << compound_msg;
930 error_msgs->push_back(compound_msg);
931 }
932 } else {
933 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100934 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700935 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
936 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100937 kRuntimeISA, error_msgs,
938 &obsolete_file_cleanup_failed));
939 // There's no point in going forward and eventually try to regenerate the
940 // file if we couldn't remove the obsolete one. Mostly likely we will fail
941 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100942 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
943 if (obsolete_file_cleanup_failed) {
944 return false;
945 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700946 }
947 needs_registering = true;
948 }
949
950 // 3) If we have an oat file, check all contained multidex files for our dex_location.
951 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100952 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
953 dex_location_checksum_pointer,
954 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700955 if (success) {
956 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
957 if (needs_registering) {
958 // We opened the oat file, so we must register it.
959 RegisterOatFile(oat_file);
960 }
Alex Light9dcc4572014-08-14 14:16:26 -0700961 // If the file isn't executable we failed patchoat but did manage to get the dex files.
962 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700963 } else {
964 if (needs_registering) {
965 // We opened it, delete it.
966 open_oat_file.reset();
967 } else {
968 open_oat_file.release(); // Do not delete open oat files.
969 }
970 }
971
972 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
973
974 // Need a checksum, fail else.
975 if (!have_checksum) {
976 error_msgs->push_back(checksum_error_msg);
977 return false;
978 }
979
980 // Look in cache location if no oat_location is given.
981 std::string cache_location;
982 if (oat_location == nullptr) {
983 // Use the dalvik cache.
984 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
985 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
986 oat_location = cache_location.c_str();
987 }
988
Alex Light64ad14d2014-08-19 14:23:13 -0700989 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700990 // Definitely need to lock now.
991 if (!scoped_flock.HasFile()) {
992 std::string error_msg;
993 if (!scoped_flock.Init(oat_location, &error_msg)) {
994 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700995 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -0700996 }
997 }
998
Alex Light64ad14d2014-08-19 14:23:13 -0700999 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001000 // Create the oat file.
1001 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1002 oat_location, error_msgs));
1003 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001004
1005 // Failed, bail.
1006 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001007 std::string error_msg;
1008 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1009 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1010 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001011 return false;
1012 }
1013
1014 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001015 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1016 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001017 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001018 if (success) {
1019 RegisterOatFile(open_oat_file.release());
1020 return true;
1021 } else {
1022 return false;
1023 }
1024}
1025
1026const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1027 uint32_t dex_location_checksum,
1028 const char* oat_location,
1029 std::string* error_msg) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001030 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001031 !Runtime::Current()->IsCompiler(),
1032 error_msg));
1033 if (oat_file.get() == nullptr) {
1034 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1035 error_msg->c_str());
1036 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001037 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001038 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001039 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1040 if (image_space != nullptr) {
1041 const ImageHeader& image_header = image_space->GetImageHeader();
1042 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1043 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1044 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1045 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1046 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1047 actual_image_oat_checksum);
1048 return nullptr;
1049 }
1050
1051 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1052 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1053 if (expected_image_oat_offset != actual_image_oat_offset) {
1054 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1055 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1056 actual_image_oat_offset);
1057 return nullptr;
1058 }
1059 int32_t expected_patch_delta = image_header.GetPatchDelta();
1060 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1061 if (expected_patch_delta != actual_patch_delta) {
1062 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1063 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1064 return nullptr;
1065 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001066 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001067
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001068 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1069 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001070 if (oat_dex_file == nullptr) {
1071 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1072 dex_location);
1073 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001074 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001075 uint32_t expected_dex_checksum = dex_location_checksum;
1076 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1077 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001078 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1079 "found 0x%x", oat_location, expected_dex_checksum,
1080 actual_dex_checksum);
1081 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001082 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001083 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1084 if (dex_file.get() != nullptr) {
1085 return oat_file.release();
1086 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001087 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001088 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001089}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001090
Andreas Gampe833a4852014-05-21 18:46:59 -07001091const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1092 int fd, const char* oat_location,
1093 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001094 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001095 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001096 std::string error_msg;
1097 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001098 CHECK(!error_msg.empty());
1099 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001100 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001101 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001102 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001103 !Runtime::Current()->IsCompiler(),
1104 &error_msg));
1105 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001106 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1107 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001108 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001109 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001110 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001111
1112 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001113}
1114
Alex Light6e183f22014-07-18 14:57:04 -07001115bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1116 const InstructionSet instruction_set) {
1117 Runtime* runtime = Runtime::Current();
1118 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001119 if (image_space == nullptr) {
1120 return false;
1121 }
Alex Light6e183f22014-07-18 14:57:04 -07001122 uint32_t image_oat_checksum = 0;
1123 if (instruction_set == kRuntimeISA) {
1124 const ImageHeader& image_header = image_space->GetImageHeader();
1125 image_oat_checksum = image_header.GetOatChecksum();
1126 } else {
1127 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1128 image_space->GetImageLocation().c_str(), instruction_set));
1129 image_oat_checksum = image_header->GetOatChecksum();
1130 }
1131 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1132}
1133
1134bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1135 const InstructionSet instruction_set,
1136 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001137 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001138 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001139 if (image_space == nullptr) {
1140 *error_msg = "No image space for verification against";
1141 return false;
1142 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001143
1144 // If the requested instruction set is the same as the current runtime,
1145 // we can use the checksums directly. If it isn't, we'll have to read the
1146 // image header from the image for the right instruction set.
1147 uint32_t image_oat_checksum = 0;
1148 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001149 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001150 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001151 const ImageHeader& image_header = image_space->GetImageHeader();
1152 image_oat_checksum = image_header.GetOatChecksum();
1153 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001154 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001155 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001156 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001157 image_space->GetImageLocation().c_str(), instruction_set));
1158 image_oat_checksum = image_header->GetOatChecksum();
1159 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001160 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001161 }
1162 const OatHeader& oat_header = oat_file->GetOatHeader();
Alex Light6e183f22014-07-18 14:57:04 -07001163 bool ret = ((oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum)
1164 && (oat_header.GetImagePatchDelta() == image_patch_delta)
1165 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin));
1166 if (!ret) {
1167 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1168 oat_file->GetLocation().c_str(),
1169 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1170 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1171 oat_file->GetOatHeader().GetImagePatchDelta(),
1172 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1173 }
1174 return ret;
1175}
1176
1177bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1178 const char* dex_location,
1179 uint32_t dex_location_checksum,
1180 const InstructionSet instruction_set,
1181 std::string* error_msg) {
1182 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1183 return false;
1184 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001185
Brian Carlstromf3632832014-05-20 15:36:53 -07001186 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1187 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001188 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001189 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1190 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001191 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1192 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001193 oat_file->GetLocation().c_str(),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001194 oat_dex_file->GetDexFileLocation().c_str(),
1195 oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001196 }
1197 return false;
1198 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001199
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001200 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001201 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001202}
1203
Alex Lighta59dd802014-07-02 16:28:08 -07001204bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1205 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001206 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001207 std::string* error_msg) {
1208 CHECK(oat_file != nullptr);
1209 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001210 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001211 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001212 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1213 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1214 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001215 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001216 if (oat_dex_file == nullptr) {
1217 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001218 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001219 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001220 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001221 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001222 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001223 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001224 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001225 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001226 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001227 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001228 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001229 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001230 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001231 }
Alex Lighta59dd802014-07-02 16:28:08 -07001232 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001233}
1234
Andreas Gampe833a4852014-05-21 18:46:59 -07001235const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001236 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001237 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001238 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001239 std::vector<std::string>* error_msgs,
1240 bool* obsolete_file_cleanup_failed) {
1241 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001242 bool already_opened = false;
1243 std::string dex_location_str(dex_location);
1244 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1245 &already_opened,
1246 obsolete_file_cleanup_failed,
1247 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001248 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001249 if (oat_file.get() == nullptr) {
1250 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1251 dex_location));
1252 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001253 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001254 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1255 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001256 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1257 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001258 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001259 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001260 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001261 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001262 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1263 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1264 "dex location '%s'. Image checksum incorrect.",
1265 oat_file->GetLocation().c_str(), dex_location));
1266 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001267 } else {
1268 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001269 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001270}
1271
Brian Carlstromae826982011-11-09 01:33:42 -08001272const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001273 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001274 for (size_t i = 0; i < oat_files_.size(); i++) {
1275 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001276 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001277 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001278 return oat_file;
1279 }
1280 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001281 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001282}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001283
Alex Lighta59dd802014-07-02 16:28:08 -07001284const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1285 InstructionSet isa,
1286 bool *already_opened,
1287 bool *obsolete_file_cleanup_failed,
1288 std::vector<std::string>* error_msgs) {
1289 // Find out if we've already opened the file
1290 const OatFile* ret = nullptr;
1291 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1292 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1293 if (ret != nullptr) {
1294 *already_opened = true;
1295 return ret;
1296 }
1297
1298 std::string dalvik_cache;
1299 bool have_android_data = false;
1300 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001301 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001302 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001303 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001304 std::string cache_filename;
1305 if (have_dalvik_cache) {
1306 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1307 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1308 if (ret != nullptr) {
1309 *already_opened = true;
1310 return ret;
1311 }
1312 } else {
1313 // If we need to relocate we should just place odex back where it started.
1314 cache_filename = odex_filename;
1315 }
1316
1317 ret = nullptr;
1318
1319 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1320 //
1321 // Now we do the following:
1322 // 1) Try and open the odex version
1323 // 2) If present, checksum-verified & relocated correctly return it
1324 // 3) Close the odex version to free up its address space.
1325 // 4) Try and open the cache version
1326 // 5) If present, checksum-verified & relocated correctly return it
1327 // 6) Close the cache version to free up its address space.
1328 // 7) If we should relocate:
1329 // a) If we have opened and checksum-verified the odex version relocate it to
1330 // 'cache_filename' and return it
1331 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1332 // it. This should not happen often (I think only the run-test's will hit this case).
1333 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1334 // this point.
1335 // 9) Return nullptr
1336
1337 *already_opened = false;
1338 const Runtime* runtime = Runtime::Current();
1339 CHECK(runtime != nullptr);
1340 bool executable = !runtime->IsCompiler();
1341
1342 std::string odex_error_msg;
1343 bool should_patch_system = false;
1344 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001345 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001346 {
1347 // There is a high probability that these both these oat files map similar/the same address
1348 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001349 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001350 executable, &odex_error_msg));
1351 if (odex_oat_file.get() != nullptr && CheckOatFile(odex_oat_file.get(), isa,
1352 &odex_checksum_verified,
1353 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001354 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001355 } else {
1356 if (odex_checksum_verified) {
1357 // We can just relocate
1358 should_patch_system = true;
1359 odex_error_msg = "Image Patches are incorrect";
1360 }
1361 if (odex_oat_file.get() != nullptr) {
1362 have_system_odex = true;
1363 }
Alex Lighta59dd802014-07-02 16:28:08 -07001364 }
1365 }
1366
Alex Lighta59dd802014-07-02 16:28:08 -07001367 std::string cache_error_msg;
1368 bool should_patch_cache = false;
1369 bool cache_checksum_verified = false;
1370 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001371 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001372 executable, &cache_error_msg));
1373 if (cache_oat_file.get() != nullptr && CheckOatFile(cache_oat_file.get(), isa,
1374 &cache_checksum_verified,
1375 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001376 return cache_oat_file.release();
1377 } else if (cache_checksum_verified) {
1378 // We can just relocate
1379 should_patch_cache = true;
1380 cache_error_msg = "Image Patches are incorrect";
1381 }
1382 } else if (have_android_data) {
1383 // dalvik_cache does not exist but android data does. This means we should be able to create
1384 // it, so we should try.
1385 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1386 }
1387
1388 ret = nullptr;
1389 std::string error_msg;
1390 if (runtime->CanRelocate()) {
1391 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001392 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1393 if (space != nullptr) {
1394 const std::string& image_location = space->GetImageLocation();
1395 if (odex_checksum_verified && should_patch_system) {
1396 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1397 } else if (cache_checksum_verified && should_patch_cache) {
1398 CHECK(have_dalvik_cache);
1399 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1400 }
Alex Light84d76052014-08-22 17:49:35 -07001401 } else if (have_system_odex) {
1402 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001403 }
1404 }
1405 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1406 // implicitly: were able to fine where the cached version is but we were unable to use it,
1407 // either as a destination for relocation or to open a file. We should delete it if it is
1408 // there.
1409 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1410 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1411 "searching for dex file %s: %s",
1412 cache_filename.c_str(), dex_location.c_str(),
1413 strerror(errno));
1414 error_msgs->push_back(rm_error_msg);
1415 VLOG(class_linker) << rm_error_msg;
1416 // Let the caller know that we couldn't remove the obsolete file.
1417 // This is a good indication that further writes may fail as well.
1418 *obsolete_file_cleanup_failed = true;
1419 }
1420 }
1421 if (ret == nullptr) {
1422 VLOG(class_linker) << error_msg;
1423 error_msgs->push_back(error_msg);
1424 std::string relocation_msg;
1425 if (runtime->CanRelocate()) {
1426 relocation_msg = StringPrintf(" and relocation failed");
1427 }
1428 if (have_dalvik_cache && cache_checksum_verified) {
1429 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1430 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1431 cache_filename.c_str(), cache_error_msg.c_str(),
1432 relocation_msg.c_str());
1433 } else {
1434 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1435 "dalvik_cache availible)%s.", odex_filename.c_str(),
1436 odex_error_msg.c_str(), relocation_msg.c_str());
1437 }
1438 VLOG(class_linker) << error_msg;
1439 error_msgs->push_back(error_msg);
1440 }
1441 return ret;
1442}
1443
Alex Light9dcc4572014-08-14 14:16:26 -07001444const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1445 InstructionSet isa,
1446 std::string* error_msg) {
1447 // We open it non-executable
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001448 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001449 if (output.get() == nullptr) {
1450 return nullptr;
1451 }
Alex Light84d76052014-08-22 17:49:35 -07001452 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1453 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001454 return output.release();
1455 } else {
1456 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1457 oat_path.c_str());
1458 return nullptr;
1459 }
1460}
1461
Alex Lighta59dd802014-07-02 16:28:08 -07001462const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1463 const std::string& output_oat,
1464 const std::string& image_location,
1465 InstructionSet isa,
1466 std::string* error_msg) {
Alex Light64ad14d2014-08-19 14:23:13 -07001467 if (!Runtime::Current()->GetHeap()->HasImageSpace()) {
1468 // We don't have an image space so there is no point in trying to patchoat.
1469 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1470 << "running without an image. Attempting to use oat file for interpretation.";
1471 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1472 }
Alex Light9dcc4572014-08-14 14:16:26 -07001473 if (!Runtime::Current()->IsDex2OatEnabled()) {
1474 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1475 // input_oat but make sure we only do interpretation on it's dex files.
1476 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1477 << "disabled. Attempting to use oat file for interpretation";
1478 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1479 }
Alex Lighta59dd802014-07-02 16:28:08 -07001480 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
1481 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
1482
1483 std::string isa_arg("--instruction-set=");
1484 isa_arg += GetInstructionSetString(isa);
1485 std::string input_oat_filename_arg("--input-oat-file=");
1486 input_oat_filename_arg += input_oat;
1487 std::string output_oat_filename_arg("--output-oat-file=");
1488 output_oat_filename_arg += output_oat;
1489 std::string patched_image_arg("--patched-image-location=");
1490 patched_image_arg += image_location;
1491
1492 std::vector<std::string> argv;
1493 argv.push_back(patchoat);
1494 argv.push_back(isa_arg);
1495 argv.push_back(input_oat_filename_arg);
1496 argv.push_back(output_oat_filename_arg);
1497 argv.push_back(patched_image_arg);
1498
1499 std::string command_line(Join(argv, ' '));
1500 LOG(INFO) << "Relocate Oat File: " << command_line;
1501 bool success = Exec(argv, error_msg);
1502 if (success) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001503 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001504 !Runtime::Current()->IsCompiler(), error_msg));
1505 bool checksum_verified = false;
1506 if (output.get() != nullptr && CheckOatFile(output.get(), isa, &checksum_verified, error_msg)) {
1507 return output.release();
1508 } else if (output.get() != nullptr) {
1509 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1510 "but output file '%s' failed verifcation: %s",
1511 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1512 } else {
1513 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1514 "but was unable to open output file '%s': %s",
1515 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1516 }
Alex Light9dcc4572014-08-14 14:16:26 -07001517 } else if (!Runtime::Current()->IsCompiler()) {
1518 // patchoat failed which means we probably don't have enough room to place the output oat file,
1519 // instead of failing we should just run the interpreter from the dex files in the input oat.
1520 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1521 << "for interpretation. patchoat failure was: " << *error_msg;
1522 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001523 } else {
1524 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1525 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1526 error_msg->c_str());
1527 }
1528 return nullptr;
1529}
1530
1531int32_t ClassLinker::GetRequiredDelta(const OatFile* oat_file, InstructionSet isa) {
1532 Runtime* runtime = Runtime::Current();
1533 int32_t real_patch_delta;
1534 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001535 CHECK(image_space != nullptr);
Alex Lighta59dd802014-07-02 16:28:08 -07001536 if (isa == Runtime::Current()->GetInstructionSet()) {
1537 const ImageHeader& image_header = image_space->GetImageHeader();
1538 real_patch_delta = image_header.GetPatchDelta();
1539 } else {
1540 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1541 image_space->GetImageLocation().c_str(), isa));
1542 real_patch_delta = image_header->GetPatchDelta();
1543 }
1544 const OatHeader& oat_header = oat_file->GetOatHeader();
1545 return real_patch_delta - oat_header.GetImagePatchDelta();
1546}
1547
1548bool ClassLinker::CheckOatFile(const OatFile* oat_file, InstructionSet isa,
1549 bool* checksum_verified,
1550 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001551 Runtime* runtime = Runtime::Current();
Alex Lighta59dd802014-07-02 16:28:08 -07001552 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001553 if (image_space == nullptr) {
1554 *error_msg = "No image space present";
1555 return false;
1556 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001557 uint32_t real_image_checksum;
1558 void* real_image_oat_offset;
1559 int32_t real_patch_delta;
1560 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001561 const ImageHeader& image_header = image_space->GetImageHeader();
1562 real_image_checksum = image_header.GetOatChecksum();
1563 real_image_oat_offset = image_header.GetOatDataBegin();
1564 real_patch_delta = image_header.GetPatchDelta();
1565 } else {
1566 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1567 image_space->GetImageLocation().c_str(), isa));
1568 real_image_checksum = image_header->GetOatChecksum();
1569 real_image_oat_offset = image_header->GetOatDataBegin();
1570 real_patch_delta = image_header->GetPatchDelta();
1571 }
1572
1573 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001574 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001575
1576 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1577 *checksum_verified = oat_image_checksum == real_image_checksum;
1578 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001579 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1580 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001581 }
1582
1583 void* oat_image_oat_offset =
1584 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1585 bool offset_verified = oat_image_oat_offset == real_image_oat_offset;
1586 if (!offset_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001587 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1588 real_image_oat_offset, oat_image_oat_offset);
Alex Lighta59dd802014-07-02 16:28:08 -07001589 }
1590
1591 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1592 bool patch_delta_verified = oat_patch_delta == real_patch_delta;
1593 if (!patch_delta_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001594 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, received 0x%x)",
1595 real_patch_delta, oat_patch_delta);
Alex Lighta59dd802014-07-02 16:28:08 -07001596 }
1597
1598 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001599 if (!ret) {
1600 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001601 }
1602 return ret;
1603}
1604
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001605const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1606 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001607 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001608 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001609 return oat_file;
1610 }
1611
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001612 return OatFile::Open(oat_location, oat_location, nullptr, !Runtime::Current()->IsCompiler(),
1613 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001614}
1615
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001616static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001617 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001618 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1619
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001620 DCHECK(obj != nullptr);
1621 DCHECK(class_linker != nullptr);
Ian Rogers848871b2013-08-05 10:56:33 -07001622
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001623 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001624 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001625 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001626 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers848871b2013-08-05 10:56:33 -07001627 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001628 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1629 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001630 }
1631 }
1632 }
1633}
1634
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001635void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001636 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001637 CHECK(!init_done_);
1638
Mathieu Chartier590fee92013-09-13 13:46:47 -07001639 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001640 gc::Heap* heap = Runtime::Current()->GetHeap();
1641 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001642 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001643 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001644 OatFile& oat_file = GetImageOatFile(space);
1645 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1646 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001647 const char* image_file_location = oat_file.GetOatHeader().
1648 GetStoreValueByKey(OatHeader::kImageLocationKey);
1649 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001650 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1651 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001652 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1653 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001654 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001655 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001656 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1657 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1658 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001659
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001660 StackHandleScope<1> hs(self);
1661 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1662 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1663 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001664 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001665
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001666 // Special case of setting up the String class early so that we can test arbitrary objects
1667 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001668 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001669
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001670 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001671 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001672 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001673 StackHandleScope<1> hs(self);
1674 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001675 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001676 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1677 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001678 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001679 std::string error_msg;
1680 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001681 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001682 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001683 << " from within oat file " << oat_file.GetLocation()
1684 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001685 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001686
1687 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1688
1689 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001690 }
1691
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001692 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1693 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001694 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001695
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001696 // Set entry point to interpreter if in InterpretOnly mode.
1697 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001698 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001699 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001700 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001701
1702 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001703 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001704 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001705
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001706 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001707 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1708 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001709 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001710 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001711 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001712 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1713 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1714 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1715 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1716 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1717 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1718 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1719 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1720 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1721 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001722
Ian Rogers98379392014-02-24 16:53:16 -08001723 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001724
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001725 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001726}
1727
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001728void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1729 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1730 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001731 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1732 it.second.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001733 }
1734 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1735 for (auto& pair : new_class_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001736 mirror::Class* old_ref = pair.second.Read<kWithoutReadBarrier>();
1737 pair.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1738 mirror::Class* new_ref = pair.second.Read<kWithoutReadBarrier>();
1739 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001740 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1741 // corresponding object. This is slow, but luckily for us, this may only happen with a
1742 // concurrent moving GC.
1743 for (auto it = class_table_.lower_bound(pair.first), end = class_table_.end();
1744 it != end && it->first == pair.first; ++it) {
1745 // If the class stored matches the old class, update it to the new value.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001746 if (old_ref == it->second.Read<kWithoutReadBarrier>()) {
1747 it->second = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001748 }
1749 }
1750 }
1751 }
1752 }
1753 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1754 new_class_roots_.clear();
1755 }
1756 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1757 log_new_class_table_roots_ = true;
1758 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1759 log_new_class_table_roots_ = false;
1760 }
1761 // We deliberately ignore the class roots in the image since we
1762 // handle image roots by using the MS/CMS rescanning of dirty cards.
1763}
1764
Brian Carlstroma663ea52011-08-19 23:33:41 -07001765// Keep in sync with InitCallback. Anything we visit, we need to
1766// reinit references to when reinitializing a ClassLinker from a
1767// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001768void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001769 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001770 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001771 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001772 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001773 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001774 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1775 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001776 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001777 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1778 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001779 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001780 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001781 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001782 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1783 new_dex_cache_roots_.clear();
1784 }
1785 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1786 log_new_dex_caches_roots_ = true;
1787 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1788 log_new_dex_caches_roots_ = false;
1789 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001790 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001791 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001792 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1793 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001794 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001795 if (!find_array_class_cache_[i].IsNull()) {
1796 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001797 }
1798 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001799}
1800
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001801void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1802 if (dex_cache_image_class_lookup_required_) {
1803 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001804 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001805 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001806 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001807 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1808 mirror::Class* c = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07001809 if (!visitor(c, arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001810 return;
1811 }
1812 }
1813}
1814
Ian Rogersdbf3be02014-08-29 15:40:08 -07001815static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001816 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001817 classes->insert(c);
1818 return true;
1819}
1820
Ian Rogersdbf3be02014-08-29 15:40:08 -07001821struct GetClassesVisitorArrayArg {
1822 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1823 int32_t index;
1824 bool success;
1825};
1826
1827static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1828 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1829 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1830 if (arg->index < (*arg->classes)->GetLength()) {
1831 (*arg->classes)->Set(arg->index, c);
1832 arg->index++;
1833 return true;
1834 } else {
1835 arg->success = false;
1836 return false;
1837 }
1838}
1839
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001840void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001841 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1842 // is avoiding duplicates.
1843 if (!kMovingClasses) {
1844 std::set<mirror::Class*> classes;
1845 VisitClasses(GetClassesVisitorSet, &classes);
1846 for (mirror::Class* klass : classes) {
1847 if (!visitor(klass, arg)) {
1848 return;
1849 }
1850 }
1851 } else {
1852 Thread* self = Thread::Current();
1853 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001854 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001855 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1856 GetClassesVisitorArrayArg local_arg;
1857 local_arg.classes = &classes;
1858 local_arg.success = false;
1859 // We size the array assuming classes won't be added to the class table during the visit.
1860 // If this assumption fails we iterate again.
1861 while (!local_arg.success) {
1862 size_t class_table_size;
1863 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001864 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogersdbf3be02014-08-29 15:40:08 -07001865 class_table_size = class_table_.size();
1866 }
1867 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1868 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1869 classes.Assign(
1870 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1871 CHECK(classes.Get() != nullptr); // OOME.
1872 local_arg.index = 0;
1873 local_arg.success = true;
1874 VisitClasses(GetClassesVisitorArray, &local_arg);
1875 }
1876 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1877 // If the class table shrank during creation of the clases array we expect null elements. If
1878 // the class table grew then the loop repeats. If classes are created after the loop has
1879 // finished then we don't visit.
1880 mirror::Class* klass = classes->Get(i);
1881 if (klass != nullptr && !visitor(klass, arg)) {
1882 return;
1883 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001884 }
1885 }
1886}
1887
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001888ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001889 mirror::Class::ResetClass();
1890 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001891 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001892 mirror::ArtField::ResetClass();
1893 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001894 mirror::BooleanArray::ResetArrayClass();
1895 mirror::ByteArray::ResetArrayClass();
1896 mirror::CharArray::ResetArrayClass();
1897 mirror::DoubleArray::ResetArrayClass();
1898 mirror::FloatArray::ResetArrayClass();
1899 mirror::IntArray::ResetArrayClass();
1900 mirror::LongArray::ResetArrayClass();
1901 mirror::ShortArray::ResetArrayClass();
1902 mirror::Throwable::ResetClass();
1903 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001904 STLDeleteElements(&boot_class_path_);
1905 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001906}
1907
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001908mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001909 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001910 StackHandleScope<16> hs(self);
1911 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1912 Handle<mirror::DexCache> dex_cache(
1913 hs.NewHandle(down_cast<mirror::DexCache*>(
1914 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1915 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001916 if (dex_cache.Get() == nullptr) {
1917 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001918 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001919 Handle<mirror::String>
1920 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001921 if (location.Get() == nullptr) {
1922 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001923 }
Ian Rogers700a4022014-05-19 16:49:03 -07001924 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001925 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001926 if (strings.Get() == nullptr) {
1927 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001928 }
Ian Rogers700a4022014-05-19 16:49:03 -07001929 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001930 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001931 if (types.Get() == nullptr) {
1932 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001933 }
Ian Rogers700a4022014-05-19 16:49:03 -07001934 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001935 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001936 if (methods.Get() == nullptr) {
1937 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001938 }
Ian Rogers700a4022014-05-19 16:49:03 -07001939 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001940 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001941 if (fields.Get() == nullptr) {
1942 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001943 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001944 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1945 fields.Get());
1946 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001947}
1948
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001949mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001950 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001951 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001952 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001953 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001954 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001955 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1956 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001957 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001958 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001959 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001960 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001961 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001962}
1963
Ian Rogers6fac4472014-02-25 17:01:10 -08001964mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001965 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001966}
1967
Brian Carlstromea46f952013-07-30 01:26:50 -07001968mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001969 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001970 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001971}
1972
Brian Carlstromea46f952013-07-30 01:26:50 -07001973mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001974 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001975 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001976}
1977
Mathieu Chartier590fee92013-09-13 13:46:47 -07001978mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1979 Thread* self, size_t length) {
1980 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1981 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001982}
1983
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001984mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1985 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001986 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001987
1988 // For temporary classes we must wait for them to be retired.
1989 if (init_done_ && klass->IsTemp()) {
1990 CHECK(!klass->IsResolved());
1991 if (klass->IsErroneous()) {
1992 ThrowEarlierClassFailure(klass);
1993 return nullptr;
1994 }
1995 StackHandleScope<1> hs(self);
1996 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1997 ObjectLock<mirror::Class> lock(self, h_class);
1998 // Loop and wait for the resolving thread to retire this class.
1999 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2000 lock.WaitIgnoringInterrupts();
2001 }
2002 if (h_class->IsErroneous()) {
2003 ThrowEarlierClassFailure(h_class.Get());
2004 return nullptr;
2005 }
2006 CHECK(h_class->IsRetired());
2007 // Get the updated class from class table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002008 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002009 }
2010
Brian Carlstromaded5f72011-10-07 17:15:04 -07002011 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002012 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002013 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002014 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2015 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002016 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002017 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2018 ThrowClassCircularityError(h_class.Get());
2019 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002020 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002021 }
2022 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002023 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002024 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002025 }
2026 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002027
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002028 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002029 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002030 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002031 }
2032 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002033 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002034 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002035 return klass;
2036}
2037
Ian Rogers68b56852014-08-29 20:19:11 -07002038typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2039
2040// Search a collection of DexFiles for a descriptor
2041ClassPathEntry FindInClassPath(const char* descriptor,
2042 const std::vector<const DexFile*>& class_path) {
2043 for (size_t i = 0; i != class_path.size(); ++i) {
2044 const DexFile* dex_file = class_path[i];
2045 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002046 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002047 return ClassPathEntry(dex_file, dex_class_def);
2048 }
2049 }
2050 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002051 return ClassPathEntry(static_cast<const DexFile*>(nullptr),
2052 static_cast<const DexFile::ClassDef*>(nullptr));
Ian Rogers68b56852014-08-29 20:19:11 -07002053}
2054
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002055mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2056 Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002057 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002058 if (class_loader->GetClass() !=
2059 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2060 class_loader->GetParent()->GetClass() !=
2061 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2062 return nullptr;
2063 }
2064 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2065 // Check if this would be found in the parent boot class loader.
2066 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002067 mirror::Class* klass = LookupClass(self, descriptor, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002068 if (klass != nullptr) {
2069 return EnsureResolved(self, descriptor, klass);
2070 }
Ian Rogers7b078e82014-09-10 14:44:24 -07002071 klass = DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002072 *pair.second);
2073 if (klass != nullptr) {
2074 return klass;
2075 }
2076 CHECK(self->IsExceptionPending()) << descriptor;
2077 self->ClearException();
2078 } else {
2079 // RegisterDexFile may allocate dex caches (and cause thread suspension).
2080 StackHandleScope<3> hs(self);
2081 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2082 // We need to get the DexPathList and loop through it.
2083 Handle<mirror::ArtField> cookie_field =
2084 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2085 Handle<mirror::ArtField> dex_file_field =
2086 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002087 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002088 mirror::Object* dex_path_list =
2089 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2090 GetObject(class_loader.Get());
2091 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2092 cookie_field.Get() != nullptr) {
2093 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2094 mirror::Object* dex_elements_obj =
2095 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2096 GetObject(dex_path_list);
2097 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2098 // at the mCookie which is a DexFile vector.
2099 if (dex_elements_obj != nullptr) {
2100 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2101 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2102 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2103 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2104 if (element == nullptr) {
2105 // Should never happen, fall back to java code to throw a NPE.
2106 break;
2107 }
2108 mirror::Object* dex_file = dex_file_field->GetObject(element);
2109 if (dex_file != nullptr) {
2110 const uint64_t cookie = cookie_field->GetLong(dex_file);
2111 auto* dex_files =
2112 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2113 if (dex_files == nullptr) {
2114 // This should never happen so log a warning.
2115 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2116 break;
2117 }
2118 for (const DexFile* dex_file : *dex_files) {
2119 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
2120 if (dex_class_def != nullptr) {
2121 RegisterDexFile(*dex_file);
2122 mirror::Class* klass =
Ian Rogers7b078e82014-09-10 14:44:24 -07002123 DefineClass(self, descriptor, class_loader, *dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002124 if (klass == nullptr) {
2125 CHECK(self->IsExceptionPending()) << descriptor;
2126 self->ClearException();
2127 return nullptr;
2128 }
2129 return klass;
2130 }
2131 }
2132 }
2133 }
2134 }
2135 }
2136 }
2137 return nullptr;
2138}
2139
Ian Rogers98379392014-02-24 16:53:16 -08002140mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002141 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002142 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002143 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002144 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002145 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002146 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2147 // for primitive classes that aren't backed by dex files.
2148 return FindPrimitiveClass(descriptor[0]);
2149 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002150 // Find the class in the loaded classes table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002151 mirror::Class* klass = LookupClass(self, descriptor, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002152 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002153 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002154 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002155 // Class is not yet loaded.
2156 if (descriptor[0] == '[') {
Ian Rogers98379392014-02-24 16:53:16 -08002157 return CreateArrayClass(self, descriptor, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002158 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002159 // The boot class loader, search the boot class path.
Ian Rogers68b56852014-08-29 20:19:11 -07002160 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2161 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002162 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2163 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002164 } else {
2165 // The boot class loader is searched ahead of the application class loader, failures are
2166 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2167 // trigger the chaining with a proper stack trace.
2168 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2169 self->SetException(ThrowLocation(), pre_allocated);
2170 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002171 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002172 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002173 // First try with the bootstrap class loader.
2174 if (class_loader.Get() != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002175 klass = LookupClass(self, descriptor, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002176 if (klass != nullptr) {
2177 return EnsureResolved(self, descriptor, klass);
2178 }
2179 }
Ian Rogers63557452014-06-04 16:57:15 -07002180 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2181 // a NoClassDefFoundError being allocated.
Ian Rogers68b56852014-08-29 20:19:11 -07002182 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2183 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002184 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2185 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002186 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002187 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002188 const std::vector<const DexFile*>* class_path;
2189 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002190 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002191 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002192 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002193 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2194 }
Ian Rogers68b56852014-08-29 20:19:11 -07002195 pair = FindInClassPath(descriptor, *class_path);
2196 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002197 return DefineClass(self, descriptor, class_loader, *pair.first, *pair.second);
2198 } else {
2199 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2200 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2201 self->SetException(ThrowLocation(), pre_allocated);
2202 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002203 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002204 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002205 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002206 mirror::Class* klass = FindClassInPathClassLoader(soa, self, descriptor, class_loader);
2207 if (klass != nullptr) {
2208 return klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002209 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002210 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002211 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002212 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002213 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002214 {
2215 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002216 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2217 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002218 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002219 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002220 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002221 }
Ian Rogers68b56852014-08-29 20:19:11 -07002222 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002223 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2224 WellKnownClasses::java_lang_ClassLoader_loadClass,
2225 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002226 }
Ian Rogers98379392014-02-24 16:53:16 -08002227 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002228 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002229 return nullptr;
2230 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002231 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002232 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002233 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002234 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002235 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002236 // success, return mirror::Class*
2237 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002238 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002239 }
Ian Rogers07140832014-09-30 15:43:59 -07002240 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002241}
2242
Ian Rogers7b078e82014-09-10 14:44:24 -07002243mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002244 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002245 const DexFile& dex_file,
2246 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002247 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002248 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002249 bool should_allocate = false;
2250
Brian Carlstromaded5f72011-10-07 17:15:04 -07002251 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002252 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002253 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002254 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002255 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002256 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002257 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002258 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002259 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002260 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2261 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002262 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002263 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002264 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002265 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002266 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002267 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002268 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002269 should_allocate = true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002270 }
2271 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002272 should_allocate = true;
2273 }
2274
2275 if (should_allocate) {
2276 // Allocate a class with the status of not ready.
2277 // Interface object should get the right size here. Regular class will
2278 // figure out the right size later and be replaced with one of the right
2279 // size when the class becomes resolved.
2280 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002281 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002282 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002283 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002284 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002285 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002286 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002287 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002288 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002289 if (self->IsExceptionPending()) {
2290 // An exception occured during load, set status to erroneous while holding klass' lock in case
2291 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002292 if (!klass->IsErroneous()) {
2293 klass->SetStatus(mirror::Class::kStatusError, self);
2294 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002295 return nullptr;
2296 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002297 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002298
Mathieu Chartier590fee92013-09-13 13:46:47 -07002299 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002300 mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor));
Ian Rogersc114b5f2014-07-21 08:55:01 -07002301 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002302 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2303 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002304 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002305 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002306
Brian Carlstromaded5f72011-10-07 17:15:04 -07002307 // Finish loading (if necessary) by finding parents
2308 CHECK(!klass->IsLoaded());
2309 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2310 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002311 if (!klass->IsErroneous()) {
2312 klass->SetStatus(mirror::Class::kStatusError, self);
2313 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002314 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002315 }
2316 CHECK(klass->IsLoaded());
2317 // Link the class (if necessary)
2318 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002319 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002320 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002321
2322 mirror::Class* new_class = nullptr;
2323 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002324 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002325 if (!klass->IsErroneous()) {
2326 klass->SetStatus(mirror::Class::kStatusError, self);
2327 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002328 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002329 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002330 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002331 CHECK(new_class != nullptr) << descriptor;
2332 CHECK(new_class->IsResolved()) << descriptor;
2333
2334 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002335
2336 /*
2337 * We send CLASS_PREPARE events to the debugger from here. The
2338 * definition of "preparation" is creating the static fields for a
2339 * class and initializing them to the standard default values, but not
2340 * executing any code (that comes later, during "initialization").
2341 *
2342 * We did the static preparation in LinkClass.
2343 *
2344 * The class has been prepared and resolved but possibly not yet verified
2345 * at this point.
2346 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002347 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002348
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002349 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002350}
2351
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002352uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2353 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002354 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002355 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002356 size_t num_8 = 0;
2357 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002358 size_t num_32 = 0;
2359 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002360 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002361 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2362 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002363 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002364 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002365 switch (c) {
2366 case 'L':
2367 case '[':
2368 num_ref++;
2369 break;
2370 case 'J':
2371 case 'D':
2372 num_64++;
2373 break;
2374 case 'I':
2375 case 'F':
2376 num_32++;
2377 break;
2378 case 'S':
2379 case 'C':
2380 num_16++;
2381 break;
2382 case 'B':
2383 case 'Z':
2384 num_8++;
2385 break;
2386 default:
2387 LOG(FATAL) << "Unknown descriptor: " << c;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002388 }
2389 }
2390 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002391 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002392}
2393
Ian Rogers97b52f82014-08-14 11:34:07 -07002394OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2395 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002396 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002397 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2398 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002399 *found = false;
2400 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002401 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002402 *found = true;
2403 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002404}
2405
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002406static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2407 uint32_t method_idx) {
2408 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002409 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002410 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002411 ClassDataItemIterator it(dex_file, class_data);
2412 // Skip fields
2413 while (it.HasNextStaticField()) {
2414 it.Next();
2415 }
2416 while (it.HasNextInstanceField()) {
2417 it.Next();
2418 }
2419 // Process methods
2420 size_t class_def_method_index = 0;
2421 while (it.HasNextDirectMethod()) {
2422 if (it.GetMemberIndex() == method_idx) {
2423 return class_def_method_index;
2424 }
2425 class_def_method_index++;
2426 it.Next();
2427 }
2428 while (it.HasNextVirtualMethod()) {
2429 if (it.GetMemberIndex() == method_idx) {
2430 return class_def_method_index;
2431 }
2432 class_def_method_index++;
2433 it.Next();
2434 }
2435 DCHECK(!it.HasNext());
2436 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2437 return 0;
2438}
2439
Ian Rogers97b52f82014-08-14 11:34:07 -07002440const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002441 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002442 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002443 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002444 size_t oat_method_index;
2445 if (method->IsStatic() || method->IsDirect()) {
2446 // Simple case where the oat method index was stashed at load time.
2447 oat_method_index = method->GetMethodIndex();
2448 } else {
2449 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2450 // by search for its position in the declared virtual methods.
2451 oat_method_index = declaring_class->NumDirectMethods();
2452 size_t end = declaring_class->NumVirtualMethods();
2453 bool found = false;
2454 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002455 // Check method index instead of identity in case of duplicate method definitions.
2456 if (method->GetDexMethodIndex() ==
2457 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08002458 found = true;
2459 break;
2460 }
Ian Rogersf320b632012-03-13 18:47:47 -07002461 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002462 }
2463 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2464 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002465 DCHECK_EQ(oat_method_index,
2466 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002467 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002468 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002469 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2470 declaring_class->GetDexClassDefIndex(),
2471 found);
2472 if (!found) {
2473 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002474 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002475 *found = true;
2476 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002477}
2478
2479// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002480const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002481 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002482 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002483 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002484 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002485 bool found;
2486 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002487 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002488 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002489 result = oat_method.GetQuickCode();
2490 }
2491
Ian Rogersef7d42f2014-01-06 12:55:46 -08002492 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002493 if (method->IsNative()) {
2494 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002495 result = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002496 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002497 // No code? Do we expect portable code?
2498 result = GetQuickToPortableBridge();
2499 } else {
2500 // No code? You must mean to go into the interpreter.
2501 result = GetQuickToInterpreterBridge();
2502 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002503 }
2504 return result;
TDYa12785321912012-04-01 15:24:56 -07002505}
2506
Ian Rogersef7d42f2014-01-06 12:55:46 -08002507const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2508 bool* have_portable_code) {
2509 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2510 *have_portable_code = false;
2511 if (method->IsProxyMethod()) {
2512 return GetPortableProxyInvokeHandler();
2513 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002514 bool found;
2515 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002516 const void* result = nullptr;
2517 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002518 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002519 result = oat_method.GetPortableCode();
2520 quick_code = oat_method.GetQuickCode();
2521 }
2522
Ian Rogersef7d42f2014-01-06 12:55:46 -08002523 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002524 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002525 // No code? You must mean to go into the interpreter.
2526 result = GetPortableToInterpreterBridge();
2527 } else {
2528 // No code? But there's quick code, so use a bridge.
2529 result = GetPortableToQuickBridge();
2530 }
2531 } else {
2532 *have_portable_code = true;
2533 }
2534 return result;
2535}
2536
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002537const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2538 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2539 return nullptr;
2540 }
2541 bool found;
2542 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2543 return found ? oat_method.GetQuickCode() : nullptr;
2544}
2545
2546const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2547 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2548 return nullptr;
2549 }
2550 bool found;
2551 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2552 return found ? oat_method.GetPortableCode() : nullptr;
2553}
2554
Ian Rogersef7d42f2014-01-06 12:55:46 -08002555const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2556 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002557 bool found;
2558 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2559 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002560 return nullptr;
2561 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002562 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002563 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002564}
2565
2566const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2567 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002568 bool found;
2569 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2570 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002571 return nullptr;
2572 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002573 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002574 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002575}
2576
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002577// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002578static bool NeedsInterpreter(
2579 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2580 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002581 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002582 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002583 // May return true for native code, in the case of generic JNI
2584 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002585 return true;
2586 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002587#ifdef ART_SEA_IR_MODE
2588 ScopedObjectAccess soa(Thread::Current());
2589 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2590 LOG(INFO) << "Found " << PrettyMethod(method);
2591 return false;
2592 }
2593#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002594 // If interpreter mode is enabled, every method (except native and proxy) must
2595 // be run with interpreter.
2596 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2597 !method->IsNative() && !method->IsProxyMethod();
2598}
2599
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002600void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002601 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002602 if (klass->NumDirectMethods() == 0) {
2603 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002604 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002605 Runtime* runtime = Runtime::Current();
2606 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002607 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2608 return; // OAT file unavailable.
2609 }
Ian Rogers19846512012-02-24 11:42:47 -08002610 }
Alex Light64ad14d2014-08-19 14:23:13 -07002611
Mathieu Chartierf8322842014-05-16 10:59:25 -07002612 const DexFile& dex_file = klass->GetDexFile();
2613 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002614 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002615 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002616 // There should always be class data if there were direct methods.
2617 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002618 ClassDataItemIterator it(dex_file, class_data);
2619 // Skip fields
2620 while (it.HasNextStaticField()) {
2621 it.Next();
2622 }
2623 while (it.HasNextInstanceField()) {
2624 it.Next();
2625 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002626 bool has_oat_class;
2627 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2628 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002629 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002630 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002631 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002632 if (!method->IsStatic()) {
2633 // Only update static methods.
2634 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002635 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002636 const void* portable_code = nullptr;
2637 const void* quick_code = nullptr;
2638 if (has_oat_class) {
2639 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2640 portable_code = oat_method.GetPortableCode();
2641 quick_code = oat_method.GetQuickCode();
2642 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002643 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2644 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002645 if (enter_interpreter) {
2646 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002647 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002648 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002649 quick_code = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002650 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002651 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002652 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002653 quick_code = GetQuickToInterpreterBridge();
2654 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002655 } else {
2656 if (portable_code == nullptr) {
2657 portable_code = GetPortableToQuickBridge();
2658 } else {
2659 have_portable_code = true;
2660 }
2661 if (quick_code == nullptr) {
2662 quick_code = GetQuickToPortableBridge();
2663 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002664 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002665 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2666 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002667 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002668 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002669}
2670
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002671void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002672 const OatFile::OatClass* oat_class,
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002673 const DexFile& dex_file, uint32_t dex_method_index,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002674 uint32_t method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002675 Runtime* runtime = Runtime::Current();
2676 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002677 // The following code only applies to a non-compiler runtime.
2678 return;
2679 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002680 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002681 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2682 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002683 if (oat_class != nullptr) {
2684 // Every kind of method should at least get an invoke stub from the oat_method.
2685 // non-abstract methods also get their code pointers.
2686 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
2687 oat_method.LinkMethod(method.Get());
2688 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002689
Jeff Hao16743632013-05-08 10:59:04 -07002690 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002691 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002692 method->GetEntryPointFromQuickCompiledCode(),
2693 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002694 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002695 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002696 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002697 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002698 }
2699
Brian Carlstrom92827a52011-10-10 15:50:01 -07002700 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002701 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2702 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002703 return;
2704 }
Ian Rogers19846512012-02-24 11:42:47 -08002705
Ian Rogersef7d42f2014-01-06 12:55:46 -08002706 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002707 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002708 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002709 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2710 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002711 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2712 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002713 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002714 if (!method->IsNative()) {
2715 // Set entry point from compiled code if there's no code or in interpreter only mode.
2716 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2717 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2718 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002719 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002720 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2721 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002722 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2723 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2724 have_portable_code = true;
2725 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2726 } else {
2727 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2728 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002729 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002730
Ian Rogers62d6c772013-02-27 08:32:07 -08002731 if (method->IsNative()) {
2732 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002733 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002734
2735 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002736 // We have a native method here without code. Then it should have either the generic JNI
2737 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2738 // TODO: this doesn't handle all the cases where trampolines may be installed.
2739 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2740 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002741 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002742 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002743
Ian Rogers62d6c772013-02-27 08:32:07 -08002744 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002745 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002746 method->GetEntryPointFromQuickCompiledCode(),
2747 method->GetEntryPointFromPortableCompiledCode(),
2748 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002749}
2750
Fred Shih37f05ef2014-07-16 18:38:08 -07002751
Fred Shih37f05ef2014-07-16 18:38:08 -07002752
Ian Rogers7b078e82014-09-10 14:44:24 -07002753void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002754 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002755 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002756 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002757 CHECK(klass.Get() != nullptr);
2758 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002759 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002760 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002761 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002762
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002763 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002764 if (kUseBakerOrBrooksReadBarrier) {
2765 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002766 }
Andreas Gampe51829322014-08-25 15:05:04 -07002767 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002768 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002769 klass->SetAccessFlags(access_flags);
2770 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002771 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002772 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002773
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002774 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002775 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002776
Ian Rogers13735952014-10-08 12:43:28 -07002777 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002778 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002779 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002780 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002781
Ian Rogers97b52f82014-08-14 11:34:07 -07002782
2783 bool has_oat_class = false;
2784 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2785 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2786 &has_oat_class);
2787 if (has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002788 LoadClassMembers(self, dex_file, class_data, klass, class_loader, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002789 }
2790 }
2791 if (!has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002792 LoadClassMembers(self, dex_file, class_data, klass, class_loader, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002793 }
2794}
2795
Ian Rogers7b078e82014-09-10 14:44:24 -07002796void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002797 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002798 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002799 mirror::ClassLoader* class_loader,
2800 const OatFile::OatClass* oat_class) {
2801 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002802 ClassDataItemIterator it(dex_file, class_data);
2803 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002804 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002805 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002806 CHECK(self->IsExceptionPending()); // OOME.
2807 return;
2808 }
2809 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002810 }
2811 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002812 mirror::ObjectArray<mirror::ArtField>* fields =
2813 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002814 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002815 CHECK(self->IsExceptionPending()); // OOME.
2816 return;
2817 }
2818 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002819 }
2820 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002821 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002822 StackHandleScope<1> hs(self);
2823 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002824 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002825 CHECK(self->IsExceptionPending()); // OOME.
2826 return;
2827 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002828 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002829 LoadField(dex_file, it, klass, sfield);
2830 }
2831 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002832 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002833 StackHandleScope<1> hs(self);
2834 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002835 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002836 CHECK(self->IsExceptionPending()); // OOME.
2837 return;
2838 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002839 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002840 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002841 }
2842
Ian Rogers0571d352011-11-03 19:51:38 -07002843 // Load methods.
2844 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002845 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002846 mirror::ObjectArray<mirror::ArtMethod>* directs =
2847 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002848 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002849 CHECK(self->IsExceptionPending()); // OOME.
2850 return;
2851 }
2852 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002853 }
Ian Rogers0571d352011-11-03 19:51:38 -07002854 if (it.NumVirtualMethods() != 0) {
2855 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002856 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2857 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002858 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002859 CHECK(self->IsExceptionPending()); // OOME.
2860 return;
2861 }
2862 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002863 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002864 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002865 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2866 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002867 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002868 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002869 StackHandleScope<1> hs(self);
2870 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002871 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002872 CHECK(self->IsExceptionPending()); // OOME.
2873 return;
2874 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002875 klass->SetDirectMethod(i, method.Get());
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002876 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002877 uint32_t it_method_index = it.GetMemberIndex();
2878 if (last_dex_method_index == it_method_index) {
2879 // duplicate case
2880 method->SetMethodIndex(last_class_def_method_index);
2881 } else {
2882 method->SetMethodIndex(class_def_method_index);
2883 last_dex_method_index = it_method_index;
2884 last_class_def_method_index = class_def_method_index;
2885 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002886 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002887 }
2888 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002889 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002890 StackHandleScope<1> hs(self);
2891 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002892 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002893 CHECK(self->IsExceptionPending()); // OOME.
2894 return;
2895 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002896 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002897 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002898 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002899 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002900 }
2901 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002902}
2903
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002904void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002905 Handle<mirror::Class> klass,
2906 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002907 uint32_t field_idx = it.GetMemberIndex();
2908 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002909 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002910 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002911}
2912
Brian Carlstromea46f952013-07-30 01:26:50 -07002913mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002914 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002915 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002916 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002917 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002918 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002919
Brian Carlstromea46f952013-07-30 01:26:50 -07002920 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002921 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002922 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002923 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002924 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002925 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002926
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002927 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002928 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002929 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002930 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002931
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002932 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002933 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002934 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002935
Andreas Gampe51829322014-08-25 15:05:04 -07002936 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002937
Ian Rogersdfb325e2013-10-30 01:00:44 -07002938 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002939 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002940 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2941 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002942 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002943 klass->SetFinalizable();
2944 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002945 std::string temp;
2946 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002947 // The Enum class declares a "final" finalize() method to prevent subclasses from
2948 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2949 // subclasses, so we exclude it here.
2950 // We also want to avoid setting the flag on Object, where we know that finalize() is
2951 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002952 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2953 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002954 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002955 }
2956 }
2957 }
2958 } else if (method_name[0] == '<') {
2959 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002960 bool is_init = (strcmp("<init>", method_name) == 0);
2961 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002962 if (UNLIKELY(!is_init && !is_clinit)) {
2963 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2964 } else {
2965 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2966 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002967 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002968 access_flags |= kAccConstructor;
2969 }
2970 }
2971 }
2972 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002973
Mathieu Chartier66f19252012-09-18 08:57:04 -07002974 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002975}
2976
Ian Rogers7b078e82014-09-10 14:44:24 -07002977void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002978 StackHandleScope<1> hs(self);
2979 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002980 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2981 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002982 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002983}
2984
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002985void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002986 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002987 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002988 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002989 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002990}
2991
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002992bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002993 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002994 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002995 mirror::DexCache* dex_cache = GetDexCache(i);
2996 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002997 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002998 }
2999 }
3000 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07003001}
3002
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003003bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003004 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07003005 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003006}
3007
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003008void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003009 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003010 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003011 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003012 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3013 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003014 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003015 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003016 if (log_new_dex_caches_roots_) {
3017 // TODO: This is not safe if we can remove dex caches.
3018 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3019 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003020}
3021
Brian Carlstromaded5f72011-10-07 17:15:04 -07003022void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003023 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003024 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003025 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003026 if (IsDexFileRegisteredLocked(dex_file)) {
3027 return;
3028 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003029 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003030 // Don't alloc while holding the lock, since allocation may need to
3031 // suspend all threads and another thread may need the dex_lock_ to
3032 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003033 StackHandleScope<1> hs(self);
3034 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003035 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3036 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003037 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003038 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003039 if (IsDexFileRegisteredLocked(dex_file)) {
3040 return;
3041 }
3042 RegisterDexFileLocked(dex_file, dex_cache);
3043 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003044}
3045
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003046void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003047 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003048 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003049 RegisterDexFileLocked(dex_file, dex_cache);
3050}
3051
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003052mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003053 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003054 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003055 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003056 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003057 if (dex_cache->GetDexFile() == &dex_file) {
3058 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003059 }
3060 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003061 // Search matching by location name.
3062 std::string location(dex_file.GetLocation());
3063 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003064 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003065 if (dex_cache->GetDexFile()->GetLocation() == location) {
3066 return dex_cache;
3067 }
3068 }
3069 // Failure, dump diagnostic and abort.
3070 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003071 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003072 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3073 }
3074 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003075 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003076}
3077
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003078void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003079 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003080 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003081 mirror::DexCache* dex_cache = GetDexCache(i);
3082 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003083 }
3084}
3085
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003086mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003087 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003088 if (UNLIKELY(klass == nullptr)) {
3089 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003090 }
3091 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003092}
3093
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003094mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3095 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003096 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003097 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003098 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003099 StackHandleScope<1> hs(self);
3100 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003101 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003102 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003103 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003104 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3105 const char* descriptor = Primitive::Descriptor(type);
3106 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003107 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003108 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003109}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003110
Brian Carlstrombe977852011-07-19 14:54:54 -07003111// Create an array class (i.e. the class object for the array, not the
3112// array itself). "descriptor" looks like "[C" or "[[[[B" or
3113// "[Ljava/lang/String;".
3114//
3115// If "descriptor" refers to an array of primitives, look up the
3116// primitive type's internally-generated class object.
3117//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003118// "class_loader" is the class loader of the class that's referring to
3119// us. It's used to ensure that we're looking for the element type in
3120// the right context. It does NOT become the class loader for the
3121// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003122//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003123// Returns nullptr with an exception raised on failure.
Ian Rogers98379392014-02-24 16:53:16 -08003124mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003125 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003126 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003127 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003128 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003129 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3130 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003131 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003132 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003133 // We need to accept erroneous classes as component types.
Ian Rogers7b078e82014-09-10 14:44:24 -07003134 component_type.Assign(LookupClass(self, descriptor + 1, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003135 if (component_type.Get() == nullptr) {
3136 DCHECK(self->IsExceptionPending());
3137 return nullptr;
3138 } else {
3139 self->ClearException();
3140 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003141 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003142 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3143 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3144 return nullptr;
3145 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003146 // See if the component type is already loaded. Array classes are
3147 // always associated with the class loader of their underlying
3148 // element type -- an array of Strings goes with the loader for
3149 // java/lang/String -- so we need to look for it there. (The
3150 // caller should have checked for the existence of the class
3151 // before calling here, but they did so with *their* class loader,
3152 // not the component type's loader.)
3153 //
3154 // If we find it, the caller adds "loader" to the class' initiating
3155 // loader list, which should prevent us from going through this again.
3156 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003157 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003158 // are the same, because our caller (FindClass) just did the
3159 // lookup. (Even if we get this wrong we still have correct behavior,
3160 // because we effectively do this lookup again when we add the new
3161 // class to the hash table --- necessary because of possible races with
3162 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003163 if (class_loader.Get() != component_type->GetClassLoader()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003164 mirror::Class* new_class = LookupClass(self, descriptor, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003165 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003166 return new_class;
3167 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003168 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003169
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003170 // Fill out the fields in the Class.
3171 //
3172 // It is possible to execute some methods against arrays, because
3173 // all arrays are subclasses of java_lang_Object_, so we need to set
3174 // up a vtable. We can just point at the one in java_lang_Object_.
3175 //
3176 // Array classes are simple enough that we don't need to do a full
3177 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003178 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003179 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003180 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003181 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003182 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003183 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003184 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003185 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003186 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003187 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003188 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003189 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003190 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003191 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003192 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003193 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003194 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003195 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003196 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003197 }
3198 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003199 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003200 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003201 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003202 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003203 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003204 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003205 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003206 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003207 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003208 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003209 new_class->SetSuperClass(java_lang_Object);
3210 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003211 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003212 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003213 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
3214 new_class->PopulateEmbeddedImtAndVTable();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003215 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003216 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003217 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003218
3219
3220 // All arrays have java/lang/Cloneable and java/io/Serializable as
3221 // interfaces. We need to set that up here, so that stuff like
3222 // "instanceof" works right.
3223 //
3224 // Note: The GC could run during the call to FindSystemClass,
3225 // so we need to make sure the class object is GC-valid while we're in
3226 // there. Do this by clearing the interface list so the GC will just
3227 // think that the entries are null.
3228
3229
3230 // Use the single, global copies of "interfaces" and "iftable"
3231 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003232 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003233 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003234 CHECK(array_iftable != nullptr);
3235 new_class->SetIfTable(array_iftable);
3236 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003237
Elliott Hughes00626c22013-06-14 15:04:14 -07003238 // Inherit access flags from the component type.
3239 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3240 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3241 access_flags &= kAccJavaFlagsMask;
3242 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003243 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003244 access_flags |= kAccAbstract | kAccFinal;
3245 access_flags &= ~kAccInterface;
3246
3247 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003248
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003249 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor));
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003250 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003251 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003252 }
3253 // Another thread must have loaded the class after we
3254 // started but before we finished. Abandon what we've
3255 // done.
3256 //
3257 // (Yes, this happens.)
3258
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003259 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003260}
3261
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003262mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003263 switch (type) {
3264 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003265 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003266 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003267 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003268 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003269 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003270 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003271 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003272 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003273 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003274 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003275 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003276 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003277 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003278 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003279 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003280 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003281 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003282 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003283 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003284 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003285 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003286 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003287 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003288}
3289
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003290mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3291 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003292 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003293 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003294 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003295 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003296 source += " from ";
3297 source += dex_cache->GetLocation()->ToModifiedUtf8();
3298 }
3299 LOG(INFO) << "Loaded class " << descriptor << source;
3300 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003301 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003302 mirror::Class* existing =
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003303 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003304 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003305 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003306 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003307 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003308 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003309 // Check a class loaded with the system class loader matches one in the image if the class
3310 // is in the image.
3311 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003312 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003313 CHECK(klass == existing);
3314 }
3315 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003316 VerifyObject(klass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003317 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003318 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003319 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003320 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003321 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003322}
3323
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003324mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3325 size_t hash) {
3326 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3327 mirror::Class* existing =
3328 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
3329
3330 if (existing == nullptr) {
3331 CHECK(klass->IsProxyClass());
3332 return nullptr;
3333 }
3334
3335 CHECK_NE(existing, klass) << descriptor;
3336 CHECK(!existing->IsResolved()) << descriptor;
3337 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3338
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003339 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3340 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003341 mirror::Class* klass = it->second.Read();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07003342 if (klass == existing) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003343 class_table_.erase(it);
3344 break;
3345 }
3346 }
3347
3348 CHECK(!klass->IsTemp()) << descriptor;
3349 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3350 dex_cache_image_class_lookup_required_) {
3351 // Check a class loaded with the system class loader matches one in the image if the class
3352 // is in the image.
3353 existing = LookupClassFromImage(descriptor);
3354 if (existing != nullptr) {
3355 CHECK(klass == existing) << descriptor;
3356 }
3357 }
3358 VerifyObject(klass);
3359
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003360 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003361 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003362 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003363 }
3364
3365 return existing;
3366}
3367
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003368bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003369 size_t hash = Hash(descriptor);
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003370 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstromf3632832014-05-20 15:36:53 -07003371 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3372 it != end && it->first == hash;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003373 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003374 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003375 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003376 class_table_.erase(it);
Brian Carlstromae826982011-11-09 01:33:42 -08003377 return true;
3378 }
3379 }
3380 return false;
3381}
3382
Ian Rogers7b078e82014-09-10 14:44:24 -07003383mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003384 const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003385 size_t hash = Hash(descriptor);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003386 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003387 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003388 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003389 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003390 return result;
3391 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003392 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003393 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3394 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003395 } else {
3396 // Lookup failed but need to search dex_caches_.
3397 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003398 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003399 InsertClass(descriptor, result, hash);
3400 } else {
3401 // Searching the image dex files/caches failed, we don't want to get into this situation
3402 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3403 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003404 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003405 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3406 MoveImageClassesToClassTable();
3407 }
3408 }
3409 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003410 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003411}
3412
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003413mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
3414 const mirror::ClassLoader* class_loader,
3415 size_t hash) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003416 auto end = class_table_.end();
3417 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003418 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003419 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003420 if (kIsDebugBuild) {
3421 // Check for duplicates in the table.
3422 for (++it; it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003423 mirror::Class* klass2 = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003424 CHECK(!(klass2->GetClassLoader() == class_loader &&
3425 klass2->DescriptorEquals(descriptor)))
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003426 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
3427 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003428 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003429 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003430 return klass;
3431 }
3432 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003433 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003434}
3435
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003436static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3437 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3438 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003439 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003440 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3441 return root->AsObjectArray<mirror::DexCache>();
3442}
3443
3444void ClassLinker::MoveImageClassesToClassTable() {
3445 Thread* self = Thread::Current();
3446 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3447 if (!dex_cache_image_class_lookup_required_) {
3448 return; // All dex cache classes are already in the class table.
3449 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003450 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003451 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003452 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003453 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3454 mirror::DexCache* dex_cache = dex_caches->Get(i);
3455 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3456 for (int32_t j = 0; j < types->GetLength(); j++) {
3457 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003458 if (klass != nullptr) {
3459 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003460 const char* descriptor = klass->GetDescriptor(&temp);
3461 size_t hash = Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003462 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3463 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003464 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
3465 << PrettyClassAndClassLoader(klass);
3466 } else {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003467 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003468 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003469 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003470 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003471 }
3472 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003473 }
3474 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003475 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003476}
3477
3478mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003479 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003480 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3481 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3482 mirror::DexCache* dex_cache = dex_caches->Get(i);
3483 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003484 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003485 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003486 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003487 const DexFile::TypeId* type_id =
3488 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003489 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003490 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3491 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003492 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003493 return klass;
3494 }
3495 }
3496 }
3497 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003498 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003499}
3500
3501void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3502 result.clear();
3503 if (dex_cache_image_class_lookup_required_) {
3504 MoveImageClassesToClassTable();
3505 }
3506 size_t hash = Hash(descriptor);
3507 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003508 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
Mathieu Chartier02e25112013-08-14 16:14:24 -07003509 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003510 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003511 if (klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003512 result.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003513 }
3514 }
3515}
3516
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003517void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003518 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003519 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003520
Ian Rogers9ffb0392012-09-10 11:56:50 -07003521 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003522 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003523 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003524 return;
3525 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003526 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3527 return;
3528 }
jeffhao98eacac2011-09-14 16:11:53 -07003529
Ian Rogers9ffb0392012-09-10 11:56:50 -07003530 // The class might already be erroneous, for example at compile time if we attempted to verify
3531 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003532 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003533 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003534 return;
3535 }
3536
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003537 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003538 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003539 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003540 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003541 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003542 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003543 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003544 }
jeffhao98eacac2011-09-14 16:11:53 -07003545
Jeff Hao4a200f52014-04-01 14:58:49 -07003546 // Skip verification if disabled.
3547 if (!Runtime::Current()->IsVerificationEnabled()) {
3548 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003549 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003550 return;
3551 }
3552
Ian Rogers9ffb0392012-09-10 11:56:50 -07003553 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003554 StackHandleScope<2> hs(self);
3555 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003556 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003557 // Acquire lock to prevent races on verifying the super class.
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003558 ObjectLock<mirror::Class> lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003559
3560 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003561 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003562 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003563 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003564 std::string error_msg(
3565 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3566 PrettyDescriptor(klass.Get()).c_str(),
3567 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003568 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003569 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3570 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003571 self->ClearException();
3572 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003573 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3574 if (cause.Get() != nullptr) {
3575 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003576 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003577 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003578 if (Runtime::Current()->IsCompiler()) {
3579 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3580 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003581 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003582 return;
3583 }
3584 }
3585
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003586 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003587 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003588 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003589 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003590 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003591 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003592 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003593 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003594 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3595 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003596 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003597 return;
3598 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003599 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003600 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003601 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003602 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003603 Runtime::Current()->IsCompiler(),
3604 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003605 }
3606 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003607 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003608 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003609 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3610 << " because: " << error_msg;
3611 }
Ian Rogers1f539342012-10-03 21:09:42 -07003612 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003613 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003614 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003615 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003616 // Even though there were no verifier failures we need to respect whether the super-class
3617 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003618 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003619 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003620 } else {
3621 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003622 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003623 // Pretend a soft failure occured so that we don't consider the class verified below.
3624 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003625 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003626 } else {
3627 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3628 // Soft failures at compile time should be retried at runtime. Soft
3629 // failures at runtime will be handled by slow paths in the generated
3630 // code. Set status accordingly.
3631 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003632 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003633 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003634 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003635 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3636 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003637 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003638 }
3639 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003640 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003641 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003642 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3643 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003644 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003645 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003646 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003647 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003648 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003649 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003650 // Let the interpreter know it by setting the kAccPreverified flag onto each
3651 // method.
3652 // Note: we're going here during compilation and at runtime. When we set the
3653 // kAccPreverified flag when compiling image classes, the flag is recorded
3654 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003655 EnsurePreverifiedMethods(klass);
3656 }
3657}
3658
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003659void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003660 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003661 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003662 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003663 }
jeffhao98eacac2011-09-14 16:11:53 -07003664}
3665
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003666bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3667 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003668 // If we're compiling, we can only verify the class using the oat file if
3669 // we are not compiling the image or if the class we're verifying is not part of
3670 // the app. In other words, we will only check for preverification of bootclasspath
3671 // classes.
3672 if (Runtime::Current()->IsCompiler()) {
3673 // Are we compiling the bootclasspath?
3674 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3675 return false;
3676 }
3677 // We are compiling an app (not the image).
3678
3679 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003680 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003681 return false;
3682 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003683 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003684
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003685 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003686 // In case we run without an image there won't be a backing oat file.
3687 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003688 return false;
3689 }
3690
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003691 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003692 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003693 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3694 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003695 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003696 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003697 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003698 // Compile time verification failed with a soft error. Compile time verification can fail
3699 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003700 // class ... {
3701 // Foo x;
3702 // .... () {
3703 // if (...) {
3704 // v1 gets assigned a type of resolved class Foo
3705 // } else {
3706 // v1 gets assigned a type of unresolved class Bar
3707 // }
3708 // iput x = v1
3709 // } }
3710 // when we merge v1 following the if-the-else it results in Conflict
3711 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3712 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3713 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3714 // at compile time).
3715 return false;
3716 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003717 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003718 // Compile time verification failed with a hard error. This is caused by invalid instructions
3719 // in the class. These errors are unrecoverable.
3720 return false;
3721 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003722 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003723 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3724 // not loading the class.
3725 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3726 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003727 return false;
3728 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003729 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003730 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003731 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003732 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003733
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003734 return false;
3735}
3736
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003737void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003738 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003739 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3740 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3741 }
3742 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3743 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3744 }
3745}
3746
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003747void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003748 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003749 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3750 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003751 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003752 return; // native or abstract method
3753 }
3754 if (code_item->tries_size_ == 0) {
3755 return; // nothing to process
3756 }
Ian Rogers13735952014-10-08 12:43:28 -07003757 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003758 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3759 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3760 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3761 CatchHandlerIterator iterator(handlers_ptr);
3762 for (; iterator.HasNext(); iterator.Next()) {
3763 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3764 // unresolved exception types will be ignored by exception delivery
3765 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003766 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003767 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003768 DCHECK(Thread::Current()->IsExceptionPending());
3769 Thread::Current()->ClearException();
3770 }
3771 }
3772 }
3773 handlers_ptr = iterator.EndDataPointer();
3774 }
3775}
3776
Brian Carlstromea46f952013-07-30 01:26:50 -07003777static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003778static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3779 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003780
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003781mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003782 jobjectArray interfaces, jobject loader,
3783 jobjectArray methods, jobjectArray throws) {
3784 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003785 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003786 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003787 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003788 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003789 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003790 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003791 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003792 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003793 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003794 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3795 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003796 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003797 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003798 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003799 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003800 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003801 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003802
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003803 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003804 {
3805 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003806 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003807 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003808 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003809 }
3810 klass->SetSFields(sfields);
3811 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003812 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3813 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003814 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3815 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003816 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003817 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003818 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003819 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003820 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003821 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003822 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3823 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003824 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3825 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003826 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003827 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003828 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003829 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003830 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003831 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003832 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003833
Ian Rogers466bb252011-10-14 03:29:56 -07003834 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003835 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003836 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003837 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003838 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003839 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003840 }
3841 klass->SetDirectMethods(directs);
3842 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003843 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003844 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003845 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003846 }
3847 klass->SetDirectMethod(0, constructor);
3848 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003849
Mathieu Chartier590fee92013-09-13 13:46:47 -07003850 // Create virtual method using specified prototypes.
3851 size_t num_virtual_methods =
3852 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003853 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003854 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3855 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003856 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003857 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003858 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003859 }
3860 klass->SetVirtualMethods(virtuals);
3861 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003862 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003863 StackHandleScope<1> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003864 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3865 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003866 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003867 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003868 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003869 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003870 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003871 }
3872 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003873 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003874
3875 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003876 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003877 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003878
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003879 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3880 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003881 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003882 // Must hold lock on object when resolved.
3883 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003884 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003885 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003886 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003887 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003888 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003889 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003890 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003891 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003892
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003893 CHECK(klass->IsRetired());
3894 CHECK_NE(klass.Get(), new_class);
3895 klass.Assign(new_class);
3896
3897 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003898 interfaces_sfield->SetObject<false>(klass.Get(),
3899 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003900 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003901 throws_sfield->SetObject<false>(klass.Get(),
3902 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003903
3904 {
3905 // Lock on klass is released. Lock new class object.
3906 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003907 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003908 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003909
3910 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003911 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003912 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003913 CheckProxyConstructor(klass->GetDirectMethod(0));
3914 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003915 StackHandleScope<2> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003916 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3917 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003918 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003919 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3920 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003921 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003922
Mathieu Chartier590fee92013-09-13 13:46:47 -07003923 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003924 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003925 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003926 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3927
3928 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003929 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003930 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003931
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003932 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003933 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003934 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003935 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003936 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003937 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003938 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003939 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003940}
3941
Ian Rogersef7d42f2014-01-06 12:55:46 -08003942std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003943 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003944 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003945 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003946 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3947}
3948
Ian Rogersef7d42f2014-01-06 12:55:46 -08003949mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3950 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003951 DCHECK(proxy_class->IsProxyClass());
3952 DCHECK(proxy_method->IsProxyMethod());
3953 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003954 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003955 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003956 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003957 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003958 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003959 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003960 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003961 break;
3962 }
3963 }
3964 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003965 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003966 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003967 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003968 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003969 return resolved_method;
3970}
3971
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003972
Brian Carlstromea46f952013-07-30 01:26:50 -07003973mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003974 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003975 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003976 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003977 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003978 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003979 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3980 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003981 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3982 // constructor method.
3983 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3984 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003985 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3986 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003987 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3988 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003989 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003990 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003991 }
Ian Rogers466bb252011-10-14 03:29:56 -07003992 // Make this constructor public and fix the class to be our Proxy version
3993 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003994 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003995 return constructor;
3996}
3997
Brian Carlstromea46f952013-07-30 01:26:50 -07003998static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003999 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004000 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004001 CHECK_STREQ(constructor->GetName(), "<init>");
4002 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4003 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004004 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004005}
4006
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004007mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004008 Handle<mirror::Class> klass,
4009 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004010 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4011 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004012 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004013 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004014 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004015 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004016 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004017 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004018 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004019 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004020 }
Ian Rogers466bb252011-10-14 03:29:56 -07004021
4022 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4023 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004024 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004025 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004026
Ian Rogers466bb252011-10-14 03:29:56 -07004027 // At runtime the method looks like a reference and argument saving method, clone the code
4028 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004029 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4030 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004031 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004032
Ian Rogersc2b44472011-12-14 21:17:17 -08004033 return method;
4034}
Jesse Wilson95caa792011-10-12 18:14:17 -04004035
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004036static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4037 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004038 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004039 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004040 CHECK(!prototype->IsFinal());
4041 CHECK(method->IsFinal());
4042 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004043
4044 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4045 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
4046 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
Andreas Gampe58a5af82014-07-31 16:23:49 -07004047 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4048 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004049 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4050
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004051 StackHandleScope<2> hs(Thread::Current());
4052 MethodHelper mh(hs.NewHandle(method.Get()));
4053 MethodHelper mh2(hs.NewHandle(prototype.Get()));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004054 CHECK_STREQ(method->GetName(), prototype->GetName());
4055 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004056 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08004057 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004058}
4059
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004060static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4061 bool can_init_parents)
4062 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004063 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004064 return true;
4065 }
4066 if (!can_init_statics) {
4067 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004068 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004069 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004070 return false;
4071 }
4072 // Check if there are encoded static values needing initialization.
4073 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004074 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004075 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004076 if (dex_class_def->static_values_off_ != 0) {
4077 return false;
4078 }
4079 }
4080 }
4081 if (!klass->IsInterface() && klass->HasSuperClass()) {
4082 mirror::Class* super_class = klass->GetSuperClass();
4083 if (!can_init_parents && !super_class->IsInitialized()) {
4084 return false;
4085 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004086 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004087 return false;
4088 }
4089 }
4090 }
4091 return true;
4092}
4093
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004094bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004095 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004096 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4097
4098 // Are we already initialized and therefore done?
4099 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4100 // an initialized class will never change its state.
4101 if (klass->IsInitialized()) {
4102 return true;
4103 }
4104
4105 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004106 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004107 return false;
4108 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004109
Ian Rogers7b078e82014-09-10 14:44:24 -07004110 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004111 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004112 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004113 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004114
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004115 // Re-check under the lock in case another thread initialized ahead of us.
4116 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004117 return true;
4118 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004119
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004120 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004121 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004122 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004123 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004124 return false;
4125 }
4126
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004127 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004128
4129 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004130 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004131 if (!klass->IsVerified()) {
4132 // We failed to verify, expect either the klass to be erroneous or verification failed at
4133 // compile time.
4134 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004135 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004136 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004137 } else {
4138 CHECK(Runtime::Current()->IsCompiler());
4139 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004140 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004141 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004142 } else {
4143 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004144 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004145 }
4146
Brian Carlstromd1422f82011-09-28 11:37:09 -07004147 // If the class is kStatusInitializing, either this thread is
4148 // initializing higher up the stack or another thread has beat us
4149 // to initializing and we need to wait. Either way, this
4150 // invocation of InitializeClass will not be responsible for
4151 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004152 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004153 // Could have got an exception during verification.
4154 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004155 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004156 return false;
4157 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004158 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004159 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004160 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004161 return true;
4162 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004163 // No. That's fine. Wait for another thread to finish initializing.
4164 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004165 }
4166
4167 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004168 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004169 return false;
4170 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004171 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004172
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004173 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004174
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004175 // From here out other threads may observe that we're initializing and so changes of state
4176 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004177 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004178 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004179
4180 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004181 }
4182
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004183 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004184 if (!klass->IsInterface() && klass->HasSuperClass()) {
4185 mirror::Class* super_class = klass->GetSuperClass();
4186 if (!super_class->IsInitialized()) {
4187 CHECK(!super_class->IsInterface());
4188 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004189 StackHandleScope<1> hs(self);
4190 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004191 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004192 if (!super_initialized) {
4193 // The super class was verified ahead of entering initializing, we should only be here if
4194 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004195 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004196 << "Super class initialization failed for "
4197 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004198 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004199 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004200 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004201 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004202 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004203 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004204 return false;
4205 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004206 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004207 }
4208
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004209 if (klass->NumStaticFields() > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004210 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004211 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004212 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004213 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004214 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004215 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004216 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4217 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004218 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004219 ClassDataItemIterator field_it(dex_file, class_data);
4220 if (value_it.HasNext()) {
4221 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004222 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004223 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004224 StackHandleScope<1> hs(self);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004225 Handle<mirror::ArtField> field(hs.NewHandle(
4226 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004227 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004228 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004229 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004230 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004231 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004232 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004233 }
4234 }
4235 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004236
Ian Rogersd91d6d62013-09-25 20:26:14 -07004237 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004238 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004239 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004240 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004241 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004242 }
4243
Ian Rogers7b078e82014-09-10 14:44:24 -07004244 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004245 uint64_t t1 = NanoTime();
4246
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004247 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004248 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004249 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004250
4251 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004252 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004253 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004254 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004255 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004256 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4257 RuntimeStats* thread_stats = self->GetStats();
4258 ++global_stats->class_init_count;
4259 ++thread_stats->class_init_count;
4260 global_stats->class_init_time_ns += (t1 - t0);
4261 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004262 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004263 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004264 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004265 std::string temp;
4266 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004267 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004268 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004269 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004270 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004271 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004272 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004273 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004274}
4275
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004276bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004277 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004278 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004279 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004280 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004281 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004282 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004283
4284 // When we wake up, repeat the test for init-in-progress. If
4285 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004286 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004287 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004288 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004289 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004290 return false;
4291 }
4292 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004293 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004294 continue;
4295 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004296 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004297 // Compile time initialization failed.
4298 return false;
4299 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004300 if (klass->IsErroneous()) {
4301 // The caller wants an exception, but it was thrown in a
4302 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004303 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004304 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004305 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004306 return false;
4307 }
4308 if (klass->IsInitialized()) {
4309 return true;
4310 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004311 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004312 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004313 }
Ian Rogers07140832014-09-30 15:43:59 -07004314 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004315}
4316
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004317bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004318 if (klass->IsInterface()) {
4319 return true;
4320 }
Ian Rogers151f2212014-05-06 11:27:27 -07004321 // Begin with the methods local to the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004322 StackHandleScope<2> hs(Thread::Current());
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004323 MutableMethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4324 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004325 if (klass->HasSuperClass() &&
4326 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004327 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4328 mh.ChangeMethod(klass->GetVTableEntry(i));
4329 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004330 if (mh.GetMethod() != super_mh.GetMethod() &&
4331 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4332 ThrowLinkageError(klass.Get(),
4333 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004334 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004335 PrettyMethod(mh.GetMethod()).c_str(),
4336 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004337 return false;
4338 }
4339 }
4340 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004341 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004342 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4343 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4344 for (uint32_t j = 0; j < num_methods; ++j) {
4345 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4346 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004347 if (mh.GetMethod() != super_mh.GetMethod() &&
4348 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4349 ThrowLinkageError(klass.Get(),
4350 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004351 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004352 PrettyMethod(mh.GetMethod()).c_str(),
4353 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004354 return false;
4355 }
4356 }
4357 }
4358 }
4359 return true;
4360}
4361
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004362bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4363 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004364 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004365 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004366 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004367 return true;
4368 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004369 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004370 if (!success) {
4371 if (can_init_fields && can_init_parents) {
4372 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4373 }
4374 } else {
4375 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004376 }
4377 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004378}
4379
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004380void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4381 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4382 if (fields != nullptr) {
4383 for (int index = 0; index < fields->GetLength(); index ++) {
4384 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4385 fields->Get(index)->SetDeclaringClass(new_class);
4386 }
4387 }
4388 }
4389
4390 fields = new_class->GetSFields();
4391 if (fields != nullptr) {
4392 for (int index = 0; index < fields->GetLength(); index ++) {
4393 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4394 fields->Get(index)->SetDeclaringClass(new_class);
4395 }
4396 }
4397 }
4398
4399 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4400 if (methods != nullptr) {
4401 for (int index = 0; index < methods->GetLength(); index ++) {
4402 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4403 methods->Get(index)->SetDeclaringClass(new_class);
4404 }
4405 }
4406 }
4407
4408 methods = new_class->GetVirtualMethods();
4409 if (methods != nullptr) {
4410 for (int index = 0; index < methods->GetLength(); index ++) {
4411 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4412 methods->Get(index)->SetDeclaringClass(new_class);
4413 }
4414 }
4415 }
4416}
4417
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004418bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4419 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004420 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004421 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004422
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004423 if (!LinkSuperClass(klass)) {
4424 return false;
4425 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004426 if (!LinkMethods(self, klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004427 return false;
4428 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004429 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004430 return false;
4431 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004432 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004433 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004434 return false;
4435 }
4436 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004437 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004438
4439 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4440 // We don't need to retire this class as it has no embedded tables or it was created the
4441 // correct size during class linker initialization.
4442 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4443
4444 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4445 klass->PopulateEmbeddedImtAndVTable();
4446 }
4447
4448 // This will notify waiters on klass that saw the not yet resolved
4449 // class in the class_table_ during EnsureResolved.
4450 klass->SetStatus(mirror::Class::kStatusResolved, self);
4451 *new_class = klass.Get();
4452 } else {
4453 CHECK(!klass->IsResolved());
4454 // Retire the temporary class and create the correctly sized resolved class.
4455 *new_class = klass->CopyOf(self, class_size);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004456 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004457 CHECK(self->IsExceptionPending()); // Expect an OOME.
4458 klass->SetStatus(mirror::Class::kStatusError, self);
4459 return false;
4460 }
4461
4462 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4463 StackHandleScope<1> hs(self);
4464 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4465 ObjectLock<mirror::Class> lock(self, new_class_h);
4466
4467 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4468
4469 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004470 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004471
4472 // This will notify waiters on temp class that saw the not yet resolved class in the
4473 // class_table_ during EnsureResolved.
4474 klass->SetStatus(mirror::Class::kStatusRetired, self);
4475
4476 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4477 // This will notify waiters on new_class that saw the not yet resolved
4478 // class in the class_table_ during EnsureResolved.
4479 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004480 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004481 return true;
4482}
4483
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004484bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004485 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004486 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4487 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004488 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004489 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004490 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004491 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004492 return false;
4493 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004494 // Verify
4495 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004496 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004497 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004498 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004499 return false;
4500 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004501 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004502 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004503 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004504 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004505 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004506 for (size_t i = 0; i < interfaces->Size(); i++) {
4507 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004508 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004509 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004510 DCHECK(Thread::Current()->IsExceptionPending());
4511 return false;
4512 }
4513 // Verify
4514 if (!klass->CanAccess(interface)) {
4515 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004516 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004517 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004518 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004519 return false;
4520 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004521 }
4522 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004523 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004524 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004525 return true;
4526}
4527
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004528bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004529 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004530 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004531 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004532 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004533 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004534 return false;
4535 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004536 return true;
4537 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004538 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004539 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4540 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004541 return false;
4542 }
4543 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004544 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004545 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004546 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004547 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004548 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004549 return false;
4550 }
4551 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004552 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004553 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004554 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004555 return false;
4556 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004557
Brian Carlstromf3632832014-05-20 15:36:53 -07004558 // Inherit kAccClassIsFinalizable from the superclass in case this
4559 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004560 if (super->IsFinalizable()) {
4561 klass->SetFinalizable();
4562 }
4563
Elliott Hughes2da50362011-10-10 16:57:08 -07004564 // Inherit reference flags (if any) from the superclass.
4565 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4566 if (reference_flags != 0) {
4567 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4568 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004569 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004570 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004571 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004572 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004573 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004574 return false;
4575 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004576
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004577 if (kIsDebugBuild) {
4578 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004579 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004580 CHECK(super->IsResolved());
4581 super = super->GetSuperClass();
4582 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004583 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004584 return true;
4585}
4586
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004587// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004588bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
4589 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004590 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004591 if (klass->IsInterface()) {
4592 // No vtable.
4593 size_t count = klass->NumVirtualMethods();
4594 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004595 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004596 return false;
4597 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004598 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004599 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004600 }
jeffhaobdb76512011-09-07 11:43:16 -07004601 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004602 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004603 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07004604 // Link virtual and interface method tables
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004605 return LinkVirtualMethods(self, klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004606 }
4607 return true;
4608}
4609
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004610bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004611 if (klass->HasSuperClass()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004612 uint32_t max_count = klass->NumVirtualMethods() +
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004613 klass->GetSuperClass()->GetVTableLength();
4614 size_t actual_count = klass->GetSuperClass()->GetVTableLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004615 CHECK_LE(actual_count, max_count);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004616 StackHandleScope<4> hs(self);
4617 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004618 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004619 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4620 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4621 if (UNLIKELY(vtable.Get() == nullptr)) {
4622 CHECK(self->IsExceptionPending()); // OOME.
4623 return false;
4624 }
4625 int len = super_class->GetVTableLength();
Mingyao Yang1a128582014-07-22 17:33:25 -07004626 for (int i = 0; i < len; i++) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004627 vtable->Set<false>(i, super_class->GetVTableEntry(i));
4628 }
4629 } else {
Mingyao Yang38eecb02014-08-13 14:51:03 -07004630 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class.Get());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004631 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count));
4632 if (UNLIKELY(vtable.Get() == nullptr)) {
4633 CHECK(self->IsExceptionPending()); // OOME.
4634 return false;
4635 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004636 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004637
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004638 // See if any of our virtual methods override the superclass.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004639 MutableMethodHelper local_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4640 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004641 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004642 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004643 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004644 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004645 for (; j < actual_count; ++j) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004646 mirror::ArtMethod* super_method = vtable->Get(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004647 super_mh.ChangeMethod(super_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004648 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004649 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4650 super_method->GetAccessFlags())) {
Elliott Hughes39717372012-07-13 16:21:23 -07004651 if (super_method->IsFinal()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004652 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
Elliott Hughes39717372012-07-13 16:21:23 -07004653 PrettyMethod(local_method).c_str(),
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004654 super_method->GetDeclaringClassDescriptor());
Elliott Hughes39717372012-07-13 16:21:23 -07004655 return false;
4656 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004657 vtable->Set<false>(j, local_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004658 local_method->SetMethodIndex(j);
4659 break;
4660 } else {
4661 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
4662 << " would have incorrectly overridden the package-private method in "
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004663 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004664 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004665 }
4666 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004667 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004668 // Not overriding, append.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004669 vtable->Set<false>(actual_count, local_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004670 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004671 actual_count += 1;
4672 }
4673 }
4674 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004675 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004676 return false;
4677 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004678 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004679 CHECK_LE(actual_count, max_count);
4680 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004681 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004682 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004683 CHECK(self->IsExceptionPending()); // OOME.
4684 return false;
4685 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004686 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004687 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004688 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004689 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004690 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004691 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004692 ThrowClassFormatError(klass.Get(), "Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004693 return false;
4694 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004695 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004696 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004697 vtable(hs.NewHandle(AllocArtMethodArray(self, num_virtual_methods)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004698 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004699 CHECK(self->IsExceptionPending()); // OOME.
4700 return false;
4701 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004702 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004703 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004704 vtable->Set<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004705 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004706 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004707 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004708 }
4709 return true;
4710}
4711
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004712bool ClassLinker::LinkInterfaceMethods(Handle<mirror::Class> klass,
4713 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004714 Thread* const self = Thread::Current();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004715 Runtime* const runtime = Runtime::Current();
Jeff Hao88474b42013-10-23 16:24:40 -07004716 // Set the imt table to be all conflicts by default.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004717 klass->SetImTable(runtime->GetDefaultImt());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004718 size_t super_ifcount;
4719 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004720 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004721 } else {
4722 super_ifcount = 0;
4723 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07004724 uint32_t num_interfaces =
4725 interfaces.Get() == nullptr ? klass->NumDirectInterfaces() : interfaces->GetLength();
4726 size_t ifcount = super_ifcount + num_interfaces;
4727 for (size_t i = 0; i < num_interfaces; i++) {
4728 mirror::Class* interface =
4729 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4730 interfaces->Get(i);
4731 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004732 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004733 if (ifcount == 0) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004734 // Class implements no interfaces.
4735 DCHECK_EQ(klass->GetIfTableCount(), 0);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004736 DCHECK(klass->GetIfTable() == nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004737 return true;
4738 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004739 if (ifcount == super_ifcount) {
4740 // Class implements same interfaces as parent, are any of these not marker interfaces?
4741 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004742 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Ian Rogers9bc81912012-10-11 21:43:36 -07004743 for (size_t i = 0; i < ifcount; ++i) {
4744 if (super_iftable->GetMethodArrayCount(i) > 0) {
4745 has_non_marker_interface = true;
4746 break;
4747 }
4748 }
4749 if (!has_non_marker_interface) {
4750 // Class just inherits marker interfaces from parent so recycle parent's iftable.
4751 klass->SetIfTable(super_iftable);
4752 return true;
4753 }
4754 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004755 StackHandleScope<5> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004756 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004757 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004758 CHECK(self->IsExceptionPending()); // OOME.
4759 return false;
4760 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004761 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004762 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004763 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004764 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004765 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004766 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004767 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004768 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004769 // Flatten the interface inheritance hierarchy.
4770 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004771 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004772 mirror::Class* interface =
Mathieu Chartierf8322842014-05-16 10:59:25 -07004773 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4774 interfaces->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004775 DCHECK(interface != nullptr);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004776 if (!interface->IsInterface()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004777 std::string temp;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004778 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4779 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers1ff3c982014-08-12 02:30:58 -07004780 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004781 return false;
4782 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004783 // Check if interface is already in iftable
4784 bool duplicate = false;
4785 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004786 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004787 if (existing_interface == interface) {
4788 duplicate = true;
4789 break;
4790 }
4791 }
4792 if (!duplicate) {
4793 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004794 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004795 // Add this interface's non-duplicate super-interfaces.
4796 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004797 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004798 bool super_duplicate = false;
4799 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004800 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004801 if (existing_interface == super_interface) {
4802 super_duplicate = true;
4803 break;
4804 }
4805 }
4806 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004807 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004808 }
4809 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004810 }
4811 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004812 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004813 // Shrink iftable in case duplicates were found
4814 if (idx < ifcount) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004815 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004816 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004817 CHECK(self->IsExceptionPending()); // OOME.
4818 return false;
4819 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004820 ifcount = idx;
4821 } else {
4822 CHECK_EQ(idx, ifcount);
4823 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004824 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004825
4826 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004827 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004828 return true;
4829 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004830 self->AllowThreadSuspension();
Jeff Hao88474b42013-10-23 16:24:40 -07004831 // Allocate imtable
4832 bool imtable_changed = false;
Ian Rogers700a4022014-05-19 16:49:03 -07004833 Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004834 hs.NewHandle(AllocArtMethodArray(self, mirror::Class::kImtSize)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004835 if (UNLIKELY(imtable.Get() == nullptr)) {
Jeff Hao88474b42013-10-23 16:24:40 -07004836 CHECK(self->IsExceptionPending()); // OOME.
4837 return false;
4838 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004839 MutableMethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4840 MutableMethodHelper vtable_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004841 size_t max_miranda_methods = 0; // The max size of miranda_list.
4842 for (size_t i = 0; i < ifcount; ++i) {
4843 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4844 }
4845 Handle<mirror::ObjectArray<mirror::ArtMethod>>
4846 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
4847 size_t miranda_list_size = 0; // The current size of miranda_list.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004848 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004849 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004850 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004851 if (num_methods > 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004852 StackHandleScope<2> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004853 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004854 method_array(hs.NewHandle(AllocArtMethodArray(self, num_methods)));
4855 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004856 CHECK(self->IsExceptionPending()); // OOME.
4857 return false;
4858 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004859 iftable->SetMethodArray(i, method_array.Get());
Ian Rogers700a4022014-05-19 16:49:03 -07004860 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004861 hs.NewHandle(klass->GetVTableDuringLinking()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004862 for (size_t j = 0; j < num_methods; ++j) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004863 interface_mh.ChangeMethod(iftable->GetInterface(i)->GetVirtualMethod(j));
Ian Rogers9bc81912012-10-11 21:43:36 -07004864 int32_t k;
4865 // For each method listed in the interface's method list, find the
4866 // matching method in our class's method list. We want to favor the
4867 // subclass over the superclass, which just requires walking
4868 // back from the end of the vtable. (This only matters if the
4869 // superclass defines a private method and this class redefines
4870 // it -- otherwise it would use the same vtable slot. In .dex files
4871 // those don't end up in the virtual method table, so it shouldn't
4872 // matter which direction we go. We walk it backward anyway.)
4873 for (k = vtable->GetLength() - 1; k >= 0; --k) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004874 vtable_mh.ChangeMethod(vtable->Get(k));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004875 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004876 if (!vtable_mh.Get()->IsAbstract() && !vtable_mh.Get()->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004877 ThrowIllegalAccessError(
4878 klass.Get(),
4879 "Method '%s' implementing interface method '%s' is not public",
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004880 PrettyMethod(vtable_mh.Get()).c_str(),
4881 PrettyMethod(interface_mh.Get()).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004882 return false;
4883 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004884 method_array->Set<false>(j, vtable_mh.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004885 // Place method in imt if entry is empty, place conflict otherwise.
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004886 uint32_t imt_index = interface_mh.Get()->GetDexMethodIndex() % mirror::Class::kImtSize;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004887 if (imtable->Get(imt_index) == nullptr) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004888 imtable->Set<false>(imt_index, vtable_mh.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004889 imtable_changed = true;
4890 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004891 imtable->Set<false>(imt_index, runtime->GetImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -07004892 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004893 break;
4894 }
4895 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004896 if (k < 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004897 StackHandleScope<1> hs(self);
4898 auto miranda_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004899 for (size_t l = 0; l < miranda_list_size; ++l) {
4900 mirror::ArtMethod* mir_method = miranda_list->Get(l);
4901 DCHECK(mir_method != nullptr);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004902 vtable_mh.ChangeMethod(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004903 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004904 miranda_method.Assign(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004905 break;
4906 }
4907 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004908 if (miranda_method.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004909 // Point the interface table at a phantom slot.
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004910 miranda_method.Assign(down_cast<mirror::ArtMethod*>(interface_mh.Get()->Clone(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004911 if (UNLIKELY(miranda_method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004912 CHECK(self->IsExceptionPending()); // OOME.
4913 return false;
4914 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004915 DCHECK_LT(miranda_list_size, max_miranda_methods);
4916 miranda_list->Set<false>(miranda_list_size++, miranda_method.Get());
Ian Rogers9bc81912012-10-11 21:43:36 -07004917 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004918 method_array->Set<false>(j, miranda_method.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004919 }
4920 }
4921 }
4922 }
Jeff Hao88474b42013-10-23 16:24:40 -07004923 if (imtable_changed) {
4924 // Fill in empty entries in interface method table with conflict.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004925 mirror::ArtMethod* imt_conflict_method = runtime->GetImtConflictMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004926 for (size_t i = 0; i < mirror::Class::kImtSize; i++) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004927 if (imtable->Get(i) == nullptr) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004928 imtable->Set<false>(i, imt_conflict_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004929 }
4930 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004931 klass->SetImTable(imtable.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004932 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004933 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004934 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004935 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004936 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4937 if (old_method_count == 0) {
4938 virtuals = AllocArtMethodArray(self, new_method_count);
4939 } else {
4940 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4941 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004942 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004943 CHECK(self->IsExceptionPending()); // OOME.
4944 return false;
4945 }
4946 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004947
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004948 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004949 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004950 hs.NewHandle(klass->GetVTableDuringLinking()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004951 CHECK(vtable.Get() != nullptr);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004952 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004953 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004954 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004955 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004956 CHECK(self->IsExceptionPending()); // OOME.
4957 return false;
4958 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004959 for (size_t i = 0; i < miranda_list_size; ++i) {
4960 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004961 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004962 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4963 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4964 klass->SetVirtualMethod(old_method_count + i, method);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004965 vtable->Set<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004966 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004967 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004968 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004969 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004970
Brian Carlstromea46f952013-07-30 01:26:50 -07004971 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
Elliott Hughes4681c802011-09-25 18:04:37 -07004972 for (int i = 0; i < vtable->GetLength(); ++i) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004973 CHECK(vtable->Get(i) != nullptr);
Elliott Hughes4681c802011-09-25 18:04:37 -07004974 }
4975
Ian Rogers7b078e82014-09-10 14:44:24 -07004976 self->AllowThreadSuspension();
Elliott Hughes4681c802011-09-25 18:04:37 -07004977
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004978 return true;
4979}
4980
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004981bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004982 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004983 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004984}
4985
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004986bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004987 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004988 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004989}
4990
Brian Carlstromdbc05252011-09-09 01:59:59 -07004991struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004992 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4993 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004994 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004995 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004996 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07004997 // 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 -07004998 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4999 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005000 if (type1 != type2) {
5001 bool is_primitive1 = type1 != Primitive::kPrimNot;
5002 bool is_primitive2 = type2 != Primitive::kPrimNot;
Fred Shih37f05ef2014-07-16 18:38:08 -07005003 if (type1 != type2) {
5004 if (is_primitive1 && is_primitive2) {
5005 // Larger primitive types go first.
5006 return Primitive::ComponentSize(type1) > Primitive::ComponentSize(type2);
5007 } else {
5008 // Reference always goes first.
5009 return !is_primitive1;
5010 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08005011 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005012 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005013 // same basic group? then sort by string.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005014 return strcmp(field1->GetName(), field2->GetName()) < 0;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005015 }
5016};
5017
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005018bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005019 size_t* class_size) {
5020 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005021 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005022 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005023
Brian Carlstromea46f952013-07-30 01:26:50 -07005024 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005025 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005026
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005027 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005028 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005029 if (is_static) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005030 uint32_t base = sizeof(mirror::Class); // Static fields come after the class.
5031 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
5032 // Static fields come after the embedded tables.
5033 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
Fred Shih37f05ef2014-07-16 18:38:08 -07005034 0, 0, 0, 0, 0);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005035 }
5036 field_offset = MemberOffset(base);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005037 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005038 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005039 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005040 CHECK(super_class->IsResolved())
5041 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005042 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005043 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005044 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005045
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005046 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005047
Brian Carlstromdbc05252011-09-09 01:59:59 -07005048 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005049 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005050 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005051 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005052 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005053 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005054 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005055 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005056 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005057 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005058 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5059 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005060
Fred Shih381e4ca2014-08-25 17:24:27 -07005061 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005062 size_t current_field = 0;
5063 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005064 FieldGaps gaps;
5065
Brian Carlstromdbc05252011-09-09 01:59:59 -07005066 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005067 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005068 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005069 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005070 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005071 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005072 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005073 if (UNLIKELY(!IsAligned<4>(field_offset.Uint32Value()))) {
5074 MemberOffset old_offset = field_offset;
5075 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5076 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5077 }
5078 DCHECK(IsAligned<4>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005079 grouped_and_sorted_fields.pop_front();
5080 num_reference_fields++;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005081 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005082 field->SetOffset(field_offset);
5083 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005084 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005085 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5086 // otherwise we could end up with suboptimal gap fills.
5087 ShuffleForward<8>(num_fields, &current_field, &field_offset,
5088 fields, &grouped_and_sorted_fields, &gaps);
5089 ShuffleForward<4>(num_fields, &current_field, &field_offset,
5090 fields, &grouped_and_sorted_fields, &gaps);
5091 ShuffleForward<2>(num_fields, &current_field, &field_offset,
5092 fields, &grouped_and_sorted_fields, &gaps);
5093 ShuffleForward<1>(num_fields, &current_field, &field_offset,
5094 fields, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005095 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5096 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005097 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005098
Elliott Hughesadb460d2011-10-05 17:02:34 -07005099 // 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 -07005100 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005101 // We know there are no non-reference fields in the Reference classes, and we know
5102 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005103 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005104 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005105 --num_reference_fields;
5106 }
5107
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005108 if (kIsDebugBuild) {
5109 // Make sure that all reference fields appear before
5110 // non-reference fields, and all double-wide fields are aligned.
5111 bool seen_non_ref = false;
5112 for (size_t i = 0; i < num_fields; i++) {
5113 mirror::ArtField* field = fields->Get(i);
Ian Rogerscf7f1912014-10-22 22:06:39 -07005114 if ((false)) { // enable to debug field layout
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005115 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005116 << " class=" << PrettyClass(klass.Get())
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005117 << " field=" << PrettyField(field)
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07005118 << " offset="
5119 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005120 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005121 Primitive::Type type = field->GetTypeAsPrimitiveType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005122 bool is_primitive = type != Primitive::kPrimNot;
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005123 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005124 strcmp("referent", field->GetName()) == 0) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005125 is_primitive = true; // We lied above, so we have to expect a lie here.
5126 }
5127 if (is_primitive) {
5128 if (!seen_non_ref) {
5129 seen_non_ref = true;
Brian Carlstromf3632832014-05-20 15:36:53 -07005130 DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005131 }
5132 } else {
Brian Carlstromf3632832014-05-20 15:36:53 -07005133 DCHECK(!seen_non_ref) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005134 }
5135 }
5136 if (!seen_non_ref) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005137 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005138 }
5139 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005140
5141 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005142 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005143 if (is_static) {
5144 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005145 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005146 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005147 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005148 if (!klass->IsVariableSize()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005149 std::string temp;
5150 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005151 size_t previous_size = klass->GetObjectSize();
5152 if (previous_size != 0) {
5153 // Make sure that we didn't originally have an incorrect size.
Ian Rogers1ff3c982014-08-12 02:30:58 -07005154 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005155 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005156 klass->SetObjectSize(size);
5157 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005158 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005159 return true;
5160}
5161
5162// Set the bitmap of reference offsets, refOffsets, from the ifields
5163// list.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005164void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005165 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005166 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005167 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005168 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005169 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005170 // Compute reference offsets unless our superclass overflowed.
5171 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5172 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
5173 mirror::ObjectArray<mirror::ArtField>* fields = klass->GetIFields();
5174 // All of the fields that contain object references are guaranteed
5175 // to be at the beginning of the fields list.
5176 for (size_t i = 0; i < num_reference_fields; ++i) {
5177 // Note that byte_offset is the offset from the beginning of
5178 // object, not the offset into instance data
5179 mirror::ArtField* field = fields->Get(i);
5180 MemberOffset byte_offset = field->GetOffsetDuringLinking();
5181 uint32_t displaced_bitmap_position =
5182 (byte_offset.Uint32Value() - mirror::kObjectHeaderSize) /
5183 sizeof(mirror::HeapReference<mirror::Object>);
5184 if (displaced_bitmap_position >= 32) {
5185 // Can't encode offset so fall back on slow-path.
5186 reference_offsets = mirror::Class::kClassWalkSuper;
5187 break;
5188 } else {
5189 reference_offsets |= (1 << displaced_bitmap_position);
5190 }
5191 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005192 }
5193 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005194 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005195}
5196
Mathieu Chartier590fee92013-09-13 13:46:47 -07005197mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005198 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005199 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005200 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005201 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005202 return resolved;
5203 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005204 uint32_t utf16_length;
5205 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005206 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005207 dex_cache->SetResolvedString(string_idx, string);
5208 return string;
5209}
5210
Mathieu Chartier590fee92013-09-13 13:46:47 -07005211mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005212 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005213 StackHandleScope<2> hs(Thread::Current());
5214 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5215 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005216 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5217}
5218
5219mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005220 Handle<mirror::DexCache> dex_cache,
5221 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005222 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005223 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005224 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005225 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005226 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005227 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005228 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005229 // TODO: we used to throw here if resolved's class loader was not the
5230 // boot class loader. This was to permit different classes with the
5231 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005232 dex_cache->SetResolvedType(type_idx, resolved);
5233 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005234 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005235 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005236 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005237 StackHandleScope<1> hs(self);
5238 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005239 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005240 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005241 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005242 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005243 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005244 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005245 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005246 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005247 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005248 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005249 return resolved;
5250}
5251
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005252mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005253 Handle<mirror::DexCache> dex_cache,
5254 Handle<mirror::ClassLoader> class_loader,
5255 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005256 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005257 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005258 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005259 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005260 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005261 return resolved;
5262 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005263 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005264 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005265 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005266 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005267 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005268 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005269 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005270 // Scan using method_idx, this saves string compares but will only hit for matching dex
5271 // caches/files.
5272 switch (type) {
5273 case kDirect: // Fall-through.
5274 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005275 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005276 break;
5277 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005278 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005279 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005280 break;
5281 case kSuper: // Fall-through.
5282 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005283 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005284 break;
5285 default:
5286 LOG(FATAL) << "Unreachable - invocation type: " << type;
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005287 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005288 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005289 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005290 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005291 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005292 switch (type) {
5293 case kDirect: // Fall-through.
5294 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005295 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005296 break;
5297 case kInterface:
5298 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005299 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005300 break;
5301 case kSuper: // Fall-through.
5302 case kVirtual:
5303 resolved = klass->FindVirtualMethod(name, signature);
5304 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005305 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005306 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005307 // If we found a method, check for incompatible class changes.
5308 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005309 // Be a good citizen and update the dex cache to speed subsequent calls.
5310 dex_cache->SetResolvedMethod(method_idx, resolved);
5311 return resolved;
5312 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005313 // If we had a method, it's an incompatible-class-change error.
5314 if (resolved != nullptr) {
5315 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5316 } else {
5317 // We failed to find the method which means either an access error, an incompatible class
5318 // change, or no such method. First try to find the method among direct and virtual methods.
5319 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5320 const Signature signature = dex_file.GetMethodSignature(method_id);
5321 switch (type) {
5322 case kDirect:
5323 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005324 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005325 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5326 // have had a resolved method before, which triggers the "true" branch above.
5327 break;
5328 case kInterface:
5329 case kVirtual:
5330 case kSuper:
5331 resolved = klass->FindDirectMethod(name, signature);
5332 break;
5333 }
5334
5335 // If we found something, check that it can be accessed by the referrer.
5336 if (resolved != nullptr && referrer.Get() != nullptr) {
5337 mirror::Class* methods_class = resolved->GetDeclaringClass();
5338 mirror::Class* referring_class = referrer->GetDeclaringClass();
5339 if (!referring_class->CanAccess(methods_class)) {
5340 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5341 resolved, type);
5342 return nullptr;
5343 } else if (!referring_class->CanAccessMember(methods_class,
5344 resolved->GetAccessFlags())) {
5345 ThrowIllegalAccessErrorMethod(referring_class, resolved);
5346 return nullptr;
5347 }
5348 }
5349
5350 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5351 // methods and throw if we find the method there. If we find nothing, throw a
5352 // NoSuchMethodError.
5353 switch (type) {
5354 case kDirect:
5355 case kStatic:
5356 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005357 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005358 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005359 resolved = klass->FindInterfaceMethod(name, signature);
5360 if (resolved != nullptr) {
5361 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5362 } else {
5363 ThrowNoSuchMethodError(type, klass, name, signature);
5364 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005365 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005366 break;
5367 case kInterface:
5368 if (resolved != nullptr) {
5369 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005370 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005371 resolved = klass->FindVirtualMethod(name, signature);
5372 if (resolved != nullptr) {
5373 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5374 } else {
5375 ThrowNoSuchMethodError(type, klass, name, signature);
5376 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005377 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005378 break;
5379 case kSuper:
Andreas Gampedf733752014-08-25 20:55:01 -07005380 if (resolved != nullptr) {
5381 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5382 } else {
5383 ThrowNoSuchMethodError(type, klass, name, signature);
5384 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005385 break;
5386 case kVirtual:
5387 if (resolved != nullptr) {
5388 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5389 } else {
5390 resolved = klass->FindInterfaceMethod(name, signature);
5391 if (resolved != nullptr) {
5392 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5393 } else {
5394 ThrowNoSuchMethodError(type, klass, name, signature);
5395 }
5396 }
5397 break;
5398 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005399 }
5400 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005401 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005402 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005403}
5404
Mathieu Chartier590fee92013-09-13 13:46:47 -07005405mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005406 Handle<mirror::DexCache> dex_cache,
5407 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005408 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005409 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005410 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005411 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005412 return resolved;
5413 }
5414 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005415 Thread* const self = Thread::Current();
5416 StackHandleScope<1> hs(self);
5417 Handle<mirror::Class> klass(
5418 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005419 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005420 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005421 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005422 }
5423
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005424 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005425 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005426 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005427 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005428 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005429
Andreas Gampe58a5af82014-07-31 16:23:49 -07005430 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005431 const char* name = dex_file.GetFieldName(field_id);
5432 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5433 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005434 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005435 } else {
5436 resolved = klass->FindInstanceField(name, type);
5437 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005438 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005439 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005440 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005441 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005442 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005443 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005444 return resolved;
5445}
5446
Brian Carlstromea46f952013-07-30 01:26:50 -07005447mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005448 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005449 Handle<mirror::DexCache> dex_cache,
5450 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005451 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005452 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005453 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005454 return resolved;
5455 }
5456 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005457 Thread* self = Thread::Current();
5458 StackHandleScope<1> hs(self);
5459 Handle<mirror::Class> klass(
5460 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005461 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005462 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005463 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005464 }
5465
Ian Rogersdfb325e2013-10-30 01:00:44 -07005466 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5467 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005468 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005469 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005470 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005471 dex_cache->SetResolvedField(field_idx, resolved);
5472 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005473 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005474 }
5475 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005476}
5477
Brian Carlstromea46f952013-07-30 01:26:50 -07005478const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005479 uint32_t* length) {
5480 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5481 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005482 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005483 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005484 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005485}
5486
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005487void ClassLinker::DumpAllClasses(int flags) {
5488 if (dex_cache_image_class_lookup_required_) {
5489 MoveImageClassesToClassTable();
5490 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005491 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5492 // 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 -08005493 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005494 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005495 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005496 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
5497 mirror::Class* klass = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07005498 all_classes.push_back(klass);
Ian Rogers5d76c432011-10-31 21:42:49 -07005499 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005500 }
5501
5502 for (size_t i = 0; i < all_classes.size(); ++i) {
5503 all_classes[i]->DumpClass(std::cerr, flags);
5504 }
5505}
5506
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005507static OatFile::OatMethod CreateOatMethod(const void* code, const uint8_t* gc_map,
5508 bool is_portable) {
5509 CHECK_EQ(kUsePortableCompiler, is_portable);
5510 CHECK(code != nullptr);
5511 const uint8_t* base;
5512 uint32_t code_offset, gc_map_offset;
5513 if (gc_map == nullptr) {
5514 base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5515 base -= sizeof(void*); // Move backward so that code_offset != 0.
5516 code_offset = sizeof(void*);
5517 gc_map_offset = 0;
5518 } else {
5519 // TODO: 64bit support.
5520 base = nullptr; // Base of data in oat file, ie 0.
5521 code_offset = PointerToLowMemUInt32(code);
5522 gc_map_offset = PointerToLowMemUInt32(gc_map);
5523 }
5524 return OatFile::OatMethod(base, code_offset, gc_map_offset);
5525}
5526
5527bool ClassLinker::IsPortableResolutionStub(const void* entry_point) const {
5528 return (entry_point == GetPortableResolutionStub()) ||
5529 (portable_resolution_trampoline_ == entry_point);
5530}
5531
5532bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5533 return (entry_point == GetQuickResolutionStub()) ||
5534 (quick_resolution_trampoline_ == entry_point);
5535}
5536
5537bool ClassLinker::IsPortableToInterpreterBridge(const void* entry_point) const {
5538 return (entry_point == GetPortableToInterpreterBridge());
5539 // TODO: portable_to_interpreter_bridge_trampoline_ == entry_point;
5540}
5541
5542bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5543 return (entry_point == GetQuickToInterpreterBridge()) ||
5544 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5545}
5546
5547bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5548 return (entry_point == GetQuickGenericJniStub()) ||
5549 (quick_generic_jni_trampoline_ == entry_point);
5550}
5551
5552const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5553 return GetQuickGenericJniStub();
5554}
5555
5556void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method, const void* method_code,
5557 bool is_portable) const {
5558 OatFile::OatMethod oat_method = CreateOatMethod(method_code, nullptr, is_portable);
5559 oat_method.LinkMethod(method);
5560 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5561 // Create bridges to transition between different kinds of compiled bridge.
5562 if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
5563 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5564 } else {
5565 CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
5566 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
5567 method->SetIsPortableCompiled();
5568 }
5569}
5570
5571void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5572 if (!method->IsNative()) {
5573 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
5574 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
5575 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5576 } else {
5577 const void* quick_method_code = GetQuickGenericJniStub();
5578 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code, nullptr, false);
5579 oat_method.LinkMethod(method);
5580 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5581 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5582 }
5583}
5584
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005585void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005586 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005587 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005588 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005589 MoveImageClassesToClassTable();
5590 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005591 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005592 os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005593}
5594
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005595size_t ClassLinker::NumLoadedClasses() {
5596 if (dex_cache_image_class_lookup_required_) {
5597 MoveImageClassesToClassTable();
5598 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005599 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005600 return class_table_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005601}
5602
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005603pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005604 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005605}
5606
5607pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005608 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005609}
5610
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005611void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005612 DCHECK(!init_done_);
5613
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005614 DCHECK(klass != nullptr);
5615 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005616
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005617 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005618 DCHECK(class_roots != nullptr);
5619 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005620 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005621}
5622
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005623const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5624 static const char* class_roots_descriptors[] = {
5625 "Ljava/lang/Class;",
5626 "Ljava/lang/Object;",
5627 "[Ljava/lang/Class;",
5628 "[Ljava/lang/Object;",
5629 "Ljava/lang/String;",
5630 "Ljava/lang/DexCache;",
5631 "Ljava/lang/ref/Reference;",
5632 "Ljava/lang/reflect/ArtField;",
5633 "Ljava/lang/reflect/ArtMethod;",
5634 "Ljava/lang/reflect/Proxy;",
5635 "[Ljava/lang/String;",
5636 "[Ljava/lang/reflect/ArtField;",
5637 "[Ljava/lang/reflect/ArtMethod;",
5638 "Ljava/lang/ClassLoader;",
5639 "Ljava/lang/Throwable;",
5640 "Ljava/lang/ClassNotFoundException;",
5641 "Ljava/lang/StackTraceElement;",
5642 "Z",
5643 "B",
5644 "C",
5645 "D",
5646 "F",
5647 "I",
5648 "J",
5649 "S",
5650 "V",
5651 "[Z",
5652 "[B",
5653 "[C",
5654 "[D",
5655 "[F",
5656 "[I",
5657 "[J",
5658 "[S",
5659 "[Ljava/lang/StackTraceElement;",
5660 };
5661 COMPILE_ASSERT(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5662 mismatch_between_class_descriptors_and_class_root_enum);
5663
5664 const char* descriptor = class_roots_descriptors[class_root];
5665 CHECK(descriptor != nullptr);
5666 return descriptor;
5667}
5668
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005669} // namespace art