blob: f0c8819a529f47c265eb9eb6abf6a7802a56c601 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromdbc05252011-09-09 01:59:59 -070019#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070020#include <iostream>
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070022#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070023#include <string>
Andreas Gampea696c0a2014-12-10 20:51:45 -080024#include <unistd.h>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070027
Elliott Hughes1aa246d2012-12-13 09:29:36 -080028#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080029#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010030#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080031#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080032#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080033#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000034#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080035#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070037#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070038#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/accounting/card_table-inl.h"
40#include "gc/accounting/heap_bitmap.h"
41#include "gc/heap.h"
42#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070043#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070044#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070045#include "interpreter/interpreter.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080046#include "jit/jit.h"
47#include "jit/jit_code_cache.h"
Ian Rogers0571d352011-11-03 19:51:38 -070048#include "leb128.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080049#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070050#include "oat_file.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070051#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070052#include "mirror/art_field-inl.h"
53#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080054#include "mirror/class.h"
55#include "mirror/class-inl.h"
56#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070057#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080058#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "mirror/object-inl.h"
60#include "mirror/object_array-inl.h"
61#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070062#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080063#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070064#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080065#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070066#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070067#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070068#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070069#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070070#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070071#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070072#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080073#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070074#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070075
76namespace art {
77
Ian Rogers00f7d0e2012-07-19 15:28:27 -070078static void ThrowNoClassDefFoundError(const char* fmt, ...)
79 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070080 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070081static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070082 va_list args;
83 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080084 Thread* self = Thread::Current();
85 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
86 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080087 va_end(args);
88}
89
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080090static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070091 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070092 // The class failed to initialize on a previous attempt, so we want to throw
93 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
94 // failed in verification, in which case v2 5.4.1 says we need to re-throw
95 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080096 Runtime* const runtime = Runtime::Current();
97 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -070098 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
99 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700100
Elliott Hughes5c599942012-06-13 16:45:05 -0700101 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800102 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800103 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700104 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
105 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000106 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700107 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700108 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
109 if (c->GetVerifyErrorClass() != NULL) {
110 // TODO: change the verifier to store an _instance_, with a useful detail message?
111 std::string temp;
112 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
113 PrettyDescriptor(c).c_str());
114 } else {
115 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
116 PrettyDescriptor(c).c_str());
117 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700118 }
119}
120
Brian Carlstromb23eab12014-10-08 17:55:21 -0700121static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
122 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
123 if (VLOG_IS_ON(class_linker)) {
124 std::string temp;
125 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000126 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700127 }
128}
129
130static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
131 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700132 Thread* self = Thread::Current();
133 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700134
135 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700136 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700137
138 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700139 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
140 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700141
Elliott Hughesa4f94742012-05-29 16:28:38 -0700142 // We only wrap non-Error exceptions; an Error can just be used as-is.
143 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800144 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700145 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;",
146 nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700147 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700148 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700149}
150
Fred Shih381e4ca2014-08-25 17:24:27 -0700151// Gap between two fields in object layout.
152struct FieldGap {
153 uint32_t start_offset; // The offset from the start of the object.
154 uint32_t size; // The gap size of 1, 2, or 4 bytes.
155};
156struct FieldGapsComparator {
157 explicit FieldGapsComparator() {
158 }
159 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
160 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800161 // Sort by gap size, largest first. Secondary sort by starting offset.
162 return lhs.size > rhs.size || (lhs.size == rhs.size && lhs.start_offset < rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700163 }
164};
165typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
166
167// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800168static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700169 DCHECK(gaps != nullptr);
170
171 uint32_t current_offset = gap_start;
172 while (current_offset != gap_end) {
173 size_t remaining = gap_end - current_offset;
174 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
175 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
176 current_offset += sizeof(uint32_t);
177 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
178 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
179 current_offset += sizeof(uint16_t);
180 } else {
181 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
182 current_offset += sizeof(uint8_t);
183 }
184 DCHECK_LE(current_offset, gap_end) << "Overran gap";
185 }
186}
187// Shuffle fields forward, making use of gaps whenever possible.
188template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000189static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700190 MemberOffset* field_offset,
Fred Shih381e4ca2014-08-25 17:24:27 -0700191 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
192 FieldGaps* gaps)
193 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
194 DCHECK(current_field_idx != nullptr);
195 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700196 DCHECK(gaps != nullptr);
197 DCHECK(field_offset != nullptr);
198
199 DCHECK(IsPowerOfTwo(n));
200 while (!grouped_and_sorted_fields->empty()) {
201 mirror::ArtField* field = grouped_and_sorted_fields->front();
202 Primitive::Type type = field->GetTypeAsPrimitiveType();
203 if (Primitive::ComponentSize(type) < n) {
204 break;
205 }
206 if (!IsAligned<n>(field_offset->Uint32Value())) {
207 MemberOffset old_offset = *field_offset;
208 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
209 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
210 }
211 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
212 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700213 if (!gaps->empty() && gaps->top().size >= n) {
214 FieldGap gap = gaps->top();
215 gaps->pop();
216 DCHECK(IsAligned<n>(gap.start_offset));
217 field->SetOffset(MemberOffset(gap.start_offset));
218 if (gap.size > n) {
219 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
220 }
221 } else {
222 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
223 field->SetOffset(*field_offset);
224 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
225 }
226 ++(*current_field_idx);
227 }
228}
229
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800230ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700231 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700232 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700233 dex_cache_image_class_lookup_required_(false),
234 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800235 class_roots_(nullptr),
236 array_iftable_(nullptr),
237 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700238 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800239 log_new_dex_caches_roots_(false),
240 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700241 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800242 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800243 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100244 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800245 quick_to_interpreter_bridge_trampoline_(nullptr),
246 image_pointer_size_(sizeof(void*)) {
Ian Rogers98379392014-02-24 16:53:16 -0800247 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700248}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700249
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800250void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800251 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700252 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700253
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700254 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700255
Elliott Hughes30646832011-10-13 16:59:46 -0700256 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700257 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700258 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700259 // 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 -0800260 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700261 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
262 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700263 heap->AllocNonMovableObject<true>(self, nullptr,
264 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700265 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700266 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700267 mirror::Class::SetClassClass(java_lang_Class.Get());
268 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700269 if (kUseBakerOrBrooksReadBarrier) {
270 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800271 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700272 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700273 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800274 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800275 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700276
Elliott Hughes418d20f2011-09-22 14:00:39 -0700277 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700278 Handle<mirror::Class> class_array_class(hs.NewHandle(
279 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700280 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700281
Ian Rogers23435d02012-09-24 11:23:12 -0700282 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700283 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
284 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700285 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700286 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700287 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700288 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700289
Ian Rogers23435d02012-09-24 11:23:12 -0700290 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700291 Handle<mirror::Class> object_array_class(hs.NewHandle(
292 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700293 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700294
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700295 // Setup the char (primitive) class to be used for char[].
296 Handle<mirror::Class> char_class(hs.NewHandle(
297 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700298 // The primitive char class won't be initialized by
299 // InitializePrimitiveClass until line 459, but strings (and
300 // internal char arrays) will be allocated before that and the
301 // component size, which is computed from the primitive type, needs
302 // to be set here.
303 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700304
Ian Rogers23435d02012-09-24 11:23:12 -0700305 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700306 Handle<mirror::Class> char_array_class(hs.NewHandle(
307 AllocClass(self, java_lang_Class.Get(),
308 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700309 char_array_class->SetComponentType(char_class.Get());
310 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700311
Ian Rogers23435d02012-09-24 11:23:12 -0700312 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700313 Handle<mirror::Class> java_lang_String(hs.NewHandle(
314 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700315 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700316 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700317 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400318
Fred Shih4ee7a662014-07-11 09:59:27 -0700319 // Setup Reference.
320 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
321 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
322 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
323 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
324 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
325
Ian Rogers23435d02012-09-24 11:23:12 -0700326 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700327 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
328 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
329 kClassRootsMax));
330 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700331 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
332 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
333 SetClassRoot(kClassArrayClass, class_array_class.Get());
334 SetClassRoot(kObjectArrayClass, object_array_class.Get());
335 SetClassRoot(kCharArrayClass, char_array_class.Get());
336 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700337 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700338
339 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700340 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
341 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
342 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
343 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
344 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
345 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
346 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
347 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700348
Ian Rogers23435d02012-09-24 11:23:12 -0700349 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700350 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351
Ian Rogers23435d02012-09-24 11:23:12 -0700352 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700353 Handle<mirror::Class> int_array_class(hs.NewHandle(
354 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700356 mirror::IntArray::SetArrayClass(int_array_class.Get());
357 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700358
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700359 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700360
Ian Rogers52813c92012-10-11 11:50:38 -0700361 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700362 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
363 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700364 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700365 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700366 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700367
Brian Carlstromf3632832014-05-20 15:36:53 -0700368 // Constructor, Field, Method, and AbstractMethod are necessary so
369 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700370 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
371 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700372 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700373 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700374 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700375 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700376 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700377
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700378 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
379 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700380 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800381 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
382 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700383 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700384 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700385 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700386
387 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700388 Handle<mirror::Class> object_array_string(hs.NewHandle(
389 AllocClass(self, java_lang_Class.Get(),
390 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700391 object_array_string->SetComponentType(java_lang_String.Get());
392 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700393
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700394 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
395 AllocClass(self, java_lang_Class.Get(),
396 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700397 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
398 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700399
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700400 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
401 AllocClass(self, java_lang_Class.Get(),
402 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700403 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
404 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700405
Ian Rogers23435d02012-09-24 11:23:12 -0700406 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
407 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
408 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700409 CHECK_NE(0U, boot_class_path.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800410 for (auto& dex_file : boot_class_path) {
411 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700412 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800413 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700414 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700415
416 // now we can use FindSystemClass
417
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700418 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700419 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
420 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700421
Jeff Hao88474b42013-10-23 16:24:40 -0700422 // Create runtime resolution and imt conflict methods. Also setup the default imt.
423 Runtime* runtime = Runtime::Current();
424 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
425 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700426 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700427 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
428
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700429 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
430 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700431 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800432 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700433 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700434 quick_resolution_trampoline_ = GetQuickResolutionStub();
435 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
436 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700437 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700438
Mathieu Chartier66f19252012-09-18 08:57:04 -0700439 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700440 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800441 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700442 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700443 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700444 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800445 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700446 std::ostringstream os1, os2;
447 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
448 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
449 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
450 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700451 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800452 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700453 CHECK_EQ(java_lang_String.Get(), String_class);
454 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700455 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700456
Ian Rogers23435d02012-09-24 11:23:12 -0700457 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800458 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800459 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700460
Ian Rogers98379392014-02-24 16:53:16 -0800461 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800462 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700463
Ian Rogers98379392014-02-24 16:53:16 -0800464 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700465 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700466
Ian Rogers98379392014-02-24 16:53:16 -0800467 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800468 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700469
Ian Rogers98379392014-02-24 16:53:16 -0800470 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700471 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700472
Ian Rogers98379392014-02-24 16:53:16 -0800473 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800474 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700475
Ian Rogers98379392014-02-24 16:53:16 -0800476 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800477 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700478
Ian Rogers98379392014-02-24 16:53:16 -0800479 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800480 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700481
Ian Rogers98379392014-02-24 16:53:16 -0800482 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700483 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700484
Ian Rogers98379392014-02-24 16:53:16 -0800485 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700486 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700487
Ian Rogers23435d02012-09-24 11:23:12 -0700488 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800489 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700490 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800491 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700492 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700493 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
494 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700495 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700496 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700497 array_iftable->SetInterface(0, java_lang_Cloneable);
498 array_iftable->SetInterface(1, java_io_Serializable);
499 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700500
Ian Rogers23435d02012-09-24 11:23:12 -0700501 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700502 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
503 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
504 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
505 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700506 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700507 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800508 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700509 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700510
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700511 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800512 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700513 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700514
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700515 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800516 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700517 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700518
Brian Carlstromf3632832014-05-20 15:36:53 -0700519 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700520 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700521 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700522
Brian Carlstromea46f952013-07-30 01:26:50 -0700523 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700524 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700525 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700526
Brian Carlstromea46f952013-07-30 01:26:50 -0700527 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700528 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700529 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700530
Ian Rogers23435d02012-09-24 11:23:12 -0700531 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700532
Ian Rogers23435d02012-09-24 11:23:12 -0700533 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800534 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700535 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
536
Brian Carlstrom1f870082011-08-23 16:02:11 -0700537 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700538 // finish initializing Reference class
539 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
540 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
541 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
542 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
543 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700544 mirror::Class* java_lang_ref_FinalizerReference =
545 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700546 java_lang_ref_FinalizerReference->SetAccessFlags(
547 java_lang_ref_FinalizerReference->GetAccessFlags() |
548 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700549 mirror::Class* java_lang_ref_PhantomReference =
550 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700551 java_lang_ref_PhantomReference->SetAccessFlags(
552 java_lang_ref_PhantomReference->GetAccessFlags() |
553 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700554 mirror::Class* java_lang_ref_SoftReference =
555 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700556 java_lang_ref_SoftReference->SetAccessFlags(
557 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700558 mirror::Class* java_lang_ref_WeakReference =
559 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700560 java_lang_ref_WeakReference->SetAccessFlags(
561 java_lang_ref_WeakReference->GetAccessFlags() |
562 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700563
Ian Rogers23435d02012-09-24 11:23:12 -0700564 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800565 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700566 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700567 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
568
jeffhao8cd6dda2012-02-22 10:15:34 -0800569 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700570 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800571 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800572 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700573 SetClassRoot(kJavaLangClassNotFoundException,
574 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800575 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700576 SetClassRoot(kJavaLangStackTraceElementArrayClass,
577 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800578 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700579
Andreas Gampe76bd8802014-12-10 16:43:58 -0800580 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
581 // initialized.
582 {
583 const DexFile& dex_file = java_lang_Object->GetDexFile();
584 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
585 CHECK(void_string_id != nullptr);
586 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
587 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
588 CHECK(void_type_id != nullptr);
589 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
590 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
591 // as referrer so the used dex cache is core's one.
592 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
593 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
594 self->AssertNoPendingException();
595 }
596
Ian Rogers98379392014-02-24 16:53:16 -0800597 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700598
Brian Carlstroma004aa92012-02-08 18:05:09 -0800599 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700600}
601
Ian Rogers98379392014-02-24 16:53:16 -0800602void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800603 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700604
605 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700606 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700607 // as the types of the field can't be resolved prior to the runtime being
608 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800609 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700610 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800611 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800612
Brian Carlstromea46f952013-07-30 01:26:50 -0700613 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700614 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
615 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700616
Brian Carlstromea46f952013-07-30 01:26:50 -0700617 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700618 CHECK_STREQ(queue->GetName(), "queue");
619 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700620
Brian Carlstromea46f952013-07-30 01:26:50 -0700621 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700622 CHECK_STREQ(queueNext->GetName(), "queueNext");
623 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700624
Brian Carlstromea46f952013-07-30 01:26:50 -0700625 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700626 CHECK_STREQ(referent->GetName(), "referent");
627 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700628
Brian Carlstromea46f952013-07-30 01:26:50 -0700629 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700630 CHECK_STREQ(zombie->GetName(), "zombie");
631 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700632
Brian Carlstroma663ea52011-08-19 23:33:41 -0700633 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700634 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700635 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800636 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700637 CHECK(klass != nullptr);
638 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700639 // note SetClassRoot does additional validation.
640 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700641 }
642
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700643 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700644
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700645 // disable the slow paths in FindClass and CreatePrimitiveClass now
646 // that Object, Class, and Object[] are setup
647 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700648
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800649 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700650}
651
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700652void ClassLinker::RunRootClinits() {
653 Thread* self = Thread::Current();
654 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800655 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700656 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700657 StackHandleScope<1> hs(self);
658 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700659 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700660 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700661 }
662 }
663}
664
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700665bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800666 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000667 const char* oat_cache_filename,
668 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700669 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700670 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800671
Ian Rogers1d54e732013-05-02 21:10:01 -0700672 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800673 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700674 if (heap->GetImageSpace() == nullptr) {
675 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
676 // out of space anyway it might not matter.
677 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
678 "without an image.", dex_filename);
679 return false;
680 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700681 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800682
Brian Carlstrom6449c622014-02-10 23:48:36 -0800683 std::string dex_file_option("--dex-file=");
684 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800685
Brian Carlstrom6449c622014-02-10 23:48:36 -0800686 std::string oat_fd_option("--oat-fd=");
687 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800688
Brian Carlstrom6449c622014-02-10 23:48:36 -0800689 std::string oat_location_option("--oat-location=");
690 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800691
Brian Carlstrom6449c622014-02-10 23:48:36 -0800692 std::vector<std::string> argv;
693 argv.push_back(dex2oat);
694 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800695 argv.push_back("-classpath");
696 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800697 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800698
Ian Rogers8afeb852014-04-02 14:55:49 -0700699 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800700
Jeff Hao4a200f52014-04-01 14:58:49 -0700701 if (!Runtime::Current()->IsVerificationEnabled()) {
702 argv.push_back("--compiler-filter=verify-none");
703 }
704
Alex Light6e183f22014-07-18 14:57:04 -0700705 if (Runtime::Current()->MustRelocateIfPossible()) {
706 argv.push_back("--runtime-arg");
707 argv.push_back("-Xrelocate");
708 } else {
709 argv.push_back("--runtime-arg");
710 argv.push_back("-Xnorelocate");
711 }
712
Brian Carlstrom6449c622014-02-10 23:48:36 -0800713 if (!kIsTargetBuild) {
714 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700715 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700716
Brian Carlstrom6449c622014-02-10 23:48:36 -0800717 argv.push_back(boot_image_option);
718 argv.push_back(dex_file_option);
719 argv.push_back(oat_fd_option);
720 argv.push_back(oat_location_option);
721 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800722 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800723 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700724 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800725
Andreas Gampea696c0a2014-12-10 20:51:45 -0800726 if (!Exec(argv, error_msg)) {
727 // Manually delete the file. Ensures there is no garbage left over if the process unexpectedly
728 // died. Ignore unlink failure, propagate the original error.
729 TEMP_FAILURE_RETRY(unlink(oat_cache_filename));
730 return false;
731 }
732
733 return true;
jeffhao262bf462011-10-20 18:36:32 -0700734}
735
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700736const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700737 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800738 if (kIsDebugBuild) {
739 for (size_t i = 0; i < oat_files_.size(); ++i) {
740 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700741 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800742 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700743 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
744 oat_files_.push_back(oat_file);
745 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800746}
747
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700748OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
749 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700750 OatFile* oat_file = space->ReleaseOatFile();
751 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700752 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700753 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700754}
755
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100756const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800757 const char* dex_location = dex_file.GetLocation().c_str();
758 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100759 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800760}
761
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100762const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
763 const char* dex_location,
764 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700765 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100766 for (const OatFile* oat_file : oat_files_) {
767 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700768
769 if (oat_location != nullptr) {
770 if (oat_file->GetLocation() != oat_location) {
771 continue;
772 }
773 }
774
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700775 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800776 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700777 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100778 if (oat_dex_file != nullptr) {
779 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800780 }
781 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100782 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800783}
784
Calin Juravle621962a2014-09-02 15:53:55 +0100785
786// Loads all multi dex files from the given oat file returning true on success.
787//
788// Parameters:
789// oat_file - the oat file to load from
790// dex_location - the dex location used to generate the oat file
791// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
792// generated - whether or not the oat_file existed before or was just (re)generated
793// error_msgs - any error messages will be appended here
794// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
795static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
796 const char* dex_location,
797 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700798 bool generated,
799 std::vector<std::string>* error_msgs,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800800 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700801 if (oat_file == nullptr) {
802 return false;
803 }
804
805 size_t old_size = dex_files->size(); // To rollback on error.
806
807 bool success = true;
808 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100809 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700810 const char* next_name = next_name_str.c_str();
811
Calin Juravle621962a2014-09-02 15:53:55 +0100812 uint32_t next_location_checksum;
813 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700814 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100815 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
816 // When i=0 the multidex name should be the same as the location name. We already have the
817 // checksum it so we don't need to recompute it.
818 if (dex_location_checksum == nullptr) {
819 next_location_checksum_pointer = nullptr;
820 } else {
821 next_location_checksum = *dex_location_checksum;
822 }
823 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700824 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100825 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700826 }
827
828 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
829
830 if (oat_dex_file == nullptr) {
831 if (i == 0 && generated) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700832 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100833 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700834 oat_file->GetLocation().c_str());
835 error_msgs->push_back(error_msg);
836 }
837 break; // Not found, done.
838 }
839
840 // Checksum test. Test must succeed when generated.
841 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100842 if (next_location_checksum_pointer != nullptr) {
843 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700844 }
845
846 if (success) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800847 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
848 if (dex_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700849 success = false;
850 error_msgs->push_back(error_msg);
851 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800852 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700853 }
854 }
855
856 // When we generated the file, we expect success, or something is terribly wrong.
857 CHECK_EQ(false, generated && !success)
858 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100859 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700860 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
861 }
862
863 if (dex_files->size() == old_size) {
864 success = false; // We did not even find classes.dex
865 }
866
867 if (success) {
868 return true;
869 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800870 dex_files->erase(dex_files->begin() + old_size, dex_files->end());
Andreas Gampe833a4852014-05-21 18:46:59 -0700871 return false;
872 }
873}
874
875// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
876// complicates the loading process, as we should not use an iterative loading process, because that
877// would register the oat file and dex files that come before the broken one. Instead, check all
878// multidex ahead of time.
879bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
880 std::vector<std::string>* error_msgs,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800881 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700882 // 1) Check whether we have an open oat file.
883 // This requires a dex checksum, use the "primary" one.
884 uint32_t dex_location_checksum;
885 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
886 bool have_checksum = true;
887 std::string checksum_error_msg;
888 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100889 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700890 dex_location_checksum_pointer = nullptr;
891 have_checksum = false;
892 }
893
894 bool needs_registering = false;
895
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100896 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
897 dex_location_checksum_pointer);
898 std::unique_ptr<const OatFile> open_oat_file(
899 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700900
901 // 2) If we do not have an open one, maybe there's one on disk already.
902
903 // In case the oat file is not open, we play a locking game here so
904 // that if two different processes race to load and register or generate
905 // (or worse, one tries to open a partial generated file) we will be okay.
906 // This is actually common with apps that use DexClassLoader to work
907 // around the dex method reference limit and that have a background
908 // service running in a separate process.
909 ScopedFlock scoped_flock;
910
911 if (open_oat_file.get() == nullptr) {
912 if (oat_location != nullptr) {
913 // Can only do this if we have a checksum, else error.
914 if (!have_checksum) {
915 error_msgs->push_back(checksum_error_msg);
916 return false;
917 }
918
919 std::string error_msg;
920
921 // We are loading or creating one in the future. Time to set up the file lock.
922 if (!scoped_flock.Init(oat_location, &error_msg)) {
923 error_msgs->push_back(error_msg);
924 return false;
925 }
926
Alex Lighta59dd802014-07-02 16:28:08 -0700927 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700928 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
929 oat_location, &error_msg));
930
931 if (open_oat_file.get() == nullptr) {
932 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
933 dex_location, oat_location, error_msg.c_str());
934 VLOG(class_linker) << compound_msg;
935 error_msgs->push_back(compound_msg);
936 }
937 } else {
938 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100939 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700940 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
941 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100942 kRuntimeISA, error_msgs,
943 &obsolete_file_cleanup_failed));
944 // There's no point in going forward and eventually try to regenerate the
945 // file if we couldn't remove the obsolete one. Mostly likely we will fail
946 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100947 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
948 if (obsolete_file_cleanup_failed) {
949 return false;
950 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700951 }
952 needs_registering = true;
953 }
954
955 // 3) If we have an oat file, check all contained multidex files for our dex_location.
956 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100957 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
958 dex_location_checksum_pointer,
959 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700960 if (success) {
961 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
962 if (needs_registering) {
963 // We opened the oat file, so we must register it.
964 RegisterOatFile(oat_file);
965 }
Alex Light9dcc4572014-08-14 14:16:26 -0700966 // If the file isn't executable we failed patchoat but did manage to get the dex files.
967 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700968 } else {
969 if (needs_registering) {
970 // We opened it, delete it.
971 open_oat_file.reset();
972 } else {
973 open_oat_file.release(); // Do not delete open oat files.
974 }
975 }
976
977 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
978
979 // Need a checksum, fail else.
980 if (!have_checksum) {
981 error_msgs->push_back(checksum_error_msg);
982 return false;
983 }
984
985 // Look in cache location if no oat_location is given.
986 std::string cache_location;
987 if (oat_location == nullptr) {
988 // Use the dalvik cache.
989 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
990 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
991 oat_location = cache_location.c_str();
992 }
993
Alex Light64ad14d2014-08-19 14:23:13 -0700994 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700995 // Definitely need to lock now.
996 if (!scoped_flock.HasFile()) {
997 std::string error_msg;
998 if (!scoped_flock.Init(oat_location, &error_msg)) {
999 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -07001000 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -07001001 }
1002 }
1003
Alex Light64ad14d2014-08-19 14:23:13 -07001004 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001005 // Create the oat file.
1006 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1007 oat_location, error_msgs));
1008 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001009
1010 // Failed, bail.
1011 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001012 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -07001013 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
1014 std::string error_msg;
1015 if (!DexFile::Open(dex_location, dex_location, &error_msg, dex_files)) {
1016 error_msgs->push_back(error_msg);
1017 }
1018 } else {
1019 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
1020 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001021 return false;
1022 }
1023
1024 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001025 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1026 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001027 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001028 if (success) {
1029 RegisterOatFile(open_oat_file.release());
1030 return true;
1031 } else {
1032 return false;
1033 }
1034}
1035
1036const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1037 uint32_t dex_location_checksum,
1038 const char* oat_location,
1039 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001040 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001041 !Runtime::Current()->IsAotCompiler(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001042 if (oat_file.get() == nullptr) {
1043 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1044 error_msg->c_str());
1045 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001046 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001047 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001048 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1049 if (image_space != nullptr) {
1050 const ImageHeader& image_header = image_space->GetImageHeader();
1051 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1052 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1053 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1054 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1055 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1056 actual_image_oat_checksum);
1057 return nullptr;
1058 }
1059
1060 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1061 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1062 if (expected_image_oat_offset != actual_image_oat_offset) {
1063 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1064 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1065 actual_image_oat_offset);
1066 return nullptr;
1067 }
1068 int32_t expected_patch_delta = image_header.GetPatchDelta();
1069 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1070 if (expected_patch_delta != actual_patch_delta) {
1071 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1072 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1073 return nullptr;
1074 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001075 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001076
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001077 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1078 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001079 if (oat_dex_file == nullptr) {
1080 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1081 dex_location);
1082 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001083 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001084 uint32_t expected_dex_checksum = dex_location_checksum;
1085 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1086 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001087 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1088 "found 0x%x", oat_location, expected_dex_checksum,
1089 actual_dex_checksum);
1090 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001091 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001092 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1093 if (dex_file.get() != nullptr) {
1094 return oat_file.release();
1095 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001096 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001097 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001098}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001099
Andreas Gampe833a4852014-05-21 18:46:59 -07001100const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1101 int fd, const char* oat_location,
1102 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001103 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001104 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001105 std::string error_msg;
1106 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001107 CHECK(!error_msg.empty());
1108 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001109 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001110 }
Igor Murashkin46774762014-10-22 11:37:02 -07001111 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001112 !Runtime::Current()->IsAotCompiler(),
1113 &error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001114 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001115 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1116 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001117 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001118 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001119 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001120
1121 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001122}
1123
Alex Light6e183f22014-07-18 14:57:04 -07001124bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1125 const InstructionSet instruction_set) {
1126 Runtime* runtime = Runtime::Current();
1127 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001128 if (image_space == nullptr) {
1129 return false;
1130 }
Alex Light6e183f22014-07-18 14:57:04 -07001131 uint32_t image_oat_checksum = 0;
1132 if (instruction_set == kRuntimeISA) {
1133 const ImageHeader& image_header = image_space->GetImageHeader();
1134 image_oat_checksum = image_header.GetOatChecksum();
1135 } else {
1136 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1137 image_space->GetImageLocation().c_str(), instruction_set));
1138 image_oat_checksum = image_header->GetOatChecksum();
1139 }
1140 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1141}
1142
1143bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1144 const InstructionSet instruction_set,
1145 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001146 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001147 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001148 if (image_space == nullptr) {
1149 *error_msg = "No image space for verification against";
1150 return false;
1151 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001152
1153 // If the requested instruction set is the same as the current runtime,
1154 // we can use the checksums directly. If it isn't, we'll have to read the
1155 // image header from the image for the right instruction set.
1156 uint32_t image_oat_checksum = 0;
1157 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001158 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001159 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001160 const ImageHeader& image_header = image_space->GetImageHeader();
1161 image_oat_checksum = image_header.GetOatChecksum();
1162 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001163 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001164 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001165 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001166 image_space->GetImageLocation().c_str(), instruction_set));
1167 image_oat_checksum = image_header->GetOatChecksum();
1168 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001169 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001170 }
1171 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin96e83932014-10-29 19:45:42 -07001172 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1173
1174 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1175 if (!oat_file->IsPic()) {
1176 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1177 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1178 }
Alex Light6e183f22014-07-18 14:57:04 -07001179 if (!ret) {
1180 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1181 oat_file->GetLocation().c_str(),
1182 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1183 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1184 oat_file->GetOatHeader().GetImagePatchDelta(),
1185 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1186 }
1187 return ret;
1188}
1189
1190bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1191 const char* dex_location,
1192 uint32_t dex_location_checksum,
1193 const InstructionSet instruction_set,
1194 std::string* error_msg) {
1195 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1196 return false;
1197 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001198
Brian Carlstromf3632832014-05-20 15:36:53 -07001199 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1200 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001201 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001202 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1203 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001204 for (const OatFile::OatDexFile* oat_dex_file_in : oat_file->GetOatDexFiles()) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001205 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001206 oat_file->GetLocation().c_str(),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001207 oat_dex_file_in->GetDexFileLocation().c_str(),
1208 oat_dex_file_in->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001209 }
1210 return false;
1211 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001212
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001213 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001214 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001215}
1216
Alex Lighta59dd802014-07-02 16:28:08 -07001217bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1218 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001219 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001220 std::string* error_msg) {
1221 CHECK(oat_file != nullptr);
1222 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001223 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001224 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001225 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1226 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1227 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001228 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001229 if (oat_dex_file == nullptr) {
1230 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001231 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001232 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001233 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001234 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001235 dex_file = oat_dex_file->OpenDexFile(error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001236 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001237 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001238 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001239 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001240 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001241 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001242 dex_file = oat_file->GetOatDexFile(dex_location,
1243 dex_location_checksum)->OpenDexFile(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001244 }
Alex Lighta59dd802014-07-02 16:28:08 -07001245 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001246}
1247
Andreas Gampe833a4852014-05-21 18:46:59 -07001248const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001249 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001250 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001251 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001252 std::vector<std::string>* error_msgs,
1253 bool* obsolete_file_cleanup_failed) {
1254 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001255 bool already_opened = false;
1256 std::string dex_location_str(dex_location);
1257 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1258 &already_opened,
1259 obsolete_file_cleanup_failed,
1260 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001261 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001262 if (oat_file.get() == nullptr) {
1263 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1264 dex_location));
1265 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001266 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001267 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1268 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001269 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1270 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001271 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001272 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001273 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001274 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001275 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1276 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1277 "dex location '%s'. Image checksum incorrect.",
1278 oat_file->GetLocation().c_str(), dex_location));
1279 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001280 } else {
1281 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001282 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001283}
1284
Brian Carlstromae826982011-11-09 01:33:42 -08001285const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001286 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001287 for (size_t i = 0; i < oat_files_.size(); i++) {
1288 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001289 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001290 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001291 return oat_file;
1292 }
1293 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001294 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001295}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001296
Alex Lighta59dd802014-07-02 16:28:08 -07001297const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1298 InstructionSet isa,
1299 bool *already_opened,
1300 bool *obsolete_file_cleanup_failed,
1301 std::vector<std::string>* error_msgs) {
1302 // Find out if we've already opened the file
1303 const OatFile* ret = nullptr;
1304 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1305 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1306 if (ret != nullptr) {
1307 *already_opened = true;
1308 return ret;
1309 }
1310
1311 std::string dalvik_cache;
1312 bool have_android_data = false;
1313 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001314 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001315 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001316 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001317 std::string cache_filename;
1318 if (have_dalvik_cache) {
1319 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1320 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1321 if (ret != nullptr) {
1322 *already_opened = true;
1323 return ret;
1324 }
1325 } else {
1326 // If we need to relocate we should just place odex back where it started.
1327 cache_filename = odex_filename;
1328 }
1329
1330 ret = nullptr;
1331
1332 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1333 //
1334 // Now we do the following:
1335 // 1) Try and open the odex version
1336 // 2) If present, checksum-verified & relocated correctly return it
1337 // 3) Close the odex version to free up its address space.
1338 // 4) Try and open the cache version
1339 // 5) If present, checksum-verified & relocated correctly return it
1340 // 6) Close the cache version to free up its address space.
1341 // 7) If we should relocate:
1342 // a) If we have opened and checksum-verified the odex version relocate it to
1343 // 'cache_filename' and return it
1344 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1345 // it. This should not happen often (I think only the run-test's will hit this case).
1346 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1347 // this point.
1348 // 9) Return nullptr
1349
1350 *already_opened = false;
1351 const Runtime* runtime = Runtime::Current();
1352 CHECK(runtime != nullptr);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001353 bool executable = !runtime->IsAotCompiler();
Alex Lighta59dd802014-07-02 16:28:08 -07001354
1355 std::string odex_error_msg;
1356 bool should_patch_system = false;
1357 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001358 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001359 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001360 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001361 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001362 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001363 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001364 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001365 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001366 &odex_checksum_verified,
1367 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001368 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001369 } else {
1370 if (odex_checksum_verified) {
1371 // We can just relocate
1372 should_patch_system = true;
1373 odex_error_msg = "Image Patches are incorrect";
1374 }
1375 if (odex_oat_file.get() != nullptr) {
1376 have_system_odex = true;
1377 }
Alex Lighta59dd802014-07-02 16:28:08 -07001378 }
1379 }
1380
Alex Lighta59dd802014-07-02 16:28:08 -07001381 std::string cache_error_msg;
1382 bool should_patch_cache = false;
1383 bool cache_checksum_verified = false;
1384 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001385 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001386 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001387 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001388 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001389 &cache_checksum_verified,
1390 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001391 return cache_oat_file.release();
1392 } else if (cache_checksum_verified) {
1393 // We can just relocate
1394 should_patch_cache = true;
1395 cache_error_msg = "Image Patches are incorrect";
1396 }
1397 } else if (have_android_data) {
1398 // dalvik_cache does not exist but android data does. This means we should be able to create
1399 // it, so we should try.
1400 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1401 }
1402
1403 ret = nullptr;
1404 std::string error_msg;
1405 if (runtime->CanRelocate()) {
1406 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001407 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1408 if (space != nullptr) {
1409 const std::string& image_location = space->GetImageLocation();
1410 if (odex_checksum_verified && should_patch_system) {
1411 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1412 } else if (cache_checksum_verified && should_patch_cache) {
1413 CHECK(have_dalvik_cache);
1414 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1415 }
Alex Light84d76052014-08-22 17:49:35 -07001416 } else if (have_system_odex) {
1417 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001418 }
1419 }
1420 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1421 // implicitly: were able to fine where the cached version is but we were unable to use it,
1422 // either as a destination for relocation or to open a file. We should delete it if it is
1423 // there.
1424 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1425 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1426 "searching for dex file %s: %s",
1427 cache_filename.c_str(), dex_location.c_str(),
1428 strerror(errno));
1429 error_msgs->push_back(rm_error_msg);
1430 VLOG(class_linker) << rm_error_msg;
1431 // Let the caller know that we couldn't remove the obsolete file.
1432 // This is a good indication that further writes may fail as well.
1433 *obsolete_file_cleanup_failed = true;
1434 }
1435 }
1436 if (ret == nullptr) {
1437 VLOG(class_linker) << error_msg;
1438 error_msgs->push_back(error_msg);
1439 std::string relocation_msg;
1440 if (runtime->CanRelocate()) {
1441 relocation_msg = StringPrintf(" and relocation failed");
1442 }
1443 if (have_dalvik_cache && cache_checksum_verified) {
1444 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1445 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1446 cache_filename.c_str(), cache_error_msg.c_str(),
1447 relocation_msg.c_str());
1448 } else {
1449 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1450 "dalvik_cache availible)%s.", odex_filename.c_str(),
1451 odex_error_msg.c_str(), relocation_msg.c_str());
1452 }
1453 VLOG(class_linker) << error_msg;
1454 error_msgs->push_back(error_msg);
1455 }
1456 return ret;
1457}
1458
Alex Light9dcc4572014-08-14 14:16:26 -07001459const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1460 InstructionSet isa,
1461 std::string* error_msg) {
1462 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001463 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001464 if (output.get() == nullptr) {
1465 return nullptr;
1466 }
Alex Light84d76052014-08-22 17:49:35 -07001467 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1468 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001469 return output.release();
1470 } else {
1471 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1472 oat_path.c_str());
1473 return nullptr;
1474 }
1475}
1476
Alex Lighta59dd802014-07-02 16:28:08 -07001477const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1478 const std::string& output_oat,
1479 const std::string& image_location,
1480 InstructionSet isa,
1481 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001482 Runtime* runtime = Runtime::Current();
1483 DCHECK(runtime != nullptr);
1484 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001485 // We don't have an image space so there is no point in trying to patchoat.
1486 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1487 << "running without an image. Attempting to use oat file for interpretation.";
1488 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1489 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001490 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001491 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1492 // input_oat but make sure we only do interpretation on it's dex files.
1493 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1494 << "disabled. Attempting to use oat file for interpretation";
1495 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1496 }
Alex Lighta59dd802014-07-02 16:28:08 -07001497 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001498 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001499
1500 std::string isa_arg("--instruction-set=");
1501 isa_arg += GetInstructionSetString(isa);
1502 std::string input_oat_filename_arg("--input-oat-file=");
1503 input_oat_filename_arg += input_oat;
1504 std::string output_oat_filename_arg("--output-oat-file=");
1505 output_oat_filename_arg += output_oat;
1506 std::string patched_image_arg("--patched-image-location=");
1507 patched_image_arg += image_location;
1508
1509 std::vector<std::string> argv;
1510 argv.push_back(patchoat);
1511 argv.push_back(isa_arg);
1512 argv.push_back(input_oat_filename_arg);
1513 argv.push_back(output_oat_filename_arg);
1514 argv.push_back(patched_image_arg);
1515
1516 std::string command_line(Join(argv, ' '));
1517 LOG(INFO) << "Relocate Oat File: " << command_line;
1518 bool success = Exec(argv, error_msg);
1519 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001520 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001521 !runtime->IsAotCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001522 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001523 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1524 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001525 return output.release();
1526 } else if (output.get() != nullptr) {
1527 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1528 "but output file '%s' failed verifcation: %s",
1529 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1530 } else {
1531 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1532 "but was unable to open output file '%s': %s",
1533 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1534 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001535 } else if (!runtime->IsAotCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001536 // patchoat failed which means we probably don't have enough room to place the output oat file,
1537 // instead of failing we should just run the interpreter from the dex files in the input oat.
1538 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1539 << "for interpretation. patchoat failure was: " << *error_msg;
1540 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001541 } else {
1542 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1543 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1544 error_msg->c_str());
1545 }
1546 return nullptr;
1547}
1548
Andreas Gampe7ba64962014-10-23 11:37:40 -07001549bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001550 bool* checksum_verified,
1551 std::string* error_msg) {
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
Andreas Gampe7ba64962014-10-23 11:37:40 -07001583 bool offset_verified;
1584 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001585
Andreas Gampe7ba64962014-10-23 11:37:40 -07001586 if (!oat_file->IsPic()) {
1587 // If an oat file is not PIC, we need to check that the image is at the expected location and
1588 // patched in the same way.
1589 void* oat_image_oat_offset =
1590 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1591 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1592 if (!offset_verified) {
1593 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1594 real_image_oat_offset, oat_image_oat_offset);
1595 }
1596
1597 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1598 patch_delta_verified = oat_patch_delta == real_patch_delta;
1599 if (!patch_delta_verified) {
1600 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1601 "received 0x%x)", real_patch_delta, oat_patch_delta);
1602 }
1603 } else {
1604 // If an oat file is PIC, we ignore offset and patching delta.
1605 offset_verified = true;
1606 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001607 }
1608
1609 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001610 if (!ret) {
1611 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001612 }
1613 return ret;
1614}
1615
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001616const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1617 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001618 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001619 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001620 return oat_file;
1621 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001622 return OatFile::Open(oat_location, oat_location, nullptr, nullptr,
1623 !Runtime::Current()->IsAotCompiler(), error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001624}
1625
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001626void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001627 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001628 DCHECK(obj != nullptr);
1629 DCHECK(class_linker != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001630 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001631 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001632 if (!method->IsNative()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001633 const size_t pointer_size = class_linker->image_pointer_size_;
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001634 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001635 if (!method->IsRuntimeMethod() && method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001636 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1637 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001638 }
1639 }
1640 }
1641}
1642
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001643void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001644 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001645 CHECK(!init_done_);
1646
Mathieu Chartier590fee92013-09-13 13:46:47 -07001647 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001648 gc::Heap* heap = Runtime::Current()->GetHeap();
1649 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001650 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001651 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001652 OatFile& oat_file = GetImageOatFile(space);
1653 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1654 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001655 const char* image_file_location = oat_file.GetOatHeader().
1656 GetStoreValueByKey(OatHeader::kImageLocationKey);
1657 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001658 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001659 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001660 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001661 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001662 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1663 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1664 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001665
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001666 StackHandleScope<1> hs(self);
1667 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1668 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1669 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001670 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001671
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001672 // Special case of setting up the String class early so that we can test arbitrary objects
1673 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001674 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001675
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001676 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001677 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001678 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001679 StackHandleScope<1> hs2(self);
1680 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001681 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001682 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1683 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001684 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001685 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001686 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
1687 if (dex_file.get() == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001688 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001689 << " from within oat file " << oat_file.GetLocation()
1690 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -08001691 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001692 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001693
1694 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1695
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001696 AppendToBootClassPath(*dex_file.get(), dex_cache);
1697 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001698 }
1699
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001700 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1701 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001702 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001703 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001704 if (!Runtime::Current()->IsAotCompiler()) {
1705 // Aot compiler supports having an image with a different pointer size than the runtime. This
Mathieu Chartier2d721012014-11-10 11:08:06 -08001706 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
1707 // also use 32 bit dex2oat on a system with 64 bit apps.
1708 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
1709 << sizeof(void*);
1710 }
1711 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
1712 image_pointer_size_ = 4;
1713 } else {
1714 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
1715 image_pointer_size_ = 8;
1716 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001717
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001718 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001719 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001720 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001721 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001722 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001723
1724 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001725 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001726 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001727
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001728 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001729 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001730 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001731 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001732 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001733 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001734 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1735 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1736 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1737 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1738 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1739 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1740 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1741 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1742 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1743 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001744
Ian Rogers98379392014-02-24 16:53:16 -08001745 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001746
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001747 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001748}
1749
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001750void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1751 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1752 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001753 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001754 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001755 }
1756 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001757 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001758 }
1759 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001760 for (auto& root : new_class_roots_) {
1761 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001762 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001763 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001764 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001765 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1766 // corresponding object. This is slow, but luckily for us, this may only happen with a
1767 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001768 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001769 DCHECK(it != class_table_.end());
1770 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001771 }
1772 }
1773 }
1774 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1775 new_class_roots_.clear();
1776 }
1777 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1778 log_new_class_table_roots_ = true;
1779 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1780 log_new_class_table_roots_ = false;
1781 }
1782 // We deliberately ignore the class roots in the image since we
1783 // handle image roots by using the MS/CMS rescanning of dirty cards.
1784}
1785
Brian Carlstroma663ea52011-08-19 23:33:41 -07001786// Keep in sync with InitCallback. Anything we visit, we need to
1787// reinit references to when reinitializing a ClassLinker from a
1788// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001789void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001790 class_roots_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers50b35e22012-10-04 10:09:15 -07001791 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001792 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001793 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001794 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001795 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001796 dex_cache.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001797 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001798 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1799 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001800 dex_caches_[index].VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001801 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001802 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001803 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1804 new_dex_cache_roots_.clear();
1805 }
1806 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1807 log_new_dex_caches_roots_ = true;
1808 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1809 log_new_dex_caches_roots_ = false;
1810 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001811 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001812 VisitClassRoots(callback, arg, flags);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001813 array_iftable_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001814 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001815 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001816 find_array_class_cache_[i].VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001817 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001818}
1819
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001820void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1821 if (dex_cache_image_class_lookup_required_) {
1822 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001823 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001824 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001825 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001826 for (GcRoot<mirror::Class>& root : class_table_) {
1827 if (!visitor(root.Read(), arg)) {
1828 return;
1829 }
1830 }
1831 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1832 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001833 return;
1834 }
1835 }
1836}
1837
Ian Rogersdbf3be02014-08-29 15:40:08 -07001838static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001839 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001840 classes->insert(c);
1841 return true;
1842}
1843
Ian Rogersdbf3be02014-08-29 15:40:08 -07001844struct GetClassesVisitorArrayArg {
1845 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1846 int32_t index;
1847 bool success;
1848};
1849
1850static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1851 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1852 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1853 if (arg->index < (*arg->classes)->GetLength()) {
1854 (*arg->classes)->Set(arg->index, c);
1855 arg->index++;
1856 return true;
1857 } else {
1858 arg->success = false;
1859 return false;
1860 }
1861}
1862
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001863void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001864 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1865 // is avoiding duplicates.
1866 if (!kMovingClasses) {
1867 std::set<mirror::Class*> classes;
1868 VisitClasses(GetClassesVisitorSet, &classes);
1869 for (mirror::Class* klass : classes) {
1870 if (!visitor(klass, arg)) {
1871 return;
1872 }
1873 }
1874 } else {
1875 Thread* self = Thread::Current();
1876 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001877 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001878 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1879 GetClassesVisitorArrayArg local_arg;
1880 local_arg.classes = &classes;
1881 local_arg.success = false;
1882 // We size the array assuming classes won't be added to the class table during the visit.
1883 // If this assumption fails we iterate again.
1884 while (!local_arg.success) {
1885 size_t class_table_size;
1886 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001887 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001888 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001889 }
1890 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1891 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1892 classes.Assign(
1893 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1894 CHECK(classes.Get() != nullptr); // OOME.
1895 local_arg.index = 0;
1896 local_arg.success = true;
1897 VisitClasses(GetClassesVisitorArray, &local_arg);
1898 }
1899 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1900 // If the class table shrank during creation of the clases array we expect null elements. If
1901 // the class table grew then the loop repeats. If classes are created after the loop has
1902 // finished then we don't visit.
1903 mirror::Class* klass = classes->Get(i);
1904 if (klass != nullptr && !visitor(klass, arg)) {
1905 return;
1906 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001907 }
1908 }
1909}
1910
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001911ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001912 mirror::Class::ResetClass();
1913 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001914 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001915 mirror::ArtField::ResetClass();
1916 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001917 mirror::BooleanArray::ResetArrayClass();
1918 mirror::ByteArray::ResetArrayClass();
1919 mirror::CharArray::ResetArrayClass();
1920 mirror::DoubleArray::ResetArrayClass();
1921 mirror::FloatArray::ResetArrayClass();
1922 mirror::IntArray::ResetArrayClass();
1923 mirror::LongArray::ResetArrayClass();
1924 mirror::ShortArray::ResetArrayClass();
1925 mirror::Throwable::ResetClass();
1926 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001927 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001928}
1929
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001930mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001931 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001932 StackHandleScope<16> hs(self);
1933 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1934 Handle<mirror::DexCache> dex_cache(
1935 hs.NewHandle(down_cast<mirror::DexCache*>(
1936 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1937 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001938 if (dex_cache.Get() == nullptr) {
1939 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001940 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001941 Handle<mirror::String>
1942 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001943 if (location.Get() == nullptr) {
1944 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001945 }
Ian Rogers700a4022014-05-19 16:49:03 -07001946 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001947 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001948 if (strings.Get() == nullptr) {
1949 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001950 }
Ian Rogers700a4022014-05-19 16:49:03 -07001951 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001952 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001953 if (types.Get() == nullptr) {
1954 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001955 }
Ian Rogers700a4022014-05-19 16:49:03 -07001956 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001957 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001958 if (methods.Get() == nullptr) {
1959 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001960 }
Ian Rogers700a4022014-05-19 16:49:03 -07001961 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001962 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001963 if (fields.Get() == nullptr) {
1964 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001965 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001966 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1967 fields.Get());
1968 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001969}
1970
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001971mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001972 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001973 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001974 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001975 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001976 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001977 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1978 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001979 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001980 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001981 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001982 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001983 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001984}
1985
Ian Rogers6fac4472014-02-25 17:01:10 -08001986mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001987 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001988}
1989
Brian Carlstromea46f952013-07-30 01:26:50 -07001990mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001991 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001992 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001993}
1994
Brian Carlstromea46f952013-07-30 01:26:50 -07001995mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001996 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001997 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001998}
1999
Mathieu Chartier590fee92013-09-13 13:46:47 -07002000mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
2001 Thread* self, size_t length) {
2002 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2003 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002004}
2005
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002006mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
2007 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002008 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002009
2010 // For temporary classes we must wait for them to be retired.
2011 if (init_done_ && klass->IsTemp()) {
2012 CHECK(!klass->IsResolved());
2013 if (klass->IsErroneous()) {
2014 ThrowEarlierClassFailure(klass);
2015 return nullptr;
2016 }
2017 StackHandleScope<1> hs(self);
2018 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2019 ObjectLock<mirror::Class> lock(self, h_class);
2020 // Loop and wait for the resolving thread to retire this class.
2021 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2022 lock.WaitIgnoringInterrupts();
2023 }
2024 if (h_class->IsErroneous()) {
2025 ThrowEarlierClassFailure(h_class.Get());
2026 return nullptr;
2027 }
2028 CHECK(h_class->IsRetired());
2029 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002030 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2031 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002032 }
2033
Brian Carlstromaded5f72011-10-07 17:15:04 -07002034 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002035 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002036 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002037 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2038 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002039 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002040 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2041 ThrowClassCircularityError(h_class.Get());
2042 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002043 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002044 }
2045 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002046 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002047 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002048 }
2049 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002050
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002051 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002052 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002053 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002054 }
2055 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002056 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002057 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002058 return klass;
2059}
2060
Ian Rogers68b56852014-08-29 20:19:11 -07002061typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2062
2063// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002064ClassPathEntry FindInClassPath(const char* descriptor,
2065 size_t hash, const std::vector<const DexFile*>& class_path) {
2066 for (const DexFile* dex_file : class_path) {
2067 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002068 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002069 return ClassPathEntry(dex_file, dex_class_def);
2070 }
2071 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002072 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002073}
2074
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002075mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2076 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002077 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002078 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08002079 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002080 if (class_loader->GetClass() !=
2081 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2082 class_loader->GetParent()->GetClass() !=
2083 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2084 return nullptr;
2085 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002086 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002087 // Check if this would be found in the parent boot class loader.
2088 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002089 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002090 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08002091 // May return null if resolution on another thread fails.
2092 klass = EnsureResolved(self, descriptor, klass);
2093 } else {
2094 // May OOME.
2095 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2096 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002097 }
Ian Rogers32427292014-11-19 14:05:21 -08002098 if (klass == nullptr) {
2099 CHECK(self->IsExceptionPending()) << descriptor;
2100 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002101 }
Ian Rogers32427292014-11-19 14:05:21 -08002102 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002103 } else {
Ian Rogers32427292014-11-19 14:05:21 -08002104 // Handle as if this is the child PathClassLoader.
2105 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002106 StackHandleScope<3> hs(self);
2107 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2108 // We need to get the DexPathList and loop through it.
2109 Handle<mirror::ArtField> cookie_field =
2110 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2111 Handle<mirror::ArtField> dex_file_field =
2112 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002113 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002114 mirror::Object* dex_path_list =
2115 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2116 GetObject(class_loader.Get());
2117 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2118 cookie_field.Get() != nullptr) {
2119 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2120 mirror::Object* dex_elements_obj =
2121 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2122 GetObject(dex_path_list);
2123 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2124 // at the mCookie which is a DexFile vector.
2125 if (dex_elements_obj != nullptr) {
2126 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2127 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2128 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2129 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2130 if (element == nullptr) {
2131 // Should never happen, fall back to java code to throw a NPE.
2132 break;
2133 }
2134 mirror::Object* dex_file = dex_file_field->GetObject(element);
2135 if (dex_file != nullptr) {
Andreas Gampe324b9bb2015-02-23 16:33:22 -08002136 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
2137 if (long_array == nullptr) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002138 // This should never happen so log a warning.
2139 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2140 break;
2141 }
Andreas Gampe324b9bb2015-02-23 16:33:22 -08002142 int32_t long_array_size = long_array->GetLength();
2143 for (int32_t j = 0; j < long_array_size; ++j) {
2144 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
2145 long_array->GetWithoutChecks(j)));
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002146 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002147 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002148 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002149 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2150 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002151 if (klass == nullptr) {
2152 CHECK(self->IsExceptionPending()) << descriptor;
2153 self->ClearException();
2154 return nullptr;
2155 }
2156 return klass;
2157 }
2158 }
2159 }
2160 }
2161 }
2162 }
Ian Rogers32427292014-11-19 14:05:21 -08002163 self->AssertNoPendingException();
2164 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002165 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002166}
2167
Ian Rogers98379392014-02-24 16:53:16 -08002168mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002169 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002170 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002171 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002172 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002173 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002174 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2175 // for primitive classes that aren't backed by dex files.
2176 return FindPrimitiveClass(descriptor[0]);
2177 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002178 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002179 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002180 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002181 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002182 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002183 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002184 // Class is not yet loaded.
2185 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002186 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002187 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002188 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002189 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002190 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002191 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002192 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002193 } else {
2194 // The boot class loader is searched ahead of the application class loader, failures are
2195 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2196 // trigger the chaining with a proper stack trace.
2197 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002198 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002199 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002200 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002201 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002202 // First try with the bootstrap class loader.
2203 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002204 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002205 if (klass != nullptr) {
2206 return EnsureResolved(self, descriptor, klass);
2207 }
2208 }
Ian Rogers63557452014-06-04 16:57:15 -07002209 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2210 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002211 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002212 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002213 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002214 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002215 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002216 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002217 const std::vector<const DexFile*>* class_path;
2218 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002219 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002220 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002221 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002222 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2223 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002224 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07002225 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002226 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07002227 } else {
2228 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2229 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002230 self->SetException(pre_allocated);
Ian Rogers7b078e82014-09-10 14:44:24 -07002231 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002232 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002233 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002234 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002235 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2236 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002237 if (cp_klass != nullptr) {
2238 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002239 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002240 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002241 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002242 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002243 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002244 {
2245 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002246 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2247 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002248 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002249 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002250 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002251 }
Ian Rogers68b56852014-08-29 20:19:11 -07002252 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002253 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2254 WellKnownClasses::java_lang_ClassLoader_loadClass,
2255 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002256 }
Ian Rogers98379392014-02-24 16:53:16 -08002257 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002258 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002259 return nullptr;
2260 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002261 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002262 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002263 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002264 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002265 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002266 // success, return mirror::Class*
2267 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002268 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002269 }
Ian Rogers07140832014-09-30 15:43:59 -07002270 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002271}
2272
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002273mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002274 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002275 const DexFile& dex_file,
2276 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002277 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002278 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002279
Brian Carlstromaded5f72011-10-07 17:15:04 -07002280 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002281 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002282 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002283 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002284 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002285 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002286 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002287 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002288 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002289 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2290 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002291 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002292 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002293 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002294 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002295 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002296 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002297 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002298 }
2299
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002300 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002301 // Allocate a class with the status of not ready.
2302 // Interface object should get the right size here. Regular class will
2303 // figure out the right size later and be replaced with one of the right
2304 // size when the class becomes resolved.
2305 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002306 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002307 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002308 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002309 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002310 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002311 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002312 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002313 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002314 if (self->IsExceptionPending()) {
2315 // An exception occured during load, set status to erroneous while holding klass' lock in case
2316 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002317 if (!klass->IsErroneous()) {
2318 klass->SetStatus(mirror::Class::kStatusError, self);
2319 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002320 return nullptr;
2321 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002322 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002323
Mathieu Chartier590fee92013-09-13 13:46:47 -07002324 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002325 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002326 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002327 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2328 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002329 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002330 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002331
Brian Carlstromaded5f72011-10-07 17:15:04 -07002332 // Finish loading (if necessary) by finding parents
2333 CHECK(!klass->IsLoaded());
2334 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2335 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002336 if (!klass->IsErroneous()) {
2337 klass->SetStatus(mirror::Class::kStatusError, self);
2338 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002339 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002340 }
2341 CHECK(klass->IsLoaded());
2342 // Link the class (if necessary)
2343 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002344 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002345 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002346
2347 mirror::Class* new_class = nullptr;
2348 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002349 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002350 if (!klass->IsErroneous()) {
2351 klass->SetStatus(mirror::Class::kStatusError, self);
2352 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002353 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002354 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002355 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002356 CHECK(new_class != nullptr) << descriptor;
2357 CHECK(new_class->IsResolved()) << descriptor;
2358
2359 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002360
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002361 // Instrumentation may have updated entrypoints for all methods of all
2362 // classes. However it could not update methods of this class while we
2363 // were loading it. Now the class is resolved, we can update entrypoints
2364 // as required by instrumentation.
2365 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2366 // We must be in the kRunnable state to prevent instrumentation from
2367 // suspending all threads to update entrypoints while we are doing it
2368 // for this class.
2369 DCHECK_EQ(self->GetState(), kRunnable);
2370 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(new_class_h.Get());
2371 }
2372
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002373 /*
2374 * We send CLASS_PREPARE events to the debugger from here. The
2375 * definition of "preparation" is creating the static fields for a
2376 * class and initializing them to the standard default values, but not
2377 * executing any code (that comes later, during "initialization").
2378 *
2379 * We did the static preparation in LinkClass.
2380 *
2381 * The class has been prepared and resolved but possibly not yet verified
2382 * at this point.
2383 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002384 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002385
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002386 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002387}
2388
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002389uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2390 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002391 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002392 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002393 size_t num_8 = 0;
2394 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002395 size_t num_32 = 0;
2396 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002397 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002398 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2399 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002400 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002401 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002402 switch (c) {
2403 case 'L':
2404 case '[':
2405 num_ref++;
2406 break;
2407 case 'J':
2408 case 'D':
2409 num_64++;
2410 break;
2411 case 'I':
2412 case 'F':
2413 num_32++;
2414 break;
2415 case 'S':
2416 case 'C':
2417 num_16++;
2418 break;
2419 case 'B':
2420 case 'Z':
2421 num_8++;
2422 break;
2423 default:
2424 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002425 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002426 }
2427 }
2428 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002429 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002430}
2431
Ian Rogers97b52f82014-08-14 11:34:07 -07002432OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2433 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002434 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002435 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2436 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002437 *found = false;
2438 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002439 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002440 *found = true;
2441 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002442}
2443
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002444static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2445 uint32_t method_idx) {
2446 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002447 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002448 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002449 ClassDataItemIterator it(dex_file, class_data);
2450 // Skip fields
2451 while (it.HasNextStaticField()) {
2452 it.Next();
2453 }
2454 while (it.HasNextInstanceField()) {
2455 it.Next();
2456 }
2457 // Process methods
2458 size_t class_def_method_index = 0;
2459 while (it.HasNextDirectMethod()) {
2460 if (it.GetMemberIndex() == method_idx) {
2461 return class_def_method_index;
2462 }
2463 class_def_method_index++;
2464 it.Next();
2465 }
2466 while (it.HasNextVirtualMethod()) {
2467 if (it.GetMemberIndex() == method_idx) {
2468 return class_def_method_index;
2469 }
2470 class_def_method_index++;
2471 it.Next();
2472 }
2473 DCHECK(!it.HasNext());
2474 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08002475 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002476}
2477
Ian Rogers97b52f82014-08-14 11:34:07 -07002478const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002479 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002480 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002481 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002482 size_t oat_method_index;
2483 if (method->IsStatic() || method->IsDirect()) {
2484 // Simple case where the oat method index was stashed at load time.
2485 oat_method_index = method->GetMethodIndex();
2486 } else {
2487 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2488 // by search for its position in the declared virtual methods.
2489 oat_method_index = declaring_class->NumDirectMethods();
2490 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002491 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002492 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002493 // Check method index instead of identity in case of duplicate method definitions.
2494 if (method->GetDexMethodIndex() ==
2495 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002496 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002497 break;
2498 }
Ian Rogersf320b632012-03-13 18:47:47 -07002499 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002500 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002501 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2502 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002503 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002504 DCHECK_EQ(oat_method_index,
2505 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002506 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002507 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002508 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2509 declaring_class->GetDexClassDefIndex(),
2510 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002511 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002512 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002513 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002514 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002515}
2516
2517// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002518const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002519 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002520 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002521 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002522 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002523 bool found;
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08002524 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2525 if (found) {
2526 auto* code = oat_method.GetQuickCode();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002527 if (code != nullptr) {
2528 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08002529 }
2530 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08002531 jit::Jit* const jit = Runtime::Current()->GetJit();
2532 if (jit != nullptr) {
2533 auto* code = jit->GetCodeCache()->GetCodeFor(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002534 if (code != nullptr) {
2535 return code;
2536 }
2537 }
2538 if (method->IsNative()) {
2539 // No code and native? Use generic trampoline.
2540 return GetQuickGenericJniStub();
2541 }
2542 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07002543}
2544
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002545const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2546 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2547 return nullptr;
2548 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08002549 bool found;
2550 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2551 if (found) {
2552 return oat_method.GetQuickCode();
2553 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002554 jit::Jit* jit = Runtime::Current()->GetJit();
2555 if (jit != nullptr) {
2556 auto* code = jit->GetCodeCache()->GetCodeFor(method);
2557 if (code != nullptr) {
2558 return code;
2559 }
2560 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002561 return nullptr;
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002562}
2563
Ian Rogersef7d42f2014-01-06 12:55:46 -08002564const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2565 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002566 bool found;
2567 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2568 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002569 return nullptr;
2570 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002571 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002572 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002573}
2574
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002575// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08002576static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07002577 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08002578 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002579 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002580 // May return true for native code, in the case of generic JNI
2581 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002582 return true;
2583 }
2584 // If interpreter mode is enabled, every method (except native and proxy) must
2585 // be run with interpreter.
2586 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2587 !method->IsNative() && !method->IsProxyMethod();
2588}
2589
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002590void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002591 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002592 if (klass->NumDirectMethods() == 0) {
2593 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002594 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002595 Runtime* runtime = Runtime::Current();
2596 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002597 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002598 return; // OAT file unavailable.
2599 }
Ian Rogers19846512012-02-24 11:42:47 -08002600 }
Alex Light64ad14d2014-08-19 14:23:13 -07002601
Mathieu Chartierf8322842014-05-16 10:59:25 -07002602 const DexFile& dex_file = klass->GetDexFile();
2603 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002604 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002605 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002606 // There should always be class data if there were direct methods.
2607 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002608 ClassDataItemIterator it(dex_file, class_data);
2609 // Skip fields
2610 while (it.HasNextStaticField()) {
2611 it.Next();
2612 }
2613 while (it.HasNextInstanceField()) {
2614 it.Next();
2615 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002616 bool has_oat_class;
2617 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2618 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002619 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002620 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002621 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002622 if (!method->IsStatic()) {
2623 // Only update static methods.
2624 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002625 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002626 const void* quick_code = nullptr;
2627 if (has_oat_class) {
2628 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002629 quick_code = oat_method.GetQuickCode();
2630 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002631 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002632 if (enter_interpreter) {
2633 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002634 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08002635 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002636 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08002637 } else {
2638 quick_code = GetQuickToInterpreterBridge();
2639 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002640 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002641 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08002642 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002643 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002644}
2645
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002646void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002647 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002648 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002649 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002650 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002651 // The following code only applies to a non-compiler runtime.
2652 return;
2653 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002654 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002655 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002656 if (oat_class != nullptr) {
2657 // Every kind of method should at least get an invoke stub from the oat_method.
2658 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002659 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002660 oat_method.LinkMethod(method.Get());
2661 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002662
Jeff Hao16743632013-05-08 10:59:04 -07002663 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002664 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08002665 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002666 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002667 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002668 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002669 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002670 }
2671
Brian Carlstrom92827a52011-10-10 15:50:01 -07002672 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002673 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002674 return;
2675 }
Ian Rogers19846512012-02-24 11:42:47 -08002676
2677 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002678 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002679 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2680 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002681 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002682 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002683 if (!method->IsNative()) {
2684 // Set entry point from compiled code if there's no code or in interpreter only mode.
2685 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002686 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002687 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002688 }
Ian Rogers0d6de042012-02-29 08:50:26 -08002689 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002690
Ian Rogers62d6c772013-02-27 08:32:07 -08002691 if (method->IsNative()) {
2692 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002693 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002694
2695 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002696 // We have a native method here without code. Then it should have either the generic JNI
2697 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2698 // TODO: this doesn't handle all the cases where trampolines may be installed.
2699 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2700 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002701 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002702 }
2703}
2704
Fred Shih37f05ef2014-07-16 18:38:08 -07002705
Fred Shih37f05ef2014-07-16 18:38:08 -07002706
Ian Rogers7b078e82014-09-10 14:44:24 -07002707void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002708 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002709 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002710 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002711 CHECK(klass.Get() != nullptr);
2712 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002713 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002714 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002715 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002716
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002717 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07002718 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002719 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002720 klass->SetAccessFlags(access_flags);
2721 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002722 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002723 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002724
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002725 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002726 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002727 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002728
Ian Rogers13735952014-10-08 12:43:28 -07002729 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002730 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002731 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002732 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002733
Ian Rogers97b52f82014-08-14 11:34:07 -07002734
2735 bool has_oat_class = false;
2736 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2737 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2738 &has_oat_class);
2739 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002740 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002741 }
2742 }
2743 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002744 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002745 }
2746}
2747
Ian Rogers7b078e82014-09-10 14:44:24 -07002748void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002749 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002750 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002751 const OatFile::OatClass* oat_class) {
2752 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002753 ClassDataItemIterator it(dex_file, class_data);
2754 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002755 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002756 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002757 CHECK(self->IsExceptionPending()); // OOME.
2758 return;
2759 }
2760 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002761 }
2762 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002763 mirror::ObjectArray<mirror::ArtField>* fields =
2764 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002765 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002766 CHECK(self->IsExceptionPending()); // OOME.
2767 return;
2768 }
2769 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002770 }
2771 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002772 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002773 StackHandleScope<1> hs(self);
2774 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002775 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002776 CHECK(self->IsExceptionPending()); // OOME.
2777 return;
2778 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002779 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002780 LoadField(dex_file, it, klass, sfield);
2781 }
2782 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002783 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002784 StackHandleScope<1> hs(self);
2785 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002786 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002787 CHECK(self->IsExceptionPending()); // OOME.
2788 return;
2789 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002790 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002791 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002792 }
2793
Ian Rogers0571d352011-11-03 19:51:38 -07002794 // Load methods.
2795 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002796 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002797 mirror::ObjectArray<mirror::ArtMethod>* directs =
2798 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002799 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002800 CHECK(self->IsExceptionPending()); // OOME.
2801 return;
2802 }
2803 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002804 }
Ian Rogers0571d352011-11-03 19:51:38 -07002805 if (it.NumVirtualMethods() != 0) {
2806 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002807 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2808 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002809 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002810 CHECK(self->IsExceptionPending()); // OOME.
2811 return;
2812 }
2813 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002814 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002815 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002816 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2817 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002818 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002819 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002820 StackHandleScope<1> hs(self);
2821 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002822 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002823 CHECK(self->IsExceptionPending()); // OOME.
2824 return;
2825 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002826 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002827 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002828 uint32_t it_method_index = it.GetMemberIndex();
2829 if (last_dex_method_index == it_method_index) {
2830 // duplicate case
2831 method->SetMethodIndex(last_class_def_method_index);
2832 } else {
2833 method->SetMethodIndex(class_def_method_index);
2834 last_dex_method_index = it_method_index;
2835 last_class_def_method_index = class_def_method_index;
2836 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002837 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002838 }
2839 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002840 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002841 StackHandleScope<1> hs(self);
2842 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002843 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002844 CHECK(self->IsExceptionPending()); // OOME.
2845 return;
2846 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002847 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002848 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002849 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002850 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002851 }
2852 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002853}
2854
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002855void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002856 Handle<mirror::Class> klass,
2857 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002858 uint32_t field_idx = it.GetMemberIndex();
2859 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002860 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002861 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002862}
2863
Brian Carlstromea46f952013-07-30 01:26:50 -07002864mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002865 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002866 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002867 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002868 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002869 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002870
Brian Carlstromea46f952013-07-30 01:26:50 -07002871 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002872 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002873 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002874 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002875 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002876 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002877
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002878 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002879 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002880 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002881 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002882
Ian Rogers19846512012-02-24 11:42:47 -08002883 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002884 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002885
Andreas Gampe51829322014-08-25 15:05:04 -07002886 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002887
Ian Rogersdfb325e2013-10-30 01:00:44 -07002888 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002889 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002890 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2891 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002892 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002893 klass->SetFinalizable();
2894 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002895 std::string temp;
2896 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002897 // The Enum class declares a "final" finalize() method to prevent subclasses from
2898 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2899 // subclasses, so we exclude it here.
2900 // We also want to avoid setting the flag on Object, where we know that finalize() is
2901 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002902 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2903 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002904 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002905 }
2906 }
2907 }
2908 } else if (method_name[0] == '<') {
2909 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002910 bool is_init = (strcmp("<init>", method_name) == 0);
2911 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002912 if (UNLIKELY(!is_init && !is_clinit)) {
2913 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2914 } else {
2915 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2916 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002917 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002918 access_flags |= kAccConstructor;
2919 }
2920 }
2921 }
2922 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002923
Mathieu Chartier66f19252012-09-18 08:57:04 -07002924 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002925}
2926
Ian Rogers7b078e82014-09-10 14:44:24 -07002927void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002928 StackHandleScope<1> hs(self);
2929 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002930 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2931 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002932 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002933}
2934
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002935void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002936 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002937 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002938 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002939 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002940}
2941
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002942bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002943 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002944 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002945 mirror::DexCache* dex_cache = GetDexCache(i);
2946 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002947 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002948 }
2949 }
2950 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002951}
2952
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002953bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002954 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002955 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002956}
2957
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002958void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002959 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002960 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002961 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002962 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2963 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002964 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002965 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002966 if (log_new_dex_caches_roots_) {
2967 // TODO: This is not safe if we can remove dex caches.
2968 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2969 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002970}
2971
Brian Carlstromaded5f72011-10-07 17:15:04 -07002972void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002973 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002974 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002975 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002976 if (IsDexFileRegisteredLocked(dex_file)) {
2977 return;
2978 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002979 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002980 // Don't alloc while holding the lock, since allocation may need to
2981 // suspend all threads and another thread may need the dex_lock_ to
2982 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002983 StackHandleScope<1> hs(self);
2984 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002985 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2986 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002987 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002988 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002989 if (IsDexFileRegisteredLocked(dex_file)) {
2990 return;
2991 }
2992 RegisterDexFileLocked(dex_file, dex_cache);
2993 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002994}
2995
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002996void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002997 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002998 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002999 RegisterDexFileLocked(dex_file, dex_cache);
3000}
3001
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003002mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003003 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003004 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003005 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003006 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003007 if (dex_cache->GetDexFile() == &dex_file) {
3008 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003009 }
3010 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003011 // Search matching by location name.
3012 std::string location(dex_file.GetLocation());
3013 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003014 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003015 if (dex_cache->GetDexFile()->GetLocation() == location) {
3016 return dex_cache;
3017 }
3018 }
3019 // Failure, dump diagnostic and abort.
3020 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003021 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003022 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3023 }
3024 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003025 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003026}
3027
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003028void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003029 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003030 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003031 mirror::DexCache* dex_cache = GetDexCache(i);
3032 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003033 }
3034}
3035
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003036mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003037 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003038 if (UNLIKELY(klass == nullptr)) {
3039 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003040 }
3041 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003042}
3043
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003044mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3045 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003046 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003047 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003048 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003049 StackHandleScope<1> hs(self);
3050 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003051 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003052 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003053 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003054 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3055 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003056 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3057 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003058 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003059 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003060}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003061
Brian Carlstrombe977852011-07-19 14:54:54 -07003062// Create an array class (i.e. the class object for the array, not the
3063// array itself). "descriptor" looks like "[C" or "[[[[B" or
3064// "[Ljava/lang/String;".
3065//
3066// If "descriptor" refers to an array of primitives, look up the
3067// primitive type's internally-generated class object.
3068//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003069// "class_loader" is the class loader of the class that's referring to
3070// us. It's used to ensure that we're looking for the element type in
3071// the right context. It does NOT become the class loader for the
3072// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003073//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003074// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003075mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003076 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003077 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003078 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003079 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003080 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3081 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003082 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003083 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003084 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003085 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3086 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003087 if (component_type.Get() == nullptr) {
3088 DCHECK(self->IsExceptionPending());
3089 return nullptr;
3090 } else {
3091 self->ClearException();
3092 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003093 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003094 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3095 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3096 return nullptr;
3097 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003098 // See if the component type is already loaded. Array classes are
3099 // always associated with the class loader of their underlying
3100 // element type -- an array of Strings goes with the loader for
3101 // java/lang/String -- so we need to look for it there. (The
3102 // caller should have checked for the existence of the class
3103 // before calling here, but they did so with *their* class loader,
3104 // not the component type's loader.)
3105 //
3106 // If we find it, the caller adds "loader" to the class' initiating
3107 // loader list, which should prevent us from going through this again.
3108 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003109 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003110 // are the same, because our caller (FindClass) just did the
3111 // lookup. (Even if we get this wrong we still have correct behavior,
3112 // because we effectively do this lookup again when we add the new
3113 // class to the hash table --- necessary because of possible races with
3114 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003115 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003116 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003117 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003118 return new_class;
3119 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003120 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003121
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003122 // Fill out the fields in the Class.
3123 //
3124 // It is possible to execute some methods against arrays, because
3125 // all arrays are subclasses of java_lang_Object_, so we need to set
3126 // up a vtable. We can just point at the one in java_lang_Object_.
3127 //
3128 // Array classes are simple enough that we don't need to do a full
3129 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003130 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003131 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003132 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003133 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003134 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003135 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003136 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003137 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003138 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003139 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003140 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003141 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003142 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003143 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003144 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003145 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003146 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003147 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003148 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003149 }
3150 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003151 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003152 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003153 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003154 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003155 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003156 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003157 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003158 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003159 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003160 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003161 new_class->SetSuperClass(java_lang_Object);
3162 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003163 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003164 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003165 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003166 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003167 StackHandleScope<mirror::Class::kImtSize> hs2(self,
3168 Runtime::Current()->GetImtUnimplementedMethod());
3169 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003170 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003171 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003172 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003173 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003174
3175
3176 // All arrays have java/lang/Cloneable and java/io/Serializable as
3177 // interfaces. We need to set that up here, so that stuff like
3178 // "instanceof" works right.
3179 //
3180 // Note: The GC could run during the call to FindSystemClass,
3181 // so we need to make sure the class object is GC-valid while we're in
3182 // there. Do this by clearing the interface list so the GC will just
3183 // think that the entries are null.
3184
3185
3186 // Use the single, global copies of "interfaces" and "iftable"
3187 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003188 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003189 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003190 CHECK(array_iftable != nullptr);
3191 new_class->SetIfTable(array_iftable);
3192 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003193
Elliott Hughes00626c22013-06-14 15:04:14 -07003194 // Inherit access flags from the component type.
3195 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3196 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3197 access_flags &= kAccJavaFlagsMask;
3198 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003199 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003200 access_flags |= kAccAbstract | kAccFinal;
3201 access_flags &= ~kAccInterface;
3202
3203 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003204
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003205 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003206 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003207 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003208 }
3209 // Another thread must have loaded the class after we
3210 // started but before we finished. Abandon what we've
3211 // done.
3212 //
3213 // (Yes, this happens.)
3214
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003215 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003216}
3217
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003218mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003219 switch (type) {
3220 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003221 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003222 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003223 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003224 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003225 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003226 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003227 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003228 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003229 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003230 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003231 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003232 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003233 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003234 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003235 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003236 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003237 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003238 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003239 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003240 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003241 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003242 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003243 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003244}
3245
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003246mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3247 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003248 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003249 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003250 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003251 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003252 source += " from ";
3253 source += dex_cache->GetLocation()->ToModifiedUtf8();
3254 }
3255 LOG(INFO) << "Loaded class " << descriptor << source;
3256 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003257 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003258 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003259 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003260 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003261 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003262 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003263 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003264 // Check a class loaded with the system class loader matches one in the image if the class
3265 // is in the image.
3266 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003267 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003268 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003269 }
3270 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003271 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003272 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003273 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003274 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003275 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003276 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003277}
3278
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003279mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3280 size_t hash) {
3281 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003282 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3283 hash);
3284 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003285 CHECK(klass->IsProxyClass());
3286 return nullptr;
3287 }
3288
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003289 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003290 CHECK_NE(existing, klass) << descriptor;
3291 CHECK(!existing->IsResolved()) << descriptor;
3292 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3293
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003294 CHECK(!klass->IsTemp()) << descriptor;
3295 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3296 dex_cache_image_class_lookup_required_) {
3297 // Check a class loaded with the system class loader matches one in the image if the class
3298 // is in the image.
3299 existing = LookupClassFromImage(descriptor);
3300 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003301 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003302 }
3303 }
3304 VerifyObject(klass);
3305
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003306 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003307 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003308 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003309 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003310 }
3311
3312 return existing;
3313}
3314
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003315bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003316 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003317 auto pair = std::make_pair(descriptor, class_loader);
3318 auto it = class_table_.Find(pair);
3319 if (it != class_table_.end()) {
3320 class_table_.Erase(it);
3321 return true;
3322 }
3323 it = pre_zygote_class_table_.Find(pair);
3324 if (it != pre_zygote_class_table_.end()) {
3325 pre_zygote_class_table_.Erase(it);
3326 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003327 }
3328 return false;
3329}
3330
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003331mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003332 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003333 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003334 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003335 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003336 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003337 return result;
3338 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003339 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003340 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3341 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003342 } else {
3343 // Lookup failed but need to search dex_caches_.
3344 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003345 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003346 InsertClass(descriptor, result, hash);
3347 } else {
3348 // Searching the image dex files/caches failed, we don't want to get into this situation
3349 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3350 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003351 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003352 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3353 MoveImageClassesToClassTable();
3354 }
3355 }
3356 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003357 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003358}
3359
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003360mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003361 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003362 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003363 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3364 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3365 if (it == pre_zygote_class_table_.end()) {
3366 it = class_table_.FindWithHash(descriptor_pair, hash);
3367 if (it == class_table_.end()) {
3368 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003369 }
3370 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003371 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003372}
3373
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003374static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3375 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3376 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003377 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003378 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3379 return root->AsObjectArray<mirror::DexCache>();
3380}
3381
3382void ClassLinker::MoveImageClassesToClassTable() {
3383 Thread* self = Thread::Current();
3384 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3385 if (!dex_cache_image_class_lookup_required_) {
3386 return; // All dex cache classes are already in the class table.
3387 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003388 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003389 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003390 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003391 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3392 mirror::DexCache* dex_cache = dex_caches->Get(i);
3393 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3394 for (int32_t j = 0; j < types->GetLength(); j++) {
3395 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003396 if (klass != nullptr) {
3397 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003398 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003399 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003400 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3401 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003402 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003403 << PrettyClassAndClassLoader(klass);
3404 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003405 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003406 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003407 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003408 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003409 }
3410 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003411 }
3412 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003413 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003414}
3415
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003416void ClassLinker::MoveClassTableToPreZygote() {
3417 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3418 DCHECK(pre_zygote_class_table_.Empty());
3419 pre_zygote_class_table_ = std::move(class_table_);
3420 class_table_.Clear();
3421}
3422
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003423mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003424 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003425 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3426 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3427 mirror::DexCache* dex_cache = dex_caches->Get(i);
3428 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003429 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003430 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003431 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003432 const DexFile::TypeId* type_id =
3433 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003434 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003435 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3436 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003437 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003438 return klass;
3439 }
3440 }
3441 }
3442 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003443 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003444}
3445
3446void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3447 result.clear();
3448 if (dex_cache_image_class_lookup_required_) {
3449 MoveImageClassesToClassTable();
3450 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003451 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3452 while (true) {
3453 auto it = class_table_.Find(descriptor);
3454 if (it == class_table_.end()) {
3455 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003456 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003457 result.push_back(it->Read());
3458 class_table_.Erase(it);
3459 }
3460 for (mirror::Class* k : result) {
3461 class_table_.Insert(GcRoot<mirror::Class>(k));
3462 }
3463 size_t pre_zygote_start = result.size();
3464 // Now handle the pre zygote table.
3465 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3466 // called from the debugger.
3467 while (true) {
3468 auto it = pre_zygote_class_table_.Find(descriptor);
3469 if (it == pre_zygote_class_table_.end()) {
3470 break;
3471 }
3472 result.push_back(it->Read());
3473 pre_zygote_class_table_.Erase(it);
3474 }
3475 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3476 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003477 }
3478}
3479
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003480void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003481 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003482 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003483
Ian Rogers9ffb0392012-09-10 11:56:50 -07003484 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003485 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003486 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003487 return;
3488 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003489 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003490 return;
3491 }
jeffhao98eacac2011-09-14 16:11:53 -07003492
Ian Rogers9ffb0392012-09-10 11:56:50 -07003493 // The class might already be erroneous, for example at compile time if we attempted to verify
3494 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003495 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003496 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003497 return;
3498 }
3499
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003500 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003501 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003502 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003503 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003504 << PrettyClass(klass.Get());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003505 CHECK(!Runtime::Current()->IsAotCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003506 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003507 }
jeffhao98eacac2011-09-14 16:11:53 -07003508
Jeff Hao4a200f52014-04-01 14:58:49 -07003509 // Skip verification if disabled.
3510 if (!Runtime::Current()->IsVerificationEnabled()) {
3511 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003512 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003513 return;
3514 }
3515
Ian Rogers9ffb0392012-09-10 11:56:50 -07003516 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003517 StackHandleScope<2> hs(self);
3518 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003519 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003520 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003521 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003522
3523 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003524 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003525 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003526 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003527 std::string error_msg(
3528 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3529 PrettyDescriptor(klass.Get()).c_str(),
3530 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08003531 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003532 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003533 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003534 self->ClearException();
3535 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003536 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3537 if (cause.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003538 self->GetException()->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003539 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003540 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003541 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003542 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3543 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003544 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003545 return;
3546 }
3547 }
3548
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003549 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003550 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003551 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003552 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003553 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003554 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003555 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003556 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003557 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3558 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003559 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003560 return;
3561 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003562 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003563 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003564 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003565 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003566 Runtime::Current()->IsAotCompiler(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003567 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003568 }
3569 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003570 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003571 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003572 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3573 << " because: " << error_msg;
3574 }
Ian Rogers1f539342012-10-03 21:09:42 -07003575 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003576 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003577 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003578 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003579 // Even though there were no verifier failures we need to respect whether the super-class
3580 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003581 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003582 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003583 } else {
3584 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003585 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003586 // Pretend a soft failure occured so that we don't consider the class verified below.
3587 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003588 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003589 } else {
3590 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3591 // Soft failures at compile time should be retried at runtime. Soft
3592 // failures at runtime will be handled by slow paths in the generated
3593 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003594 if (Runtime::Current()->IsAotCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003595 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003596 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003597 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003598 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3599 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003600 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003601 }
3602 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003603 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08003604 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003605 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3606 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003607 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003608 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003609 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003610 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003611 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003612 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003613 // Let the interpreter know it by setting the kAccPreverified flag onto each
3614 // method.
3615 // Note: we're going here during compilation and at runtime. When we set the
3616 // kAccPreverified flag when compiling image classes, the flag is recorded
3617 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003618 EnsurePreverifiedMethods(klass);
3619 }
3620}
3621
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003622void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003623 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003624 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003625 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003626 }
jeffhao98eacac2011-09-14 16:11:53 -07003627}
3628
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003629bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3630 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003631 // If we're compiling, we can only verify the class using the oat file if
3632 // we are not compiling the image or if the class we're verifying is not part of
3633 // the app. In other words, we will only check for preverification of bootclasspath
3634 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003635 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003636 // Are we compiling the bootclasspath?
3637 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3638 return false;
3639 }
3640 // We are compiling an app (not the image).
3641
3642 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003643 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003644 return false;
3645 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003646 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003647
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003648 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003649 // In case we run without an image there won't be a backing oat file.
3650 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003651 return false;
3652 }
3653
Andreas Gampe76bd8802014-12-10 16:43:58 -08003654 // We may be running with a preopted oat file but without image. In this case,
3655 // we don't skip verification of preverified classes to ensure we initialize
3656 // dex caches with all types resolved during verification.
3657 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
3658 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
3659 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
3660 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003661 if (!Runtime::Current()->IsAotCompiler() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08003662 !Runtime::Current()->GetHeap()->HasImageSpace() &&
3663 klass->GetClassLoader() != nullptr) {
3664 return false;
3665 }
3666
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003667 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003668 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003669 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3670 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003671 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003672 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003673 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003674 // Compile time verification failed with a soft error. Compile time verification can fail
3675 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003676 // class ... {
3677 // Foo x;
3678 // .... () {
3679 // if (...) {
3680 // v1 gets assigned a type of resolved class Foo
3681 // } else {
3682 // v1 gets assigned a type of unresolved class Bar
3683 // }
3684 // iput x = v1
3685 // } }
3686 // when we merge v1 following the if-the-else it results in Conflict
3687 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3688 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3689 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3690 // at compile time).
3691 return false;
3692 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003693 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003694 // Compile time verification failed with a hard error. This is caused by invalid instructions
3695 // in the class. These errors are unrecoverable.
3696 return false;
3697 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003698 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003699 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3700 // not loading the class.
3701 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3702 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003703 return false;
3704 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003705 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003706 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003707 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003708 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003709 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003710}
3711
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003712void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003713 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003714 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3715 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3716 }
3717 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3718 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3719 }
3720}
3721
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003722void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003723 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003724 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3725 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003726 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003727 return; // native or abstract method
3728 }
3729 if (code_item->tries_size_ == 0) {
3730 return; // nothing to process
3731 }
Ian Rogers13735952014-10-08 12:43:28 -07003732 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003733 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3734 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3735 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3736 CatchHandlerIterator iterator(handlers_ptr);
3737 for (; iterator.HasNext(); iterator.Next()) {
3738 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3739 // unresolved exception types will be ignored by exception delivery
3740 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003741 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003742 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003743 DCHECK(Thread::Current()->IsExceptionPending());
3744 Thread::Current()->ClearException();
3745 }
3746 }
3747 }
3748 handlers_ptr = iterator.EndDataPointer();
3749 }
3750}
3751
Brian Carlstromea46f952013-07-30 01:26:50 -07003752static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003753static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3754 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003755
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003756mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003757 jobjectArray interfaces, jobject loader,
3758 jobjectArray methods, jobjectArray throws) {
3759 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003760 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003761 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003762 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003763 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003764 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003765 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003766 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003767 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003768 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003769 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3770 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003771 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003772 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003773 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003774 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003775 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003776 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003777
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003778 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003779 {
3780 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003781 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003782 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003783 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003784 }
3785 klass->SetSFields(sfields);
3786 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003787 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3788 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003789 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3790 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003791 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003792 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003793 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003794 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003795 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003796 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003797 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3798 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003799 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3800 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003801 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003802 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003803 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003804 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003805 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003806 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003807 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003808
Ian Rogers466bb252011-10-14 03:29:56 -07003809 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003810 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003811 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003812 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003813 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003814 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003815 }
3816 klass->SetDirectMethods(directs);
3817 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003818 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003819 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003820 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003821 }
3822 klass->SetDirectMethod(0, constructor);
3823 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003824
Mathieu Chartier590fee92013-09-13 13:46:47 -07003825 // Create virtual method using specified prototypes.
3826 size_t num_virtual_methods =
3827 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003828 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003829 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3830 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003831 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003832 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003833 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003834 }
3835 klass->SetVirtualMethods(virtuals);
3836 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003837 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003838 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003839 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3840 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003841 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003842 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003843 if (UNLIKELY(clone == 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->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003848 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003849
3850 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003851 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003852 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003853
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003854 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3855 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003856 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003857 // Must hold lock on object when resolved.
3858 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003859 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003860 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003861 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003862 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003863 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003864 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003865 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003866 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003867
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003868 CHECK(klass->IsRetired());
3869 CHECK_NE(klass.Get(), new_class);
3870 klass.Assign(new_class);
3871
3872 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003873 interfaces_sfield->SetObject<false>(klass.Get(),
3874 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003875 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003876 throws_sfield->SetObject<false>(klass.Get(),
3877 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003878
3879 {
3880 // Lock on klass is released. Lock new class object.
3881 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003882 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003883 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003884
3885 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003886 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003887 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003888 CheckProxyConstructor(klass->GetDirectMethod(0));
3889 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003890 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003891 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3892 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003893 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3894 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003895 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003896 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003897
Mathieu Chartier590fee92013-09-13 13:46:47 -07003898 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003899 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003900 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003901 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3902
3903 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003904 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003905 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003906
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003907 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003908 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003909 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003910 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003911 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003912 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3913 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003914 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003915 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003916}
3917
Ian Rogersef7d42f2014-01-06 12:55:46 -08003918std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003919 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003920 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003921 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003922 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3923}
3924
Ian Rogersef7d42f2014-01-06 12:55:46 -08003925mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3926 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003927 DCHECK(proxy_class->IsProxyClass());
3928 DCHECK(proxy_method->IsProxyMethod());
3929 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003930 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003931 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003932 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003933 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003934 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003935 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003936 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003937 break;
3938 }
3939 }
3940 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003941 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003942 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003943 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003944 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003945 return resolved_method;
3946}
3947
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003948
Brian Carlstromea46f952013-07-30 01:26:50 -07003949mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003950 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003951 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003952 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003953 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003954 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003955 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3956 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003957 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3958 // constructor method.
3959 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3960 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003961 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3962 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003963 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3964 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003965 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003966 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003967 }
Ian Rogers466bb252011-10-14 03:29:56 -07003968 // Make this constructor public and fix the class to be our Proxy version
3969 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003970 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003971 return constructor;
3972}
3973
Brian Carlstromea46f952013-07-30 01:26:50 -07003974static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003975 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003976 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003977 CHECK_STREQ(constructor->GetName(), "<init>");
3978 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3979 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003980 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003981}
3982
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003983mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003984 Handle<mirror::Class> klass,
3985 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003986 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3987 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003988 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003989 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003990 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003991 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003992 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003993 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003994 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003995 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003996 }
Ian Rogers466bb252011-10-14 03:29:56 -07003997
3998 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3999 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004000 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004001 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004002
Ian Rogers466bb252011-10-14 03:29:56 -07004003 // At runtime the method looks like a reference and argument saving method, clone the code
4004 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004005 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004006 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004007
Ian Rogersc2b44472011-12-14 21:17:17 -08004008 return method;
4009}
Jesse Wilson95caa792011-10-12 18:14:17 -04004010
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004011static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4012 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004013 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004014 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004015 CHECK(!prototype->IsFinal());
4016 CHECK(method->IsFinal());
4017 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004018
4019 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4020 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07004021 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4022 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004023 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4024
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004025 CHECK_STREQ(method->GetName(), prototype->GetName());
4026 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004027 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004028 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004029}
4030
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004031static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4032 bool can_init_parents)
4033 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004034 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004035 return true;
4036 }
4037 if (!can_init_statics) {
4038 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004039 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004040 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004041 return false;
4042 }
4043 // Check if there are encoded static values needing initialization.
4044 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004045 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004046 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004047 if (dex_class_def->static_values_off_ != 0) {
4048 return false;
4049 }
4050 }
4051 }
4052 if (!klass->IsInterface() && klass->HasSuperClass()) {
4053 mirror::Class* super_class = klass->GetSuperClass();
4054 if (!can_init_parents && !super_class->IsInitialized()) {
4055 return false;
4056 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004057 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004058 return false;
4059 }
4060 }
4061 }
4062 return true;
4063}
4064
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004065bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004066 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004067 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4068
4069 // Are we already initialized and therefore done?
4070 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4071 // an initialized class will never change its state.
4072 if (klass->IsInitialized()) {
4073 return true;
4074 }
4075
4076 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004077 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004078 return false;
4079 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004080
Ian Rogers7b078e82014-09-10 14:44:24 -07004081 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004082 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004083 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004084 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004085
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004086 // Re-check under the lock in case another thread initialized ahead of us.
4087 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004088 return true;
4089 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004090
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004091 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004092 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004093 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004094 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004095 return false;
4096 }
4097
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004098 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004099
4100 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004101 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004102 if (!klass->IsVerified()) {
4103 // We failed to verify, expect either the klass to be erroneous or verification failed at
4104 // compile time.
4105 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004106 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004107 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004108 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004109 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004110 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004111 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004112 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004113 } else {
4114 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004115 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004116 }
4117
Brian Carlstromd1422f82011-09-28 11:37:09 -07004118 // If the class is kStatusInitializing, either this thread is
4119 // initializing higher up the stack or another thread has beat us
4120 // to initializing and we need to wait. Either way, this
4121 // invocation of InitializeClass will not be responsible for
4122 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004123 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004124 // Could have got an exception during verification.
4125 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004126 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004127 return false;
4128 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004129 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004130 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004131 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004132 return true;
4133 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004134 // No. That's fine. Wait for another thread to finish initializing.
4135 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004136 }
4137
4138 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004139 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004140 return false;
4141 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004142 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004143
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004144 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004145
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004146 // From here out other threads may observe that we're initializing and so changes of state
4147 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004148 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004149 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004150
4151 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004152 }
4153
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004154 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004155 if (!klass->IsInterface() && klass->HasSuperClass()) {
4156 mirror::Class* super_class = klass->GetSuperClass();
4157 if (!super_class->IsInitialized()) {
4158 CHECK(!super_class->IsInterface());
4159 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004160 StackHandleScope<1> hs(self);
4161 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004162 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004163 if (!super_initialized) {
4164 // The super class was verified ahead of entering initializing, we should only be here if
4165 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004166 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004167 << "Super class initialization failed for "
4168 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004169 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004170 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004171 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004172 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004173 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004174 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004175 return false;
4176 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004177 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004178 }
4179
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004180 const size_t num_static_fields = klass->NumStaticFields();
4181 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004182 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004183 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004184 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004185 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004186 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004187 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004188
4189 // Eagerly fill in static fields so that the we don't have to do as many expensive
4190 // Class::FindStaticField in ResolveField.
4191 for (size_t i = 0; i < num_static_fields; ++i) {
4192 mirror::ArtField* field = klass->GetStaticField(i);
4193 const uint32_t field_idx = field->GetDexFieldIndex();
4194 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4195 if (resolved_field == nullptr) {
4196 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004197 } else {
4198 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004199 }
4200 }
4201
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004202 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4203 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004204 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004205 ClassDataItemIterator field_it(dex_file, class_data);
4206 if (value_it.HasNext()) {
4207 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004208 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004209 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004210 StackHandleScope<1> hs2(self);
4211 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004212 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004213 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004214 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004215 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004216 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004217 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004218 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004219 }
4220 }
4221 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004222
Ian Rogersd91d6d62013-09-25 20:26:14 -07004223 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004224 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004225 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004226 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004227 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004228 }
4229
Ian Rogers7b078e82014-09-10 14:44:24 -07004230 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004231 uint64_t t1 = NanoTime();
4232
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004233 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004234 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004235 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004236
4237 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004238 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004239 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004240 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004241 } else if (Runtime::Current()->IsTransactionAborted()) {
4242 // The exception thrown when the transaction aborted has been caught and cleared
4243 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01004244 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
4245 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004246 Runtime::Current()->ThrowInternalErrorForAbortedTransaction(self);
4247 klass->SetStatus(mirror::Class::kStatusError, self);
4248 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004249 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004250 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4251 RuntimeStats* thread_stats = self->GetStats();
4252 ++global_stats->class_init_count;
4253 ++thread_stats->class_init_count;
4254 global_stats->class_init_time_ns += (t1 - t0);
4255 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004256 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004257 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004258 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004259 std::string temp;
4260 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004261 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004262 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004263 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004264 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004265 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004266 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004267 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004268}
4269
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004270bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004271 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004272 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004273 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004274 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004275 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004276 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004277
4278 // When we wake up, repeat the test for init-in-progress. If
4279 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004280 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004281 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004282 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004283 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004284 return false;
4285 }
4286 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004287 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004288 continue;
4289 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004290 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
4291 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004292 // Compile time initialization failed.
4293 return false;
4294 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004295 if (klass->IsErroneous()) {
4296 // The caller wants an exception, but it was thrown in a
4297 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004298 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004299 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004300 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004301 return false;
4302 }
4303 if (klass->IsInitialized()) {
4304 return true;
4305 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004306 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004307 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004308 }
Ian Rogers07140832014-09-30 15:43:59 -07004309 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004310}
4311
Ian Rogersb5fb2072014-12-02 17:22:02 -08004312static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
4313 Handle<mirror::ArtMethod> method1,
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004314 Handle<mirror::ArtMethod> method2,
4315 std::string* error_msg)
Ian Rogersb5fb2072014-12-02 17:22:02 -08004316 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4317 {
4318 StackHandleScope<1> hs(self);
4319 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
Vladimir Marko862f43c2015-02-10 18:22:57 +00004320 mirror::Class* other_return_type = method2->GetReturnType();
4321 // NOTE: return_type.Get() must be sequenced after method2->GetReturnType().
4322 if (UNLIKELY(other_return_type != return_type.Get())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004323 *error_msg = StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
4324 PrettyClassAndClassLoader(return_type.Get()).c_str(),
4325 return_type.Get(),
4326 PrettyClassAndClassLoader(other_return_type).c_str(),
4327 other_return_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004328 return false;
4329 }
4330 }
4331 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4332 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4333 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004334 if (types2 != nullptr && types2->Size() != 0) {
4335 *error_msg = StringPrintf("Type list mismatch with %s",
4336 PrettyMethod(method2.Get(), true).c_str());
4337 return false;
4338 }
4339 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08004340 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004341 if (types1->Size() != 0) {
4342 *error_msg = StringPrintf("Type list mismatch with %s",
4343 PrettyMethod(method2.Get(), true).c_str());
4344 return false;
4345 }
4346 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08004347 }
4348 uint32_t num_types = types1->Size();
4349 if (UNLIKELY(num_types != types2->Size())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004350 *error_msg = StringPrintf("Type list mismatch with %s",
4351 PrettyMethod(method2.Get(), true).c_str());
Ian Rogersb5fb2072014-12-02 17:22:02 -08004352 return false;
4353 }
4354 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00004355 StackHandleScope<1> hs(self);
4356 Handle<mirror::Class> param_type(hs.NewHandle(
4357 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true)));
Ian Rogersb5fb2072014-12-02 17:22:02 -08004358 mirror::Class* other_param_type =
4359 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
Vladimir Marko862f43c2015-02-10 18:22:57 +00004360 // NOTE: param_type.Get() must be sequenced after method2->GetClassFromTypeIndex(...).
4361 if (UNLIKELY(param_type.Get() != other_param_type)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004362 *error_msg = StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
4363 i,
4364 PrettyClassAndClassLoader(param_type.Get()).c_str(),
4365 param_type.Get(),
4366 PrettyClassAndClassLoader(other_param_type).c_str(),
4367 other_param_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004368 return false;
4369 }
4370 }
4371 return true;
4372}
4373
4374
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004375bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004376 if (klass->IsInterface()) {
4377 return true;
4378 }
Ian Rogers151f2212014-05-06 11:27:27 -07004379 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004380 Thread* self = Thread::Current();
4381 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004382 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
4383 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004384 if (klass->HasSuperClass() &&
4385 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004386 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004387 h_m.Assign(klass->GetVTableEntry(i));
4388 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004389 if (h_m.Get() != super_h_m.Get()) {
4390 std::string error_msg;
4391 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
4392 ThrowLinkageError(klass.Get(),
4393 "Class %s method %s resolves differently in superclass %s: %s",
4394 PrettyDescriptor(klass.Get()).c_str(),
4395 PrettyMethod(h_m.Get()).c_str(),
4396 PrettyDescriptor(klass->GetSuperClass()).c_str(),
4397 error_msg.c_str());
4398 return false;
4399 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004400 }
4401 }
4402 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004403 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004404 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4405 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4406 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004407 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4408 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004409 if (h_m.Get() != super_h_m.Get()) {
4410 std::string error_msg;
4411 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
4412 ThrowLinkageError(klass.Get(),
4413 "Class %s method %s resolves differently in interface %s: %s",
4414 PrettyDescriptor(klass.Get()).c_str(),
4415 PrettyMethod(h_m.Get()).c_str(),
4416 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str(),
4417 error_msg.c_str());
4418 return false;
4419 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004420 }
4421 }
4422 }
4423 }
4424 return true;
4425}
4426
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004427bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4428 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004429 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004430 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004431 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004432 return true;
4433 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004434 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004435 if (!success) {
4436 if (can_init_fields && can_init_parents) {
4437 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4438 }
4439 } else {
4440 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004441 }
4442 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004443}
4444
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004445void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4446 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4447 if (fields != nullptr) {
4448 for (int index = 0; index < fields->GetLength(); index ++) {
4449 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4450 fields->Get(index)->SetDeclaringClass(new_class);
4451 }
4452 }
4453 }
4454
4455 fields = new_class->GetSFields();
4456 if (fields != nullptr) {
4457 for (int index = 0; index < fields->GetLength(); index ++) {
4458 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4459 fields->Get(index)->SetDeclaringClass(new_class);
4460 }
4461 }
4462 }
4463
4464 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4465 if (methods != nullptr) {
4466 for (int index = 0; index < methods->GetLength(); index ++) {
4467 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4468 methods->Get(index)->SetDeclaringClass(new_class);
4469 }
4470 }
4471 }
4472
4473 methods = new_class->GetVirtualMethods();
4474 if (methods != nullptr) {
4475 for (int index = 0; index < methods->GetLength(); index ++) {
4476 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4477 methods->Get(index)->SetDeclaringClass(new_class);
4478 }
4479 }
4480 }
4481}
4482
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004483bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4484 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004485 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004486 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004487
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004488 if (!LinkSuperClass(klass)) {
4489 return false;
4490 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004491 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4492 self, Runtime::Current()->GetImtUnimplementedMethod());
4493 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004494 return false;
4495 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004496 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004497 return false;
4498 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004499 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004500 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004501 return false;
4502 }
4503 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004504 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004505
4506 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4507 // We don't need to retire this class as it has no embedded tables or it was created the
4508 // correct size during class linker initialization.
4509 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4510
4511 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004512 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004513 }
4514
4515 // This will notify waiters on klass that saw the not yet resolved
4516 // class in the class_table_ during EnsureResolved.
4517 klass->SetStatus(mirror::Class::kStatusResolved, self);
4518 *new_class = klass.Get();
4519 } else {
4520 CHECK(!klass->IsResolved());
4521 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004522 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004523 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004524 CHECK(self->IsExceptionPending()); // Expect an OOME.
4525 klass->SetStatus(mirror::Class::kStatusError, self);
4526 return false;
4527 }
4528
4529 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4530 StackHandleScope<1> hs(self);
4531 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4532 ObjectLock<mirror::Class> lock(self, new_class_h);
4533
4534 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4535
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004536 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4537 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004538 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004539
4540 // This will notify waiters on temp class that saw the not yet resolved class in the
4541 // class_table_ during EnsureResolved.
4542 klass->SetStatus(mirror::Class::kStatusRetired, self);
4543
4544 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4545 // This will notify waiters on new_class that saw the not yet resolved
4546 // class in the class_table_ during EnsureResolved.
4547 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004548 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004549 return true;
4550}
4551
Andreas Gampefd9eb392014-11-06 16:52:58 -08004552static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
4553 size_t* virtual_methods,
4554 size_t* direct_methods,
4555 size_t* static_fields,
4556 size_t* instance_fields) {
4557 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
4558
4559 while (dex_data.HasNextStaticField()) {
4560 dex_data.Next();
4561 (*static_fields)++;
4562 }
4563 while (dex_data.HasNextInstanceField()) {
4564 dex_data.Next();
4565 (*instance_fields)++;
4566 }
4567 while (dex_data.HasNextDirectMethod()) {
4568 (*direct_methods)++;
4569 dex_data.Next();
4570 }
4571 while (dex_data.HasNextVirtualMethod()) {
4572 (*virtual_methods)++;
4573 dex_data.Next();
4574 }
4575 DCHECK(!dex_data.HasNext());
4576}
4577
4578static void DumpClass(std::ostream& os,
4579 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
4580 const char* suffix) {
4581 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
4582 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
4583 os << " Static fields:\n";
4584 while (dex_data.HasNextStaticField()) {
4585 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4586 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4587 dex_data.Next();
4588 }
4589 os << " Instance fields:\n";
4590 while (dex_data.HasNextInstanceField()) {
4591 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4592 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4593 dex_data.Next();
4594 }
4595 os << " Direct methods:\n";
4596 while (dex_data.HasNextDirectMethod()) {
4597 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4598 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4599 dex_data.Next();
4600 }
4601 os << " Virtual methods:\n";
4602 while (dex_data.HasNextVirtualMethod()) {
4603 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4604 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4605 dex_data.Next();
4606 }
4607}
4608
4609static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4610 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
4611 std::ostringstream os;
4612 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
4613 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
4614 return os.str();
4615}
4616
4617
4618// Very simple structural check on whether the classes match. Only compares the number of
4619// methods and fields.
4620static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4621 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
4622 std::string* error_msg) {
4623 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
4624 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
4625
4626 // Counters for current dex file.
4627 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
4628 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
4629 &dex_instance_fields1);
4630 // Counters for compile-time dex file.
4631 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
4632 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
4633 &dex_instance_fields2);
4634
4635 if (dex_virtual_methods1 != dex_virtual_methods2) {
4636 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4637 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
4638 dex_virtual_methods2, class_dump.c_str());
4639 return false;
4640 }
4641 if (dex_direct_methods1 != dex_direct_methods2) {
4642 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4643 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
4644 dex_direct_methods2, class_dump.c_str());
4645 return false;
4646 }
4647 if (dex_static_fields1 != dex_static_fields2) {
4648 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4649 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
4650 dex_static_fields2, class_dump.c_str());
4651 return false;
4652 }
4653 if (dex_instance_fields1 != dex_instance_fields2) {
4654 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4655 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
4656 dex_instance_fields2, class_dump.c_str());
4657 return false;
4658 }
4659
4660 return true;
4661}
4662
4663// Checks whether a the super-class changed from what we had at compile-time. This would
4664// invalidate quickening.
4665static bool CheckSuperClassChange(Handle<mirror::Class> klass,
4666 const DexFile& dex_file,
4667 const DexFile::ClassDef& class_def,
4668 mirror::Class* super_class)
4669 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4670 // Check for unexpected changes in the superclass.
4671 // Quick check 1) is the super_class class-loader the boot class loader? This always has
4672 // precedence.
4673 if (super_class->GetClassLoader() != nullptr &&
4674 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
4675 // which is implied by different dex cache.
4676 klass->GetDexCache() != super_class->GetDexCache()) {
4677 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
4678 // definition for the super-class, and (b) the files are in separate oat files. The oat files
4679 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
4680 const OatFile* class_oat_file = dex_file.GetOatFile();
4681 if (class_oat_file != nullptr) {
4682 const OatFile* loaded_super_oat_file = super_class->GetDexFile().GetOatFile();
4683 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
4684 // Now check (a).
4685 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
4686 if (super_class_def != nullptr) {
4687 // Uh-oh, we found something. Do our check.
4688 std::string error_msg;
4689 if (!SimpleStructuralCheck(dex_file, *super_class_def,
4690 super_class->GetDexFile(), *super_class->GetClassDef(),
4691 &error_msg)) {
4692 // Print a warning to the log. This exception might be caught, e.g., as common in test
4693 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
4694 // only save the type of the exception.
4695 LOG(WARNING) << "Incompatible structural change detected: " <<
4696 StringPrintf(
4697 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4698 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4699 class_oat_file->GetLocation().c_str(),
4700 loaded_super_oat_file->GetLocation().c_str(),
4701 error_msg.c_str());
4702 ThrowIncompatibleClassChangeError(klass.Get(),
4703 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4704 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4705 class_oat_file->GetLocation().c_str(),
4706 loaded_super_oat_file->GetLocation().c_str(),
4707 error_msg.c_str());
4708 return false;
4709 }
4710 }
4711 }
4712 }
4713 }
4714 return true;
4715}
4716
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004717bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004718 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004719 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4720 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004721 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004722 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004723 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004724 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004725 return false;
4726 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004727 // Verify
4728 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004729 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004730 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004731 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004732 return false;
4733 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004734 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004735 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08004736
4737 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
4738 DCHECK(Thread::Current()->IsExceptionPending());
4739 return false;
4740 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004741 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004742 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004743 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004744 for (size_t i = 0; i < interfaces->Size(); i++) {
4745 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004746 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004747 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004748 DCHECK(Thread::Current()->IsExceptionPending());
4749 return false;
4750 }
4751 // Verify
4752 if (!klass->CanAccess(interface)) {
4753 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004754 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004755 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004756 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004757 return false;
4758 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004759 }
4760 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004761 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004762 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004763 return true;
4764}
4765
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004766bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004767 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004768 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004769 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004770 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004771 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004772 return false;
4773 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004774 return true;
4775 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004776 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004777 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4778 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004779 return false;
4780 }
4781 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004782 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004783 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004784 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004785 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004786 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004787 return false;
4788 }
4789 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004790 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004791 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004792 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004793 return false;
4794 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004795
Brian Carlstromf3632832014-05-20 15:36:53 -07004796 // Inherit kAccClassIsFinalizable from the superclass in case this
4797 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004798 if (super->IsFinalizable()) {
4799 klass->SetFinalizable();
4800 }
4801
Elliott Hughes2da50362011-10-10 16:57:08 -07004802 // Inherit reference flags (if any) from the superclass.
4803 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4804 if (reference_flags != 0) {
4805 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4806 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004807 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004808 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004809 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004810 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004811 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004812 return false;
4813 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004814
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004815 if (kIsDebugBuild) {
4816 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004817 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004818 CHECK(super->IsResolved());
4819 super = super->GetSuperClass();
4820 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004821 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004822 return true;
4823}
4824
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004825// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004826bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004827 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4828 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004829 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004830 if (klass->IsInterface()) {
4831 // No vtable.
4832 size_t count = klass->NumVirtualMethods();
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004833 if (!IsUint<16>(count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004834 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004835 return false;
4836 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004837 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004838 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004839 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004840 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4841 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004842 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004843 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004844}
4845
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004846// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4847// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4848// caches in the implementation below.
4849class MethodNameAndSignatureComparator FINAL : public ValueObject {
4850 public:
4851 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4852 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4853 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4854 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004855 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4856 }
4857
4858 const char* GetName() {
4859 if (name_ == nullptr) {
4860 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4861 }
4862 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004863 }
4864
4865 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4866 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4867 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4868 const DexFile* other_dex_file = other->GetDexFile();
4869 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4870 if (dex_file_ == other_dex_file) {
4871 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4872 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004873 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004874 uint32_t other_name_len;
4875 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4876 &other_name_len);
4877 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4878 return false;
4879 }
4880 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4881 }
4882
4883 private:
4884 // Dex file for the method to compare against.
4885 const DexFile* const dex_file_;
4886 // MethodId for the method to compare against.
4887 const DexFile::MethodId* const mid_;
4888 // Lazily computed name from the dex file's strings.
4889 const char* name_;
4890 // Lazily computed name length.
4891 uint32_t name_len_;
4892};
4893
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004894class LinkVirtualHashTable {
4895 public:
4896 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4897 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4898 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4899 }
4900 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4901 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4902 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004903 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004904 uint32_t index = hash % hash_size_;
4905 // Linear probe until we have an empty slot.
4906 while (hash_table_[index] != invalid_index_) {
4907 if (++index == hash_size_) {
4908 index = 0;
4909 }
4910 }
4911 hash_table_[index] = virtual_method_index;
4912 }
4913 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4914 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4915 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004916 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004917 size_t index = hash % hash_size_;
4918 while (true) {
4919 const uint32_t value = hash_table_[index];
4920 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4921 // the block and can safely assume not found.
4922 if (value == invalid_index_) {
4923 break;
4924 }
4925 if (value != removed_index_) { // This signifies not already overriden.
4926 mirror::ArtMethod* virtual_method =
4927 klass_->GetVirtualMethodDuringLinking(value);
4928 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4929 hash_table_[index] = removed_index_;
4930 return value;
4931 }
4932 }
4933 if (++index == hash_size_) {
4934 index = 0;
4935 }
4936 }
4937 return GetNotFoundIndex();
4938 }
4939 static uint32_t GetNotFoundIndex() {
4940 return invalid_index_;
4941 }
4942
4943 private:
4944 static const uint32_t invalid_index_;
4945 static const uint32_t removed_index_;
4946
4947 Handle<mirror::Class> klass_;
4948 const size_t hash_size_;
4949 uint32_t* const hash_table_;
4950};
4951
4952const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4953const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4954
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004955bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004956 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004957 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004958 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4959 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004960 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004961 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004962 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004963 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4964 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4965 if (UNLIKELY(vtable.Get() == nullptr)) {
4966 CHECK(self->IsExceptionPending()); // OOME.
4967 return false;
4968 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004969 for (size_t i = 0; i < super_vtable_length; i++) {
4970 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004971 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004972 if (num_virtual_methods == 0) {
4973 klass->SetVTable(vtable.Get());
4974 return true;
4975 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004976 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004977 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4978 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4979 if (num_virtual_methods == 0) {
4980 klass->SetVTable(super_vtable);
4981 return true;
4982 }
4983 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004984 if (UNLIKELY(vtable.Get() == nullptr)) {
4985 CHECK(self->IsExceptionPending()); // OOME.
4986 return false;
4987 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004988 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004989 // How the algorithm works:
4990 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4991 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4992 // method which has not been matched to a vtable method, and j if the virtual method at the
4993 // index overrode the super virtual method at index j.
4994 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4995 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4996 // the need for the initial vtable which we later shrink back down).
4997 // 3. Add non overridden methods to the end of the vtable.
4998 static constexpr size_t kMaxStackHash = 250;
4999 const size_t hash_table_size = num_virtual_methods * 3;
5000 uint32_t* hash_table_ptr;
5001 std::unique_ptr<uint32_t[]> hash_heap_storage;
5002 if (hash_table_size <= kMaxStackHash) {
5003 hash_table_ptr = reinterpret_cast<uint32_t*>(
5004 alloca(hash_table_size * sizeof(*hash_table_ptr)));
5005 } else {
5006 hash_heap_storage.reset(new uint32_t[hash_table_size]);
5007 hash_table_ptr = hash_heap_storage.get();
5008 }
5009 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
5010 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005011 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005012 hash_table.Add(i);
5013 }
5014 // Loop through each super vtable method and see if they are overriden by a method we added to
5015 // the hash table.
5016 for (size_t j = 0; j < super_vtable_length; ++j) {
5017 // Search the hash table to see if we are overidden by any method.
5018 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
5019 MethodNameAndSignatureComparator super_method_name_comparator(
5020 super_method->GetInterfaceMethodIfProxy());
5021 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5022 if (hash_index != hash_table.GetNotFoundIndex()) {
5023 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
5024 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
5025 super_method->GetAccessFlags())) {
5026 if (super_method->IsFinal()) {
5027 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5028 PrettyMethod(virtual_method).c_str(),
5029 super_method->GetDeclaringClassDescriptor());
5030 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005031 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005032 vtable->SetWithoutChecks<false>(j, virtual_method);
5033 virtual_method->SetMethodIndex(j);
5034 } else {
5035 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005036 << " would have incorrectly overridden the package-private method in "
5037 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005038 }
5039 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005040 }
5041 // Add the non overridden methods at the end.
5042 size_t actual_count = super_vtable_length;
5043 for (size_t i = 0; i < num_virtual_methods; ++i) {
5044 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
5045 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5046 if (method_idx < super_vtable_length &&
5047 local_method == vtable->GetWithoutChecks(method_idx)) {
5048 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005049 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005050 vtable->SetWithoutChecks<false>(actual_count, local_method);
5051 local_method->SetMethodIndex(actual_count);
5052 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005053 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005054 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005055 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005056 return false;
5057 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005058 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005059 CHECK_LE(actual_count, max_count);
5060 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005061 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005062 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005063 CHECK(self->IsExceptionPending()); // OOME.
5064 return false;
5065 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005066 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005067 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005068 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005069 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005070 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005071 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5072 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005073 return false;
5074 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005075 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
5076 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005077 CHECK(self->IsExceptionPending()); // OOME.
5078 return false;
5079 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005080 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005081 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005082 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005083 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005084 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005085 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005086 }
5087 return true;
5088}
5089
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005090bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
5091 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
5092 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07005093 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005094 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005095 const bool has_superclass = klass->HasSuperClass();
5096 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
5097 const bool have_interfaces = interfaces.Get() != nullptr;
5098 const size_t num_interfaces =
5099 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
5100 if (num_interfaces == 0) {
5101 if (super_ifcount == 0) {
5102 // Class implements no interfaces.
5103 DCHECK_EQ(klass->GetIfTableCount(), 0);
5104 DCHECK(klass->GetIfTable() == nullptr);
5105 return true;
5106 }
Ian Rogers9bc81912012-10-11 21:43:36 -07005107 // Class implements same interfaces as parent, are any of these not marker interfaces?
5108 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005109 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005110 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005111 if (super_iftable->GetMethodArrayCount(i) > 0) {
5112 has_non_marker_interface = true;
5113 break;
5114 }
5115 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005116 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07005117 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005118 klass->SetIfTable(super_iftable);
5119 return true;
5120 }
5121 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005122 size_t ifcount = super_ifcount + num_interfaces;
5123 for (size_t i = 0; i < num_interfaces; i++) {
5124 mirror::Class* interface = have_interfaces ?
5125 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
5126 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005127 if (UNLIKELY(!interface->IsInterface())) {
5128 std::string temp;
5129 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
5130 PrettyDescriptor(klass.Get()).c_str(),
5131 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
5132 return false;
5133 }
5134 ifcount += interface->GetIfTableCount();
5135 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005136 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005137 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005138 CHECK(self->IsExceptionPending()); // OOME.
5139 return false;
5140 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005141 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005142 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005143 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005144 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07005145 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005146 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005147 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005148 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005149 // Flatten the interface inheritance hierarchy.
5150 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005151 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07005152 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
5153 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005154 // Check if interface is already in iftable
5155 bool duplicate = false;
5156 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005157 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005158 if (existing_interface == interface) {
5159 duplicate = true;
5160 break;
5161 }
5162 }
5163 if (!duplicate) {
5164 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07005165 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005166 // Add this interface's non-duplicate super-interfaces.
5167 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005168 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005169 bool super_duplicate = false;
5170 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005171 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005172 if (existing_interface == super_interface) {
5173 super_duplicate = true;
5174 break;
5175 }
5176 }
5177 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005178 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005179 }
5180 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005181 }
5182 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005183 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08005184 // Shrink iftable in case duplicates were found
5185 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005186 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005187 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005188 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005189 CHECK(self->IsExceptionPending()); // OOME.
5190 return false;
5191 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08005192 ifcount = idx;
5193 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005194 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005195 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005196 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07005197 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07005198 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005199 return true;
5200 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005201 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005202 size_t max_miranda_methods = 0; // The max size of miranda_list.
5203 for (size_t i = 0; i < ifcount; ++i) {
5204 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
5205 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005206 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005207 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005208 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
5209 hs.NewHandle(klass->GetVTableDuringLinking()));
5210 // Copy the IMT from the super class if possible.
5211 bool extend_super_iftable = false;
5212 if (has_superclass) {
5213 mirror::Class* super_class = klass->GetSuperClass();
5214 extend_super_iftable = true;
5215 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5216 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5217 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
5218 }
5219 } else {
5220 // No imt in the super class, need to reconstruct from the iftable.
5221 mirror::IfTable* if_table = super_class->GetIfTable();
5222 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5223 const size_t length = super_class->GetIfTableCount();
5224 for (size_t i = 0; i < length; ++i) {
5225 mirror::Class* interface = iftable->GetInterface(i);
5226 const size_t num_virtuals = interface->NumVirtualMethods();
5227 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5228 DCHECK_EQ(num_virtuals, method_array_count);
5229 if (method_array_count == 0) {
5230 continue;
5231 }
5232 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5233 for (size_t j = 0; j < num_virtuals; ++j) {
5234 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5235 if (method->IsMiranda()) {
5236 continue;
5237 }
5238 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5239 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5240 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5241 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5242 out_imt->SetReference(imt_index, method);
5243 } else if (imt_ref != conflict_method) {
5244 out_imt->SetReference(imt_index, conflict_method);
5245 }
5246 }
5247 }
5248 }
5249 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005250 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005251 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005252 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005253 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005254 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005255 const bool is_super = i < super_ifcount;
5256 const bool super_interface = is_super && extend_super_iftable;
5257 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5258 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5259 if (super_interface) {
5260 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5261 DCHECK(if_table != nullptr);
5262 DCHECK(if_table->GetMethodArray(i) != nullptr);
5263 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005264 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005265 AsObjectArray<mirror::ArtMethod>());
5266 // We are overwriting a super class interface, try to only virtual methods instead of the
5267 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005268 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005269 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005270 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005271 // A new interface, we need the whole vtable incase a new interface method is implemented
5272 // in the whole superclass.
5273 input_array = vtable;
5274 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005275 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005276 CHECK(self->IsExceptionPending()); // OOME.
5277 return false;
5278 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005279 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005280 if (input_array.Get() == nullptr) {
5281 // If the added virtual methods is empty, do nothing.
5282 DCHECK(super_interface);
5283 continue;
5284 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005285 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005286 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005287 MethodNameAndSignatureComparator interface_name_comparator(
5288 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005289 int32_t k;
5290 // For each method listed in the interface's method list, find the
5291 // matching method in our class's method list. We want to favor the
5292 // subclass over the superclass, which just requires walking
5293 // back from the end of the vtable. (This only matters if the
5294 // superclass defines a private method and this class redefines
5295 // it -- otherwise it would use the same vtable slot. In .dex files
5296 // those don't end up in the virtual method table, so it shouldn't
5297 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005298 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5299 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005300 mirror::ArtMethod* vtable_method_for_name_comparison =
5301 vtable_method->GetInterfaceMethodIfProxy();
5302 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005303 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005304 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005305 ThrowIllegalAccessError(
5306 klass.Get(),
5307 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005308 PrettyMethod(vtable_method).c_str(),
5309 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005310 return false;
5311 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005312 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005313 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005314 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5315 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5316 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5317 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5318 out_imt->SetReference(imt_index, vtable_method);
5319 } else if (imt_ref != conflict_method) {
5320 // If we are not a conflict and we have the same signature and name as the imt entry,
5321 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005322 MethodNameAndSignatureComparator imt_ref_name_comparator(
5323 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005324 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005325 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005326 out_imt->SetReference(imt_index, vtable_method);
5327 } else {
5328 out_imt->SetReference(imt_index, conflict_method);
5329 }
Jeff Hao88474b42013-10-23 16:24:40 -07005330 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005331 break;
5332 }
5333 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005334 if (k < 0 && !super_interface) {
5335 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005336 for (size_t l = 0; l < miranda_list_size; ++l) {
5337 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005338 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005339 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005340 break;
5341 }
5342 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005343 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005344 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005345 miranda_method = interface_method->Clone(self)->AsArtMethod();
5346 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005347 CHECK(self->IsExceptionPending()); // OOME.
5348 return false;
5349 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005350 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005351 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005352 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005353 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005354 }
5355 }
5356 }
5357 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005358 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005359 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005360 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005361 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5362 if (old_method_count == 0) {
5363 virtuals = AllocArtMethodArray(self, new_method_count);
5364 } else {
5365 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5366 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005367 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005368 CHECK(self->IsExceptionPending()); // OOME.
5369 return false;
5370 }
5371 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005372
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005373 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005374 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005375 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005376 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005377 CHECK(self->IsExceptionPending()); // OOME.
5378 return false;
5379 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005380 for (size_t i = 0; i < miranda_list_size; ++i) {
5381 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005382 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005383 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5384 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5385 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005386 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005387 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005388 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005389 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005390 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005391
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005392 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005393 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5394 for (int i = 0; i < check_vtable->GetLength(); ++i) {
5395 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005396 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005397 }
5398
Ian Rogers7b078e82014-09-10 14:44:24 -07005399 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005400 return true;
5401}
5402
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005403bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005404 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005405 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005406}
5407
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005408bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005409 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005410 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005411}
5412
Brian Carlstromdbc05252011-09-09 01:59:59 -07005413struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005414 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5415 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005416 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005417 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005418 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005419 // 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 -07005420 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5421 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005422 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005423 if (type1 == Primitive::kPrimNot) {
5424 // Reference always goes first.
5425 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005426 }
Vladimir Markod5777482014-11-12 17:02:02 +00005427 if (type2 == Primitive::kPrimNot) {
5428 // Reference always goes first.
5429 return false;
5430 }
5431 size_t size1 = Primitive::ComponentSize(type1);
5432 size_t size2 = Primitive::ComponentSize(type2);
5433 if (size1 != size2) {
5434 // Larger primitive types go first.
5435 return size1 > size2;
5436 }
5437 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5438 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005439 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005440 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5441 // by name and for equal names by type id index.
5442 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5443 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005444 }
5445};
5446
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005447bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005448 size_t* class_size) {
5449 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005450 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005451 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005452
Brian Carlstromea46f952013-07-30 01:26:50 -07005453 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005454 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005455
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005456 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005457 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005458 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00005459 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005460 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005461 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005462 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005463 CHECK(super_class->IsResolved())
5464 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005465 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005466 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005467 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005468
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005469 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005470
Brian Carlstromdbc05252011-09-09 01:59:59 -07005471 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005472 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005473 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005474 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005475 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005476 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005477 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005478 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005479 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005480 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005481 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5482 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005483
Fred Shih381e4ca2014-08-25 17:24:27 -07005484 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005485 size_t current_field = 0;
5486 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005487 FieldGaps gaps;
5488
Brian Carlstromdbc05252011-09-09 01:59:59 -07005489 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005490 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005491 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005492 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005493 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005494 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005495 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005496 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5497 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005498 MemberOffset old_offset = field_offset;
5499 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5500 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5501 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005502 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005503 grouped_and_sorted_fields.pop_front();
5504 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005505 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005506 field_offset = MemberOffset(field_offset.Uint32Value() +
5507 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005508 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005509 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5510 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005511 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5512 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5513 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5514 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005515 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5516 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005517 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005518
Elliott Hughesadb460d2011-10-05 17:02:34 -07005519 // 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 -07005520 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005521 // We know there are no non-reference fields in the Reference classes, and we know
5522 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005523 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005524 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005525 --num_reference_fields;
5526 }
5527
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005528 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005529 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005530 if (is_static) {
5531 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005532 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005533 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005534 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005535 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08005536 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
Jeff Haoc7d11882015-02-03 15:08:39 -08005537 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
5538 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartier2d721012014-11-10 11:08:06 -08005539 } else {
5540 std::string temp;
5541 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5542 size_t previous_size = klass->GetObjectSize();
5543 if (previous_size != 0) {
5544 // Make sure that we didn't originally have an incorrect size.
5545 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5546 }
5547 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005548 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005549 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005550 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005551
5552 if (kIsDebugBuild) {
5553 // Make sure that the fields array is ordered by name but all reference
5554 // offsets are at the beginning as far as alignment allows.
5555 MemberOffset start_ref_offset = is_static
5556 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5557 : klass->GetFirstReferenceInstanceFieldOffset();
5558 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5559 num_reference_fields *
5560 sizeof(mirror::HeapReference<mirror::Object>));
5561 MemberOffset current_ref_offset = start_ref_offset;
5562 for (size_t i = 0; i < num_fields; i++) {
5563 mirror::ArtField* field = fields->Get(i);
5564 if ((false)) { // enable to debug field layout
5565 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5566 << " class=" << PrettyClass(klass.Get())
5567 << " field=" << PrettyField(field)
5568 << " offset="
5569 << field->GetField32(mirror::ArtField::OffsetOffset());
5570 }
5571 if (i != 0) {
5572 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005573 // NOTE: The field names can be the same. This is not possible in the Java language
5574 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5575 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005576 }
5577 Primitive::Type type = field->GetTypeAsPrimitiveType();
5578 bool is_primitive = type != Primitive::kPrimNot;
5579 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5580 strcmp("referent", field->GetName()) == 0) {
5581 is_primitive = true; // We lied above, so we have to expect a lie here.
5582 }
5583 MemberOffset offset = field->GetOffsetDuringLinking();
5584 if (is_primitive) {
5585 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5586 // Shuffled before references.
5587 size_t type_size = Primitive::ComponentSize(type);
5588 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5589 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5590 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5591 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5592 }
5593 } else {
5594 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5595 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5596 sizeof(mirror::HeapReference<mirror::Object>));
5597 }
5598 }
5599 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5600 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005601 return true;
5602}
5603
Vladimir Marko76649e82014-11-10 18:32:59 +00005604// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005605void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005606 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005607 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005608 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005609 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005610 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005611 // Compute reference offsets unless our superclass overflowed.
5612 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5613 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005614 if (num_reference_fields != 0u) {
5615 // All of the fields that contain object references are guaranteed be grouped in memory
5616 // starting at an appropriately aligned address after super class object data.
5617 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5618 sizeof(mirror::HeapReference<mirror::Object>));
5619 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005620 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005621 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005622 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005623 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005624 reference_offsets |= (0xffffffffu << start_bit) &
5625 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005626 }
5627 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005628 }
5629 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005630 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005631}
5632
Mathieu Chartier590fee92013-09-13 13:46:47 -07005633mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005634 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005635 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005636 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005637 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005638 return resolved;
5639 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005640 uint32_t utf16_length;
5641 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005642 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005643 dex_cache->SetResolvedString(string_idx, string);
5644 return string;
5645}
5646
Mathieu Chartier590fee92013-09-13 13:46:47 -07005647mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005648 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005649 StackHandleScope<2> hs(Thread::Current());
5650 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5651 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005652 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5653}
5654
5655mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005656 Handle<mirror::DexCache> dex_cache,
5657 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005658 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005659 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005660 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005661 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005662 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005663 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005664 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005665 // TODO: we used to throw here if resolved's class loader was not the
5666 // boot class loader. This was to permit different classes with the
5667 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005668 dex_cache->SetResolvedType(type_idx, resolved);
5669 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005670 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005671 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005672 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005673 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005674 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08005675 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005676 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005677 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005678 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005679 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005680 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005681 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005682 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005683 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005684 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005685 return resolved;
5686}
5687
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005688mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005689 Handle<mirror::DexCache> dex_cache,
5690 Handle<mirror::ClassLoader> class_loader,
5691 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005692 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005693 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005694 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005695 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005696 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005697 return resolved;
5698 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005699 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005700 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005701 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005702 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005703 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005704 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005705 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005706 // Scan using method_idx, this saves string compares but will only hit for matching dex
5707 // caches/files.
5708 switch (type) {
5709 case kDirect: // Fall-through.
5710 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005711 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005712 break;
5713 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005714 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005715 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005716 break;
5717 case kSuper: // Fall-through.
5718 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005719 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005720 break;
5721 default:
5722 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005723 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005724 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005725 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005726 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005727 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005728 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005729 switch (type) {
5730 case kDirect: // Fall-through.
5731 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005732 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005733 break;
5734 case kInterface:
5735 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005736 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005737 break;
5738 case kSuper: // Fall-through.
5739 case kVirtual:
5740 resolved = klass->FindVirtualMethod(name, signature);
5741 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005742 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005743 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005744 // If we found a method, check for incompatible class changes.
5745 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005746 // Be a good citizen and update the dex cache to speed subsequent calls.
5747 dex_cache->SetResolvedMethod(method_idx, resolved);
5748 return resolved;
5749 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005750 // If we had a method, it's an incompatible-class-change error.
5751 if (resolved != nullptr) {
5752 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5753 } else {
5754 // We failed to find the method which means either an access error, an incompatible class
5755 // change, or no such method. First try to find the method among direct and virtual methods.
5756 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5757 const Signature signature = dex_file.GetMethodSignature(method_id);
5758 switch (type) {
5759 case kDirect:
5760 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005761 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005762 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5763 // have had a resolved method before, which triggers the "true" branch above.
5764 break;
5765 case kInterface:
5766 case kVirtual:
5767 case kSuper:
5768 resolved = klass->FindDirectMethod(name, signature);
5769 break;
5770 }
5771
5772 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005773 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005774 if (resolved != nullptr && referrer.Get() != nullptr) {
5775 mirror::Class* methods_class = resolved->GetDeclaringClass();
5776 mirror::Class* referring_class = referrer->GetDeclaringClass();
5777 if (!referring_class->CanAccess(methods_class)) {
5778 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5779 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005780 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005781 } else if (!referring_class->CanAccessMember(methods_class,
5782 resolved->GetAccessFlags())) {
5783 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005784 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005785 }
5786 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005787 if (!exception_generated) {
5788 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5789 // interface methods and throw if we find the method there. If we find nothing, throw a
5790 // NoSuchMethodError.
5791 switch (type) {
5792 case kDirect:
5793 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005794 if (resolved != nullptr) {
5795 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5796 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005797 resolved = klass->FindInterfaceMethod(name, signature);
5798 if (resolved != nullptr) {
5799 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5800 } else {
5801 ThrowNoSuchMethodError(type, klass, name, signature);
5802 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005803 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005804 break;
5805 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005806 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005807 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5808 } else {
5809 resolved = klass->FindVirtualMethod(name, signature);
5810 if (resolved != nullptr) {
5811 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5812 } else {
5813 ThrowNoSuchMethodError(type, klass, name, signature);
5814 }
5815 }
5816 break;
5817 case kSuper:
5818 if (resolved != nullptr) {
5819 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005820 } else {
5821 ThrowNoSuchMethodError(type, klass, name, signature);
5822 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005823 break;
5824 case kVirtual:
5825 if (resolved != nullptr) {
5826 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5827 } else {
5828 resolved = klass->FindInterfaceMethod(name, signature);
5829 if (resolved != nullptr) {
5830 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5831 } else {
5832 ThrowNoSuchMethodError(type, klass, name, signature);
5833 }
5834 }
5835 break;
5836 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005837 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005838 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005839 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005840 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005841 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005842}
5843
Mathieu Chartier590fee92013-09-13 13:46:47 -07005844mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005845 Handle<mirror::DexCache> dex_cache,
5846 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005847 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005848 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005849 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005850 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005851 return resolved;
5852 }
5853 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005854 Thread* const self = Thread::Current();
5855 StackHandleScope<1> hs(self);
5856 Handle<mirror::Class> klass(
5857 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005858 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005859 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005860 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005861 }
5862
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005863 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005864 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005865 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005866 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005867 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005868
Andreas Gampe58a5af82014-07-31 16:23:49 -07005869 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005870 const char* name = dex_file.GetFieldName(field_id);
5871 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5872 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005873 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005874 } else {
5875 resolved = klass->FindInstanceField(name, type);
5876 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005877 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005878 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005879 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005880 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005881 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005882 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005883 return resolved;
5884}
5885
Brian Carlstromea46f952013-07-30 01:26:50 -07005886mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005887 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005888 Handle<mirror::DexCache> dex_cache,
5889 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005890 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005891 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005892 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005893 return resolved;
5894 }
5895 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005896 Thread* self = Thread::Current();
5897 StackHandleScope<1> hs(self);
5898 Handle<mirror::Class> klass(
5899 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005900 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005901 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005902 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005903 }
5904
Ian Rogersdfb325e2013-10-30 01:00:44 -07005905 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5906 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005907 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005908 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005909 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005910 dex_cache->SetResolvedField(field_idx, resolved);
5911 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005912 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005913 }
5914 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005915}
5916
Brian Carlstromea46f952013-07-30 01:26:50 -07005917const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005918 uint32_t* length) {
5919 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5920 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005921 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005922 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005923 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005924}
5925
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005926void ClassLinker::DumpAllClasses(int flags) {
5927 if (dex_cache_image_class_lookup_required_) {
5928 MoveImageClassesToClassTable();
5929 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005930 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5931 // 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 -08005932 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005933 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005934 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005935 for (GcRoot<mirror::Class>& it : class_table_) {
5936 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005937 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005938 }
5939
5940 for (size_t i = 0; i < all_classes.size(); ++i) {
5941 all_classes[i]->DumpClass(std::cerr, flags);
5942 }
5943}
5944
Elliott Hughes956af0f2014-12-11 14:34:28 -08005945static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005946 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005947 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5948 base -= sizeof(void*); // Move backward so that code_offset != 0.
5949 const uint32_t code_offset = sizeof(void*);
5950 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005951}
5952
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005953bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5954 return (entry_point == GetQuickResolutionStub()) ||
5955 (quick_resolution_trampoline_ == entry_point);
5956}
5957
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005958bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5959 return (entry_point == GetQuickToInterpreterBridge()) ||
5960 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5961}
5962
5963bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5964 return (entry_point == GetQuickGenericJniStub()) ||
5965 (quick_generic_jni_trampoline_ == entry_point);
5966}
5967
5968const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5969 return GetQuickGenericJniStub();
5970}
5971
Elliott Hughes956af0f2014-12-11 14:34:28 -08005972void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5973 const void* method_code) const {
5974 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005975 oat_method.LinkMethod(method);
5976 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005977}
5978
5979void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5980 if (!method->IsNative()) {
5981 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005982 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5983 } else {
5984 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005985 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005986 oat_method.LinkMethod(method);
5987 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005988 }
5989}
5990
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005991void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005992 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005993 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005994 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005995 MoveImageClassesToClassTable();
5996 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005997 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005998 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5999 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07006000}
6001
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006002size_t ClassLinker::NumLoadedClasses() {
6003 if (dex_cache_image_class_lookup_required_) {
6004 MoveImageClassesToClassTable();
6005 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07006006 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006007 // Only return non zygote classes since these are the ones which apps which care about.
6008 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07006009}
6010
Brian Carlstrom47d237a2011-10-18 15:08:33 -07006011pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07006012 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07006013}
6014
6015pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07006016 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07006017}
6018
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08006019void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006020 DCHECK(!init_done_);
6021
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006022 DCHECK(klass != nullptr);
6023 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006024
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07006025 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006026 DCHECK(class_roots != nullptr);
6027 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07006028 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006029}
6030
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006031const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
6032 static const char* class_roots_descriptors[] = {
6033 "Ljava/lang/Class;",
6034 "Ljava/lang/Object;",
6035 "[Ljava/lang/Class;",
6036 "[Ljava/lang/Object;",
6037 "Ljava/lang/String;",
6038 "Ljava/lang/DexCache;",
6039 "Ljava/lang/ref/Reference;",
6040 "Ljava/lang/reflect/ArtField;",
6041 "Ljava/lang/reflect/ArtMethod;",
6042 "Ljava/lang/reflect/Proxy;",
6043 "[Ljava/lang/String;",
6044 "[Ljava/lang/reflect/ArtField;",
6045 "[Ljava/lang/reflect/ArtMethod;",
6046 "Ljava/lang/ClassLoader;",
6047 "Ljava/lang/Throwable;",
6048 "Ljava/lang/ClassNotFoundException;",
6049 "Ljava/lang/StackTraceElement;",
6050 "Z",
6051 "B",
6052 "C",
6053 "D",
6054 "F",
6055 "I",
6056 "J",
6057 "S",
6058 "V",
6059 "[Z",
6060 "[B",
6061 "[C",
6062 "[D",
6063 "[F",
6064 "[I",
6065 "[J",
6066 "[S",
6067 "[Ljava/lang/StackTraceElement;",
6068 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08006069 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
6070 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006071
6072 const char* descriptor = class_roots_descriptors[class_root];
6073 CHECK(descriptor != nullptr);
6074 return descriptor;
6075}
6076
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006077std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
6078 const {
6079 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006080 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006081}
6082
6083bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
6084 const GcRoot<mirror::Class>& b) {
6085 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
6086 return false;
6087 }
6088 std::string temp;
6089 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
6090}
6091
6092std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
6093 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006094 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006095}
6096
6097bool ClassLinker::ClassDescriptorHashEquals::operator()(
6098 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
6099 if (a.Read()->GetClassLoader() != b.second) {
6100 return false;
6101 }
6102 return a.Read()->DescriptorEquals(b.first);
6103}
6104
6105bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
6106 const char* descriptor) {
6107 return a.Read()->DescriptorEquals(descriptor);
6108}
6109
6110std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006111 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006112}
6113
Sebastien Hertz6963e442014-11-26 22:11:27 +01006114bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
6115 // Non-image methods don't use direct code pointer.
6116 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
6117 return false;
6118 }
6119 if (m->IsPrivate()) {
6120 // The method can only be called inside its own oat file. Therefore it won't be called using
6121 // its direct code if the oat file has been compiled in PIC mode.
6122 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
6123 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
6124 const OatFile::OatDexFile* oat_dex_file = class_linker->FindOpenedOatDexFileForDexFile(dex_file);
6125 if (oat_dex_file == nullptr) {
6126 // No oat file: the method has not been compiled.
6127 return false;
6128 }
6129 const OatFile* oat_file = oat_dex_file->GetOatFile();
6130 return oat_file != nullptr && !oat_file->IsPic();
6131 } else {
6132 // The method can be called outside its own oat file. Therefore it won't be called using its
6133 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
6134 ReaderMutexLock mu(Thread::Current(), dex_lock_);
6135 for (const OatFile* oat_file : oat_files_) {
6136 if (!oat_file->IsPic()) {
6137 return true;
6138 }
6139 }
6140 return false;
6141 }
6142}
6143
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006144} // namespace art