blob: afb2a06461500b74ef8701e62e72dd6355f768c1 [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();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +000085 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080086 va_end(args);
87}
88
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080089static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070090 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070091 // The class failed to initialize on a previous attempt, so we want to throw
92 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
93 // failed in verification, in which case v2 5.4.1 says we need to re-throw
94 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080095 Runtime* const runtime = Runtime::Current();
96 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -070097 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
98 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -070099
Elliott Hughes5c599942012-06-13 16:45:05 -0700100 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800101 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800102 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700103 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
104 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000105 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700106 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700107 if (c->GetVerifyErrorClass() != NULL) {
108 // TODO: change the verifier to store an _instance_, with a useful detail message?
109 std::string temp;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000110 self->ThrowNewException(c->GetVerifyErrorClass()->GetDescriptor(&temp),
Ian Rogers7b078e82014-09-10 14:44:24 -0700111 PrettyDescriptor(c).c_str());
112 } else {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000113 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
Ian Rogers7b078e82014-09-10 14:44:24 -0700114 PrettyDescriptor(c).c_str());
115 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700116 }
117}
118
Brian Carlstromb23eab12014-10-08 17:55:21 -0700119static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
120 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
121 if (VLOG_IS_ON(class_linker)) {
122 std::string temp;
123 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000124 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700125 }
126}
127
128static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
129 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700130 Thread* self = Thread::Current();
131 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700132
133 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700134 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700135
136 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700137 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
138 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700139
Elliott Hughesa4f94742012-05-29 16:28:38 -0700140 // We only wrap non-Error exceptions; an Error can just be used as-is.
141 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000142 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700143 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700144 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700145}
146
Fred Shih381e4ca2014-08-25 17:24:27 -0700147// Gap between two fields in object layout.
148struct FieldGap {
149 uint32_t start_offset; // The offset from the start of the object.
150 uint32_t size; // The gap size of 1, 2, or 4 bytes.
151};
152struct FieldGapsComparator {
153 explicit FieldGapsComparator() {
154 }
155 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
156 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800157 // Sort by gap size, largest first. Secondary sort by starting offset.
158 return lhs.size > rhs.size || (lhs.size == rhs.size && lhs.start_offset < rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700159 }
160};
161typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
162
163// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800164static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700165 DCHECK(gaps != nullptr);
166
167 uint32_t current_offset = gap_start;
168 while (current_offset != gap_end) {
169 size_t remaining = gap_end - current_offset;
170 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
171 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
172 current_offset += sizeof(uint32_t);
173 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
174 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
175 current_offset += sizeof(uint16_t);
176 } else {
177 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
178 current_offset += sizeof(uint8_t);
179 }
180 DCHECK_LE(current_offset, gap_end) << "Overran gap";
181 }
182}
183// Shuffle fields forward, making use of gaps whenever possible.
184template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000185static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700186 MemberOffset* field_offset,
Fred Shih381e4ca2014-08-25 17:24:27 -0700187 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
188 FieldGaps* gaps)
189 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
190 DCHECK(current_field_idx != nullptr);
191 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700192 DCHECK(gaps != nullptr);
193 DCHECK(field_offset != nullptr);
194
195 DCHECK(IsPowerOfTwo(n));
196 while (!grouped_and_sorted_fields->empty()) {
197 mirror::ArtField* field = grouped_and_sorted_fields->front();
198 Primitive::Type type = field->GetTypeAsPrimitiveType();
199 if (Primitive::ComponentSize(type) < n) {
200 break;
201 }
202 if (!IsAligned<n>(field_offset->Uint32Value())) {
203 MemberOffset old_offset = *field_offset;
204 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
205 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
206 }
207 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
208 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700209 if (!gaps->empty() && gaps->top().size >= n) {
210 FieldGap gap = gaps->top();
211 gaps->pop();
212 DCHECK(IsAligned<n>(gap.start_offset));
213 field->SetOffset(MemberOffset(gap.start_offset));
214 if (gap.size > n) {
215 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
216 }
217 } else {
218 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
219 field->SetOffset(*field_offset);
220 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
221 }
222 ++(*current_field_idx);
223 }
224}
225
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800226ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700227 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700228 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700229 dex_cache_image_class_lookup_required_(false),
230 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800231 class_roots_(nullptr),
232 array_iftable_(nullptr),
233 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700234 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800235 log_new_dex_caches_roots_(false),
236 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700237 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800238 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800239 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100240 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800241 quick_to_interpreter_bridge_trampoline_(nullptr),
242 image_pointer_size_(sizeof(void*)) {
Ian Rogers98379392014-02-24 16:53:16 -0800243 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700244}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700245
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800246void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800247 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700248 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700249
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700250 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700251
Elliott Hughes30646832011-10-13 16:59:46 -0700252 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700253 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700254 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700255 // 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 -0800256 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700257 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
258 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700259 heap->AllocNonMovableObject<true>(self, nullptr,
260 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700261 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700262 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700263 mirror::Class::SetClassClass(java_lang_Class.Get());
264 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700265 if (kUseBakerOrBrooksReadBarrier) {
266 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800267 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700268 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700269 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800270 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800271 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700272
Elliott Hughes418d20f2011-09-22 14:00:39 -0700273 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700274 Handle<mirror::Class> class_array_class(hs.NewHandle(
275 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700276 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700277
Ian Rogers23435d02012-09-24 11:23:12 -0700278 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700279 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
280 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700281 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700282 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700283 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700284 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700285
Ian Rogers23435d02012-09-24 11:23:12 -0700286 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700287 Handle<mirror::Class> object_array_class(hs.NewHandle(
288 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700289 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700290
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700291 // Setup the char (primitive) class to be used for char[].
292 Handle<mirror::Class> char_class(hs.NewHandle(
293 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700294 // The primitive char class won't be initialized by
295 // InitializePrimitiveClass until line 459, but strings (and
296 // internal char arrays) will be allocated before that and the
297 // component size, which is computed from the primitive type, needs
298 // to be set here.
299 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700300
Ian Rogers23435d02012-09-24 11:23:12 -0700301 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700302 Handle<mirror::Class> char_array_class(hs.NewHandle(
303 AllocClass(self, java_lang_Class.Get(),
304 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700305 char_array_class->SetComponentType(char_class.Get());
306 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700307
Ian Rogers23435d02012-09-24 11:23:12 -0700308 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700309 Handle<mirror::Class> java_lang_String(hs.NewHandle(
310 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700311 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700312 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700313 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400314
Fred Shih4ee7a662014-07-11 09:59:27 -0700315 // Setup Reference.
316 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
317 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
318 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
319 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
320 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
321
Ian Rogers23435d02012-09-24 11:23:12 -0700322 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700323 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
324 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
325 kClassRootsMax));
326 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700327 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
328 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
329 SetClassRoot(kClassArrayClass, class_array_class.Get());
330 SetClassRoot(kObjectArrayClass, object_array_class.Get());
331 SetClassRoot(kCharArrayClass, char_array_class.Get());
332 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700333 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700334
335 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700336 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
337 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
338 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
339 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
340 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
341 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
342 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
343 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700344
Ian Rogers23435d02012-09-24 11:23:12 -0700345 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700346 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700347
Ian Rogers23435d02012-09-24 11:23:12 -0700348 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700349 Handle<mirror::Class> int_array_class(hs.NewHandle(
350 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700352 mirror::IntArray::SetArrayClass(int_array_class.Get());
353 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700354
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700355 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700356
Ian Rogers52813c92012-10-11 11:50:38 -0700357 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700358 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
359 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700360 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700361 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700362 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700363
Brian Carlstromf3632832014-05-20 15:36:53 -0700364 // Constructor, Field, Method, and AbstractMethod are necessary so
365 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700366 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
367 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700368 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700369 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700370 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700371 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700372 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700373
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700374 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
375 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700376 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800377 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
378 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700379 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700380 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700381 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700382
383 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700384 Handle<mirror::Class> object_array_string(hs.NewHandle(
385 AllocClass(self, java_lang_Class.Get(),
386 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700387 object_array_string->SetComponentType(java_lang_String.Get());
388 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700389
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700390 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
391 AllocClass(self, java_lang_Class.Get(),
392 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700393 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
394 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700395
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700396 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
397 AllocClass(self, java_lang_Class.Get(),
398 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700399 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
400 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700401
Ian Rogers23435d02012-09-24 11:23:12 -0700402 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
403 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
404 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700405 CHECK_NE(0U, boot_class_path.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800406 for (auto& dex_file : boot_class_path) {
407 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700408 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800409 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700410 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700411
412 // now we can use FindSystemClass
413
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700414 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700415 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
416 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700417
Jeff Hao88474b42013-10-23 16:24:40 -0700418 // Create runtime resolution and imt conflict methods. Also setup the default imt.
419 Runtime* runtime = Runtime::Current();
420 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
421 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700422 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700423 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
424
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700425 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
426 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700427 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800428 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700429 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700430 quick_resolution_trampoline_ = GetQuickResolutionStub();
431 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
432 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700433 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700434
Mathieu Chartier66f19252012-09-18 08:57:04 -0700435 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700436 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800437 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700438 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700439 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700440 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800441 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700442 std::ostringstream os1, os2;
443 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
444 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
445 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
446 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700447 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800448 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700449 CHECK_EQ(java_lang_String.Get(), String_class);
450 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700451 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700452
Ian Rogers23435d02012-09-24 11:23:12 -0700453 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800454 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800455 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700456
Ian Rogers98379392014-02-24 16:53:16 -0800457 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800458 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459
Ian Rogers98379392014-02-24 16:53:16 -0800460 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700461 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700462
Ian Rogers98379392014-02-24 16:53:16 -0800463 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800464 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700465
Ian Rogers98379392014-02-24 16:53:16 -0800466 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700467 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700468
Ian Rogers98379392014-02-24 16:53:16 -0800469 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800470 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700471
Ian Rogers98379392014-02-24 16:53:16 -0800472 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800473 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700474
Ian Rogers98379392014-02-24 16:53:16 -0800475 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800476 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700477
Ian Rogers98379392014-02-24 16:53:16 -0800478 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700479 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700480
Ian Rogers98379392014-02-24 16:53:16 -0800481 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700482 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700483
Ian Rogers23435d02012-09-24 11:23:12 -0700484 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800485 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700486 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800487 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700488 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700489 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
490 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700491 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700492 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700493 array_iftable->SetInterface(0, java_lang_Cloneable);
494 array_iftable->SetInterface(1, java_io_Serializable);
495 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700496
Ian Rogers23435d02012-09-24 11:23:12 -0700497 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700498 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
499 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
500 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
501 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700502 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700503 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800504 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700505 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700506
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700507 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800508 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700509 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700510
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700511 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800512 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700513 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700514
Brian Carlstromf3632832014-05-20 15:36:53 -0700515 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700516 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700517 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700518
Brian Carlstromea46f952013-07-30 01:26:50 -0700519 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700520 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700521 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700522
Brian Carlstromea46f952013-07-30 01:26:50 -0700523 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700524 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700525 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700526
Ian Rogers23435d02012-09-24 11:23:12 -0700527 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700528
Ian Rogers23435d02012-09-24 11:23:12 -0700529 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800530 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700531 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
532
Brian Carlstrom1f870082011-08-23 16:02:11 -0700533 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700534 // finish initializing Reference class
535 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
536 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
537 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
538 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
539 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700540 mirror::Class* java_lang_ref_FinalizerReference =
541 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700542 java_lang_ref_FinalizerReference->SetAccessFlags(
543 java_lang_ref_FinalizerReference->GetAccessFlags() |
544 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700545 mirror::Class* java_lang_ref_PhantomReference =
546 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700547 java_lang_ref_PhantomReference->SetAccessFlags(
548 java_lang_ref_PhantomReference->GetAccessFlags() |
549 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700550 mirror::Class* java_lang_ref_SoftReference =
551 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700552 java_lang_ref_SoftReference->SetAccessFlags(
553 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700554 mirror::Class* java_lang_ref_WeakReference =
555 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700556 java_lang_ref_WeakReference->SetAccessFlags(
557 java_lang_ref_WeakReference->GetAccessFlags() |
558 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700559
Ian Rogers23435d02012-09-24 11:23:12 -0700560 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800561 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700562 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700563 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
564
jeffhao8cd6dda2012-02-22 10:15:34 -0800565 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700566 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800567 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800568 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700569 SetClassRoot(kJavaLangClassNotFoundException,
570 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800571 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700572 SetClassRoot(kJavaLangStackTraceElementArrayClass,
573 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800574 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700575
Andreas Gampe76bd8802014-12-10 16:43:58 -0800576 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
577 // initialized.
578 {
579 const DexFile& dex_file = java_lang_Object->GetDexFile();
580 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
581 CHECK(void_string_id != nullptr);
582 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
583 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
584 CHECK(void_type_id != nullptr);
585 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
586 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
587 // as referrer so the used dex cache is core's one.
588 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
589 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
590 self->AssertNoPendingException();
591 }
592
Ian Rogers98379392014-02-24 16:53:16 -0800593 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700594
Brian Carlstroma004aa92012-02-08 18:05:09 -0800595 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700596}
597
Ian Rogers98379392014-02-24 16:53:16 -0800598void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800599 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700600
601 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700602 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700603 // as the types of the field can't be resolved prior to the runtime being
604 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800605 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700606 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800607 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800608
Brian Carlstromea46f952013-07-30 01:26:50 -0700609 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700610 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
611 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700612
Brian Carlstromea46f952013-07-30 01:26:50 -0700613 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700614 CHECK_STREQ(queue->GetName(), "queue");
615 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700616
Brian Carlstromea46f952013-07-30 01:26:50 -0700617 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700618 CHECK_STREQ(queueNext->GetName(), "queueNext");
619 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700620
Brian Carlstromea46f952013-07-30 01:26:50 -0700621 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700622 CHECK_STREQ(referent->GetName(), "referent");
623 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700624
Brian Carlstromea46f952013-07-30 01:26:50 -0700625 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700626 CHECK_STREQ(zombie->GetName(), "zombie");
627 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700628
Brian Carlstroma663ea52011-08-19 23:33:41 -0700629 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700630 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700631 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800632 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700633 CHECK(klass != nullptr);
634 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700635 // note SetClassRoot does additional validation.
636 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700637 }
638
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700639 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700640
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700641 // disable the slow paths in FindClass and CreatePrimitiveClass now
642 // that Object, Class, and Object[] are setup
643 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700644
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800645 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700646}
647
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700648void ClassLinker::RunRootClinits() {
649 Thread* self = Thread::Current();
650 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800651 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700652 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700653 StackHandleScope<1> hs(self);
654 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700655 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700656 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700657 }
658 }
659}
660
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700661bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800662 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000663 const char* oat_cache_filename,
664 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700665 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700666 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800667
Ian Rogers1d54e732013-05-02 21:10:01 -0700668 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800669 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700670 if (heap->GetImageSpace() == nullptr) {
671 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
672 // out of space anyway it might not matter.
673 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
674 "without an image.", dex_filename);
675 return false;
676 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700677 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800678
Brian Carlstrom6449c622014-02-10 23:48:36 -0800679 std::string dex_file_option("--dex-file=");
680 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800681
Brian Carlstrom6449c622014-02-10 23:48:36 -0800682 std::string oat_fd_option("--oat-fd=");
683 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800684
Brian Carlstrom6449c622014-02-10 23:48:36 -0800685 std::string oat_location_option("--oat-location=");
686 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800687
Brian Carlstrom6449c622014-02-10 23:48:36 -0800688 std::vector<std::string> argv;
689 argv.push_back(dex2oat);
690 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800691 argv.push_back("-classpath");
692 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800693 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800694
Ian Rogers8afeb852014-04-02 14:55:49 -0700695 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800696
Jeff Hao4a200f52014-04-01 14:58:49 -0700697 if (!Runtime::Current()->IsVerificationEnabled()) {
698 argv.push_back("--compiler-filter=verify-none");
699 }
700
Alex Light6e183f22014-07-18 14:57:04 -0700701 if (Runtime::Current()->MustRelocateIfPossible()) {
702 argv.push_back("--runtime-arg");
703 argv.push_back("-Xrelocate");
704 } else {
705 argv.push_back("--runtime-arg");
706 argv.push_back("-Xnorelocate");
707 }
708
Brian Carlstrom6449c622014-02-10 23:48:36 -0800709 if (!kIsTargetBuild) {
710 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700711 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700712
Brian Carlstrom6449c622014-02-10 23:48:36 -0800713 argv.push_back(boot_image_option);
714 argv.push_back(dex_file_option);
715 argv.push_back(oat_fd_option);
716 argv.push_back(oat_location_option);
717 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800718 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800719 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700720 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800721
Andreas Gampea696c0a2014-12-10 20:51:45 -0800722 if (!Exec(argv, error_msg)) {
723 // Manually delete the file. Ensures there is no garbage left over if the process unexpectedly
724 // died. Ignore unlink failure, propagate the original error.
725 TEMP_FAILURE_RETRY(unlink(oat_cache_filename));
726 return false;
727 }
728
729 return true;
jeffhao262bf462011-10-20 18:36:32 -0700730}
731
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700732const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700733 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800734 if (kIsDebugBuild) {
735 for (size_t i = 0; i < oat_files_.size(); ++i) {
736 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700737 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800738 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700739 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
740 oat_files_.push_back(oat_file);
741 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800742}
743
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700744OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
745 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700746 OatFile* oat_file = space->ReleaseOatFile();
747 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700748 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700749 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700750}
751
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100752const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800753 const char* dex_location = dex_file.GetLocation().c_str();
754 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100755 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800756}
757
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100758const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
759 const char* dex_location,
760 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700761 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100762 for (const OatFile* oat_file : oat_files_) {
763 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700764
765 if (oat_location != nullptr) {
766 if (oat_file->GetLocation() != oat_location) {
767 continue;
768 }
769 }
770
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700771 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800772 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700773 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100774 if (oat_dex_file != nullptr) {
775 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800776 }
777 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100778 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800779}
780
Calin Juravle621962a2014-09-02 15:53:55 +0100781
782// Loads all multi dex files from the given oat file returning true on success.
783//
784// Parameters:
785// oat_file - the oat file to load from
786// dex_location - the dex location used to generate the oat file
787// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
788// generated - whether or not the oat_file existed before or was just (re)generated
789// error_msgs - any error messages will be appended here
790// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
791static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
792 const char* dex_location,
793 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700794 bool generated,
795 std::vector<std::string>* error_msgs,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800796 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700797 if (oat_file == nullptr) {
798 return false;
799 }
800
801 size_t old_size = dex_files->size(); // To rollback on error.
802
803 bool success = true;
804 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100805 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700806 const char* next_name = next_name_str.c_str();
807
Calin Juravle621962a2014-09-02 15:53:55 +0100808 uint32_t next_location_checksum;
809 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700810 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100811 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
812 // When i=0 the multidex name should be the same as the location name. We already have the
813 // checksum it so we don't need to recompute it.
814 if (dex_location_checksum == nullptr) {
815 next_location_checksum_pointer = nullptr;
816 } else {
817 next_location_checksum = *dex_location_checksum;
818 }
819 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700820 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100821 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700822 }
823
824 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
825
826 if (oat_dex_file == nullptr) {
827 if (i == 0 && generated) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700828 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100829 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700830 oat_file->GetLocation().c_str());
831 error_msgs->push_back(error_msg);
832 }
833 break; // Not found, done.
834 }
835
836 // Checksum test. Test must succeed when generated.
837 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100838 if (next_location_checksum_pointer != nullptr) {
839 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700840 }
841
842 if (success) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800843 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
844 if (dex_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700845 success = false;
846 error_msgs->push_back(error_msg);
847 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800848 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700849 }
850 }
851
852 // When we generated the file, we expect success, or something is terribly wrong.
853 CHECK_EQ(false, generated && !success)
854 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100855 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700856 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
857 }
858
859 if (dex_files->size() == old_size) {
860 success = false; // We did not even find classes.dex
861 }
862
863 if (success) {
864 return true;
865 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800866 dex_files->erase(dex_files->begin() + old_size, dex_files->end());
Andreas Gampe833a4852014-05-21 18:46:59 -0700867 return false;
868 }
869}
870
871// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
872// complicates the loading process, as we should not use an iterative loading process, because that
873// would register the oat file and dex files that come before the broken one. Instead, check all
874// multidex ahead of time.
875bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
876 std::vector<std::string>* error_msgs,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800877 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700878 // 1) Check whether we have an open oat file.
879 // This requires a dex checksum, use the "primary" one.
880 uint32_t dex_location_checksum;
881 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
882 bool have_checksum = true;
883 std::string checksum_error_msg;
884 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100885 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700886 dex_location_checksum_pointer = nullptr;
887 have_checksum = false;
888 }
889
890 bool needs_registering = false;
891
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100892 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
893 dex_location_checksum_pointer);
894 std::unique_ptr<const OatFile> open_oat_file(
895 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700896
897 // 2) If we do not have an open one, maybe there's one on disk already.
898
899 // In case the oat file is not open, we play a locking game here so
900 // that if two different processes race to load and register or generate
901 // (or worse, one tries to open a partial generated file) we will be okay.
902 // This is actually common with apps that use DexClassLoader to work
903 // around the dex method reference limit and that have a background
904 // service running in a separate process.
905 ScopedFlock scoped_flock;
906
907 if (open_oat_file.get() == nullptr) {
908 if (oat_location != nullptr) {
909 // Can only do this if we have a checksum, else error.
910 if (!have_checksum) {
911 error_msgs->push_back(checksum_error_msg);
912 return false;
913 }
914
915 std::string error_msg;
916
917 // We are loading or creating one in the future. Time to set up the file lock.
918 if (!scoped_flock.Init(oat_location, &error_msg)) {
919 error_msgs->push_back(error_msg);
920 return false;
921 }
922
Alex Lighta59dd802014-07-02 16:28:08 -0700923 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700924 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
925 oat_location, &error_msg));
926
927 if (open_oat_file.get() == nullptr) {
928 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
929 dex_location, oat_location, error_msg.c_str());
930 VLOG(class_linker) << compound_msg;
931 error_msgs->push_back(compound_msg);
932 }
933 } else {
934 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100935 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700936 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
937 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100938 kRuntimeISA, error_msgs,
939 &obsolete_file_cleanup_failed));
940 // There's no point in going forward and eventually try to regenerate the
941 // file if we couldn't remove the obsolete one. Mostly likely we will fail
942 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100943 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
944 if (obsolete_file_cleanup_failed) {
945 return false;
946 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700947 }
948 needs_registering = true;
949 }
950
951 // 3) If we have an oat file, check all contained multidex files for our dex_location.
952 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100953 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
954 dex_location_checksum_pointer,
955 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700956 if (success) {
957 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
958 if (needs_registering) {
959 // We opened the oat file, so we must register it.
960 RegisterOatFile(oat_file);
961 }
Alex Light9dcc4572014-08-14 14:16:26 -0700962 // If the file isn't executable we failed patchoat but did manage to get the dex files.
963 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700964 } else {
965 if (needs_registering) {
966 // We opened it, delete it.
967 open_oat_file.reset();
968 } else {
969 open_oat_file.release(); // Do not delete open oat files.
970 }
971 }
972
973 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
974
975 // Need a checksum, fail else.
976 if (!have_checksum) {
977 error_msgs->push_back(checksum_error_msg);
978 return false;
979 }
980
981 // Look in cache location if no oat_location is given.
982 std::string cache_location;
983 if (oat_location == nullptr) {
984 // Use the dalvik cache.
985 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
986 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
987 oat_location = cache_location.c_str();
988 }
989
Alex Light64ad14d2014-08-19 14:23:13 -0700990 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700991 // Definitely need to lock now.
992 if (!scoped_flock.HasFile()) {
993 std::string error_msg;
994 if (!scoped_flock.Init(oat_location, &error_msg)) {
995 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700996 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -0700997 }
998 }
999
Alex Light64ad14d2014-08-19 14:23:13 -07001000 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001001 // Create the oat file.
1002 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1003 oat_location, error_msgs));
1004 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001005
1006 // Failed, bail.
1007 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001008 // 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 -07001009 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
1010 std::string error_msg;
1011 if (!DexFile::Open(dex_location, dex_location, &error_msg, dex_files)) {
1012 error_msgs->push_back(error_msg);
1013 }
1014 } else {
1015 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
1016 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001017 return false;
1018 }
1019
1020 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001021 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1022 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001023 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001024 if (success) {
1025 RegisterOatFile(open_oat_file.release());
1026 return true;
1027 } else {
1028 return false;
1029 }
1030}
1031
1032const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1033 uint32_t dex_location_checksum,
1034 const char* oat_location,
1035 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001036 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001037 !Runtime::Current()->IsAotCompiler(), error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001038 if (oat_file.get() == nullptr) {
1039 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1040 error_msg->c_str());
1041 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001042 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001043 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001044 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1045 if (image_space != nullptr) {
1046 const ImageHeader& image_header = image_space->GetImageHeader();
1047 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1048 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1049 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1050 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1051 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1052 actual_image_oat_checksum);
1053 return nullptr;
1054 }
1055
1056 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1057 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1058 if (expected_image_oat_offset != actual_image_oat_offset) {
1059 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1060 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1061 actual_image_oat_offset);
1062 return nullptr;
1063 }
1064 int32_t expected_patch_delta = image_header.GetPatchDelta();
1065 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1066 if (expected_patch_delta != actual_patch_delta) {
1067 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1068 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1069 return nullptr;
1070 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001071 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001072
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001073 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1074 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001075 if (oat_dex_file == nullptr) {
1076 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1077 dex_location);
1078 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001079 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001080 uint32_t expected_dex_checksum = dex_location_checksum;
1081 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1082 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001083 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1084 "found 0x%x", oat_location, expected_dex_checksum,
1085 actual_dex_checksum);
1086 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001087 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001088 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1089 if (dex_file.get() != nullptr) {
1090 return oat_file.release();
1091 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001092 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001093 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001094}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001095
Andreas Gampe833a4852014-05-21 18:46:59 -07001096const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1097 int fd, const char* oat_location,
1098 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001099 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001100 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001101 std::string error_msg;
1102 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001103 CHECK(!error_msg.empty());
1104 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001105 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001106 }
Igor Murashkin46774762014-10-22 11:37:02 -07001107 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001108 !Runtime::Current()->IsAotCompiler(),
1109 &error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001110 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001111 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1112 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001113 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001114 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001115 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001116
1117 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001118}
1119
Alex Light6e183f22014-07-18 14:57:04 -07001120bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1121 const InstructionSet instruction_set) {
1122 Runtime* runtime = Runtime::Current();
1123 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001124 if (image_space == nullptr) {
1125 return false;
1126 }
Alex Light6e183f22014-07-18 14:57:04 -07001127 uint32_t image_oat_checksum = 0;
1128 if (instruction_set == kRuntimeISA) {
1129 const ImageHeader& image_header = image_space->GetImageHeader();
1130 image_oat_checksum = image_header.GetOatChecksum();
1131 } else {
1132 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1133 image_space->GetImageLocation().c_str(), instruction_set));
1134 image_oat_checksum = image_header->GetOatChecksum();
1135 }
1136 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1137}
1138
1139bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1140 const InstructionSet instruction_set,
1141 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001142 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001143 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001144 if (image_space == nullptr) {
1145 *error_msg = "No image space for verification against";
1146 return false;
1147 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001148
1149 // If the requested instruction set is the same as the current runtime,
1150 // we can use the checksums directly. If it isn't, we'll have to read the
1151 // image header from the image for the right instruction set.
1152 uint32_t image_oat_checksum = 0;
1153 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001154 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001155 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001156 const ImageHeader& image_header = image_space->GetImageHeader();
1157 image_oat_checksum = image_header.GetOatChecksum();
1158 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001159 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001160 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001161 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001162 image_space->GetImageLocation().c_str(), instruction_set));
1163 image_oat_checksum = image_header->GetOatChecksum();
1164 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001165 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001166 }
1167 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin96e83932014-10-29 19:45:42 -07001168 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1169
1170 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1171 if (!oat_file->IsPic()) {
1172 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1173 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1174 }
Alex Light6e183f22014-07-18 14:57:04 -07001175 if (!ret) {
1176 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1177 oat_file->GetLocation().c_str(),
1178 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1179 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1180 oat_file->GetOatHeader().GetImagePatchDelta(),
1181 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1182 }
1183 return ret;
1184}
1185
1186bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1187 const char* dex_location,
1188 uint32_t dex_location_checksum,
1189 const InstructionSet instruction_set,
1190 std::string* error_msg) {
1191 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1192 return false;
1193 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001194
Brian Carlstromf3632832014-05-20 15:36:53 -07001195 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1196 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001197 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001198 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1199 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001200 for (const OatFile::OatDexFile* oat_dex_file_in : oat_file->GetOatDexFiles()) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001201 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001202 oat_file->GetLocation().c_str(),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001203 oat_dex_file_in->GetDexFileLocation().c_str(),
1204 oat_dex_file_in->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001205 }
1206 return false;
1207 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001208
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001209 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001210 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001211}
1212
Alex Lighta59dd802014-07-02 16:28:08 -07001213bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1214 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001215 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001216 std::string* error_msg) {
1217 CHECK(oat_file != nullptr);
1218 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001219 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001220 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001221 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1222 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1223 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001224 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001225 if (oat_dex_file == nullptr) {
1226 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001227 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001228 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001229 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001230 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001231 dex_file = oat_dex_file->OpenDexFile(error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001232 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001233 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001234 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001235 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001236 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001237 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001238 dex_file = oat_file->GetOatDexFile(dex_location,
1239 dex_location_checksum)->OpenDexFile(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001240 }
Alex Lighta59dd802014-07-02 16:28:08 -07001241 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001242}
1243
Andreas Gampe833a4852014-05-21 18:46:59 -07001244const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001245 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001246 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001247 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001248 std::vector<std::string>* error_msgs,
1249 bool* obsolete_file_cleanup_failed) {
1250 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001251 bool already_opened = false;
1252 std::string dex_location_str(dex_location);
1253 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1254 &already_opened,
1255 obsolete_file_cleanup_failed,
1256 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001257 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001258 if (oat_file.get() == nullptr) {
1259 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1260 dex_location));
1261 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001262 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001263 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1264 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001265 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1266 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001267 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001268 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001269 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001270 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001271 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1272 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1273 "dex location '%s'. Image checksum incorrect.",
1274 oat_file->GetLocation().c_str(), dex_location));
1275 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001276 } else {
1277 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001278 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001279}
1280
Brian Carlstromae826982011-11-09 01:33:42 -08001281const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001282 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001283 for (size_t i = 0; i < oat_files_.size(); i++) {
1284 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001285 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001286 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001287 return oat_file;
1288 }
1289 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001290 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001291}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001292
Alex Lighta59dd802014-07-02 16:28:08 -07001293const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1294 InstructionSet isa,
1295 bool *already_opened,
1296 bool *obsolete_file_cleanup_failed,
1297 std::vector<std::string>* error_msgs) {
1298 // Find out if we've already opened the file
1299 const OatFile* ret = nullptr;
1300 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1301 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1302 if (ret != nullptr) {
1303 *already_opened = true;
1304 return ret;
1305 }
1306
1307 std::string dalvik_cache;
1308 bool have_android_data = false;
1309 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001310 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001311 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001312 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001313 std::string cache_filename;
1314 if (have_dalvik_cache) {
1315 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1316 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1317 if (ret != nullptr) {
1318 *already_opened = true;
1319 return ret;
1320 }
1321 } else {
1322 // If we need to relocate we should just place odex back where it started.
1323 cache_filename = odex_filename;
1324 }
1325
1326 ret = nullptr;
1327
1328 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1329 //
1330 // Now we do the following:
1331 // 1) Try and open the odex version
1332 // 2) If present, checksum-verified & relocated correctly return it
1333 // 3) Close the odex version to free up its address space.
1334 // 4) Try and open the cache version
1335 // 5) If present, checksum-verified & relocated correctly return it
1336 // 6) Close the cache version to free up its address space.
1337 // 7) If we should relocate:
1338 // a) If we have opened and checksum-verified the odex version relocate it to
1339 // 'cache_filename' and return it
1340 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1341 // it. This should not happen often (I think only the run-test's will hit this case).
1342 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1343 // this point.
1344 // 9) Return nullptr
1345
1346 *already_opened = false;
1347 const Runtime* runtime = Runtime::Current();
1348 CHECK(runtime != nullptr);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001349 bool executable = !runtime->IsAotCompiler();
Alex Lighta59dd802014-07-02 16:28:08 -07001350
1351 std::string odex_error_msg;
1352 bool should_patch_system = false;
1353 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001354 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001355 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001356 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001357 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001358 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001359 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001360 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001361 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001362 &odex_checksum_verified,
1363 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001364 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001365 } else {
1366 if (odex_checksum_verified) {
1367 // We can just relocate
1368 should_patch_system = true;
1369 odex_error_msg = "Image Patches are incorrect";
1370 }
1371 if (odex_oat_file.get() != nullptr) {
1372 have_system_odex = true;
1373 }
Alex Lighta59dd802014-07-02 16:28:08 -07001374 }
1375 }
1376
Alex Lighta59dd802014-07-02 16:28:08 -07001377 std::string cache_error_msg;
1378 bool should_patch_cache = false;
1379 bool cache_checksum_verified = false;
1380 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001381 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001382 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001383 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001384 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001385 &cache_checksum_verified,
1386 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001387 return cache_oat_file.release();
1388 } else if (cache_checksum_verified) {
1389 // We can just relocate
1390 should_patch_cache = true;
1391 cache_error_msg = "Image Patches are incorrect";
1392 }
1393 } else if (have_android_data) {
1394 // dalvik_cache does not exist but android data does. This means we should be able to create
1395 // it, so we should try.
1396 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1397 }
1398
1399 ret = nullptr;
1400 std::string error_msg;
1401 if (runtime->CanRelocate()) {
1402 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001403 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1404 if (space != nullptr) {
1405 const std::string& image_location = space->GetImageLocation();
1406 if (odex_checksum_verified && should_patch_system) {
1407 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1408 } else if (cache_checksum_verified && should_patch_cache) {
1409 CHECK(have_dalvik_cache);
1410 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1411 }
Alex Light84d76052014-08-22 17:49:35 -07001412 } else if (have_system_odex) {
1413 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001414 }
1415 }
1416 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1417 // implicitly: were able to fine where the cached version is but we were unable to use it,
1418 // either as a destination for relocation or to open a file. We should delete it if it is
1419 // there.
1420 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1421 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1422 "searching for dex file %s: %s",
1423 cache_filename.c_str(), dex_location.c_str(),
1424 strerror(errno));
1425 error_msgs->push_back(rm_error_msg);
1426 VLOG(class_linker) << rm_error_msg;
1427 // Let the caller know that we couldn't remove the obsolete file.
1428 // This is a good indication that further writes may fail as well.
1429 *obsolete_file_cleanup_failed = true;
1430 }
1431 }
1432 if (ret == nullptr) {
1433 VLOG(class_linker) << error_msg;
1434 error_msgs->push_back(error_msg);
1435 std::string relocation_msg;
1436 if (runtime->CanRelocate()) {
1437 relocation_msg = StringPrintf(" and relocation failed");
1438 }
1439 if (have_dalvik_cache && cache_checksum_verified) {
1440 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1441 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1442 cache_filename.c_str(), cache_error_msg.c_str(),
1443 relocation_msg.c_str());
1444 } else {
1445 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1446 "dalvik_cache availible)%s.", odex_filename.c_str(),
1447 odex_error_msg.c_str(), relocation_msg.c_str());
1448 }
1449 VLOG(class_linker) << error_msg;
1450 error_msgs->push_back(error_msg);
1451 }
1452 return ret;
1453}
1454
Alex Light9dcc4572014-08-14 14:16:26 -07001455const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1456 InstructionSet isa,
1457 std::string* error_msg) {
1458 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001459 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001460 if (output.get() == nullptr) {
1461 return nullptr;
1462 }
Alex Light84d76052014-08-22 17:49:35 -07001463 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1464 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001465 return output.release();
1466 } else {
1467 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1468 oat_path.c_str());
1469 return nullptr;
1470 }
1471}
1472
Alex Lighta59dd802014-07-02 16:28:08 -07001473const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1474 const std::string& output_oat,
1475 const std::string& image_location,
1476 InstructionSet isa,
1477 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001478 Runtime* runtime = Runtime::Current();
1479 DCHECK(runtime != nullptr);
1480 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001481 // We don't have an image space so there is no point in trying to patchoat.
1482 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1483 << "running without an image. Attempting to use oat file for interpretation.";
1484 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1485 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001486 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001487 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1488 // input_oat but make sure we only do interpretation on it's dex files.
1489 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1490 << "disabled. Attempting to use oat file for interpretation";
1491 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1492 }
Alex Lighta59dd802014-07-02 16:28:08 -07001493 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001494 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001495
1496 std::string isa_arg("--instruction-set=");
1497 isa_arg += GetInstructionSetString(isa);
1498 std::string input_oat_filename_arg("--input-oat-file=");
1499 input_oat_filename_arg += input_oat;
1500 std::string output_oat_filename_arg("--output-oat-file=");
1501 output_oat_filename_arg += output_oat;
1502 std::string patched_image_arg("--patched-image-location=");
1503 patched_image_arg += image_location;
1504
1505 std::vector<std::string> argv;
1506 argv.push_back(patchoat);
1507 argv.push_back(isa_arg);
1508 argv.push_back(input_oat_filename_arg);
1509 argv.push_back(output_oat_filename_arg);
1510 argv.push_back(patched_image_arg);
1511
1512 std::string command_line(Join(argv, ' '));
1513 LOG(INFO) << "Relocate Oat File: " << command_line;
1514 bool success = Exec(argv, error_msg);
1515 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001516 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001517 !runtime->IsAotCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001518 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001519 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1520 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001521 return output.release();
1522 } else if (output.get() != nullptr) {
1523 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1524 "but output file '%s' failed verifcation: %s",
1525 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1526 } else {
1527 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1528 "but was unable to open output file '%s': %s",
1529 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1530 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001531 } else if (!runtime->IsAotCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001532 // patchoat failed which means we probably don't have enough room to place the output oat file,
1533 // instead of failing we should just run the interpreter from the dex files in the input oat.
1534 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1535 << "for interpretation. patchoat failure was: " << *error_msg;
1536 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001537 } else {
1538 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1539 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1540 error_msg->c_str());
1541 }
1542 return nullptr;
1543}
1544
Andreas Gampe7ba64962014-10-23 11:37:40 -07001545bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001546 bool* checksum_verified,
1547 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001548 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001549 if (image_space == nullptr) {
1550 *error_msg = "No image space present";
1551 return false;
1552 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001553 uint32_t real_image_checksum;
1554 void* real_image_oat_offset;
1555 int32_t real_patch_delta;
1556 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001557 const ImageHeader& image_header = image_space->GetImageHeader();
1558 real_image_checksum = image_header.GetOatChecksum();
1559 real_image_oat_offset = image_header.GetOatDataBegin();
1560 real_patch_delta = image_header.GetPatchDelta();
1561 } else {
1562 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1563 image_space->GetImageLocation().c_str(), isa));
1564 real_image_checksum = image_header->GetOatChecksum();
1565 real_image_oat_offset = image_header->GetOatDataBegin();
1566 real_patch_delta = image_header->GetPatchDelta();
1567 }
1568
1569 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001570 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001571
1572 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1573 *checksum_verified = oat_image_checksum == real_image_checksum;
1574 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001575 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1576 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001577 }
1578
Andreas Gampe7ba64962014-10-23 11:37:40 -07001579 bool offset_verified;
1580 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001581
Andreas Gampe7ba64962014-10-23 11:37:40 -07001582 if (!oat_file->IsPic()) {
1583 // If an oat file is not PIC, we need to check that the image is at the expected location and
1584 // patched in the same way.
1585 void* oat_image_oat_offset =
1586 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1587 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1588 if (!offset_verified) {
1589 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1590 real_image_oat_offset, oat_image_oat_offset);
1591 }
1592
1593 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1594 patch_delta_verified = oat_patch_delta == real_patch_delta;
1595 if (!patch_delta_verified) {
1596 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1597 "received 0x%x)", real_patch_delta, oat_patch_delta);
1598 }
1599 } else {
1600 // If an oat file is PIC, we ignore offset and patching delta.
1601 offset_verified = true;
1602 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001603 }
1604
1605 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001606 if (!ret) {
1607 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001608 }
1609 return ret;
1610}
1611
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001612const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1613 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001614 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001615 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001616 return oat_file;
1617 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001618 return OatFile::Open(oat_location, oat_location, nullptr, nullptr,
1619 !Runtime::Current()->IsAotCompiler(), error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001620}
1621
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001622void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001623 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001624 DCHECK(obj != nullptr);
1625 DCHECK(class_linker != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001626 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001627 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001628 if (!method->IsNative()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001629 const size_t pointer_size = class_linker->image_pointer_size_;
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001630 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001631 if (!method->IsRuntimeMethod() && method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001632 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1633 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001634 }
1635 }
1636 }
1637}
1638
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001639void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001640 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001641 CHECK(!init_done_);
1642
Mathieu Chartier590fee92013-09-13 13:46:47 -07001643 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001644 gc::Heap* heap = Runtime::Current()->GetHeap();
1645 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001646 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001647 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001648 OatFile& oat_file = GetImageOatFile(space);
1649 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1650 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001651 const char* image_file_location = oat_file.GetOatHeader().
1652 GetStoreValueByKey(OatHeader::kImageLocationKey);
1653 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001654 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001655 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001656 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001657 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001658 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1659 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1660 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001661
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001662 StackHandleScope<1> hs(self);
1663 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1664 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1665 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001666 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001667
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001668 // Special case of setting up the String class early so that we can test arbitrary objects
1669 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001670 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001671
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001672 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001673 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001674 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001675 StackHandleScope<1> hs2(self);
1676 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001677 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001678 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1679 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001680 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001681 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001682 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
1683 if (dex_file.get() == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001684 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001685 << " from within oat file " << oat_file.GetLocation()
1686 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -08001687 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001688 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001689
1690 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1691
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001692 AppendToBootClassPath(*dex_file.get(), dex_cache);
1693 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001694 }
1695
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001696 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1697 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001698 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001699 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001700 if (!Runtime::Current()->IsAotCompiler()) {
1701 // Aot compiler supports having an image with a different pointer size than the runtime. This
Mathieu Chartier2d721012014-11-10 11:08:06 -08001702 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
1703 // also use 32 bit dex2oat on a system with 64 bit apps.
1704 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
1705 << sizeof(void*);
1706 }
1707 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
1708 image_pointer_size_ = 4;
1709 } else {
1710 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
1711 image_pointer_size_ = 8;
1712 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001713
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001714 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001715 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001716 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001717 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001718 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001719
1720 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001721 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001722 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001723
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001724 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001725 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001726 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001727 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001728 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001729 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001730 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1731 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1732 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1733 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1734 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1735 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1736 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1737 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1738 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1739 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001740
Ian Rogers98379392014-02-24 16:53:16 -08001741 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001742
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001743 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001744}
1745
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001746void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1747 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1748 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001749 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001750 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001751 }
1752 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001753 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001754 }
1755 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001756 for (auto& root : new_class_roots_) {
1757 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001758 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001759 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001760 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001761 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1762 // corresponding object. This is slow, but luckily for us, this may only happen with a
1763 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001764 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001765 DCHECK(it != class_table_.end());
1766 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001767 }
1768 }
1769 }
1770 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1771 new_class_roots_.clear();
1772 }
1773 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1774 log_new_class_table_roots_ = true;
1775 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1776 log_new_class_table_roots_ = false;
1777 }
1778 // We deliberately ignore the class roots in the image since we
1779 // handle image roots by using the MS/CMS rescanning of dirty cards.
1780}
1781
Brian Carlstroma663ea52011-08-19 23:33:41 -07001782// Keep in sync with InitCallback. Anything we visit, we need to
1783// reinit references to when reinitializing a ClassLinker from a
1784// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001785void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001786 class_roots_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers50b35e22012-10-04 10:09:15 -07001787 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001788 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001789 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001790 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001791 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001792 dex_cache.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001793 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001794 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1795 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001796 dex_caches_[index].VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001797 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001798 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001799 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1800 new_dex_cache_roots_.clear();
1801 }
1802 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1803 log_new_dex_caches_roots_ = true;
1804 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1805 log_new_dex_caches_roots_ = false;
1806 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001807 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001808 VisitClassRoots(callback, arg, flags);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001809 array_iftable_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001810 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001811 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001812 find_array_class_cache_[i].VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001813 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001814}
1815
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001816void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1817 if (dex_cache_image_class_lookup_required_) {
1818 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001819 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001820 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001821 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001822 for (GcRoot<mirror::Class>& root : class_table_) {
1823 if (!visitor(root.Read(), arg)) {
1824 return;
1825 }
1826 }
1827 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1828 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001829 return;
1830 }
1831 }
1832}
1833
Ian Rogersdbf3be02014-08-29 15:40:08 -07001834static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001835 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001836 classes->insert(c);
1837 return true;
1838}
1839
Ian Rogersdbf3be02014-08-29 15:40:08 -07001840struct GetClassesVisitorArrayArg {
1841 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1842 int32_t index;
1843 bool success;
1844};
1845
1846static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1847 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1848 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1849 if (arg->index < (*arg->classes)->GetLength()) {
1850 (*arg->classes)->Set(arg->index, c);
1851 arg->index++;
1852 return true;
1853 } else {
1854 arg->success = false;
1855 return false;
1856 }
1857}
1858
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001859void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001860 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1861 // is avoiding duplicates.
1862 if (!kMovingClasses) {
1863 std::set<mirror::Class*> classes;
1864 VisitClasses(GetClassesVisitorSet, &classes);
1865 for (mirror::Class* klass : classes) {
1866 if (!visitor(klass, arg)) {
1867 return;
1868 }
1869 }
1870 } else {
1871 Thread* self = Thread::Current();
1872 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001873 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001874 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1875 GetClassesVisitorArrayArg local_arg;
1876 local_arg.classes = &classes;
1877 local_arg.success = false;
1878 // We size the array assuming classes won't be added to the class table during the visit.
1879 // If this assumption fails we iterate again.
1880 while (!local_arg.success) {
1881 size_t class_table_size;
1882 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001883 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001884 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001885 }
1886 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1887 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1888 classes.Assign(
1889 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1890 CHECK(classes.Get() != nullptr); // OOME.
1891 local_arg.index = 0;
1892 local_arg.success = true;
1893 VisitClasses(GetClassesVisitorArray, &local_arg);
1894 }
1895 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1896 // If the class table shrank during creation of the clases array we expect null elements. If
1897 // the class table grew then the loop repeats. If classes are created after the loop has
1898 // finished then we don't visit.
1899 mirror::Class* klass = classes->Get(i);
1900 if (klass != nullptr && !visitor(klass, arg)) {
1901 return;
1902 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001903 }
1904 }
1905}
1906
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001907ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001908 mirror::Class::ResetClass();
1909 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001910 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001911 mirror::ArtField::ResetClass();
1912 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001913 mirror::BooleanArray::ResetArrayClass();
1914 mirror::ByteArray::ResetArrayClass();
1915 mirror::CharArray::ResetArrayClass();
1916 mirror::DoubleArray::ResetArrayClass();
1917 mirror::FloatArray::ResetArrayClass();
1918 mirror::IntArray::ResetArrayClass();
1919 mirror::LongArray::ResetArrayClass();
1920 mirror::ShortArray::ResetArrayClass();
1921 mirror::Throwable::ResetClass();
1922 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001923 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001924}
1925
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001926mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001927 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001928 StackHandleScope<16> hs(self);
1929 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1930 Handle<mirror::DexCache> dex_cache(
1931 hs.NewHandle(down_cast<mirror::DexCache*>(
1932 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1933 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001934 if (dex_cache.Get() == nullptr) {
1935 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001936 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001937 Handle<mirror::String>
1938 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001939 if (location.Get() == nullptr) {
1940 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001941 }
Ian Rogers700a4022014-05-19 16:49:03 -07001942 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001943 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001944 if (strings.Get() == nullptr) {
1945 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001946 }
Ian Rogers700a4022014-05-19 16:49:03 -07001947 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001948 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001949 if (types.Get() == nullptr) {
1950 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001951 }
Ian Rogers700a4022014-05-19 16:49:03 -07001952 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001953 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001954 if (methods.Get() == nullptr) {
1955 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001956 }
Ian Rogers700a4022014-05-19 16:49:03 -07001957 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001958 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001959 if (fields.Get() == nullptr) {
1960 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001961 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001962 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1963 fields.Get());
1964 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001965}
1966
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001967mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001968 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001969 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001970 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001971 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001972 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001973 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1974 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001975 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001976 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001977 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001978 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001979 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001980}
1981
Ian Rogers6fac4472014-02-25 17:01:10 -08001982mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001983 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001984}
1985
Brian Carlstromea46f952013-07-30 01:26:50 -07001986mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001987 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001988 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001989}
1990
Brian Carlstromea46f952013-07-30 01:26:50 -07001991mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001992 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001993 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001994}
1995
Mathieu Chartier590fee92013-09-13 13:46:47 -07001996mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1997 Thread* self, size_t length) {
1998 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1999 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002000}
2001
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002002mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
2003 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002004 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002005
2006 // For temporary classes we must wait for them to be retired.
2007 if (init_done_ && klass->IsTemp()) {
2008 CHECK(!klass->IsResolved());
2009 if (klass->IsErroneous()) {
2010 ThrowEarlierClassFailure(klass);
2011 return nullptr;
2012 }
2013 StackHandleScope<1> hs(self);
2014 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2015 ObjectLock<mirror::Class> lock(self, h_class);
2016 // Loop and wait for the resolving thread to retire this class.
2017 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2018 lock.WaitIgnoringInterrupts();
2019 }
2020 if (h_class->IsErroneous()) {
2021 ThrowEarlierClassFailure(h_class.Get());
2022 return nullptr;
2023 }
2024 CHECK(h_class->IsRetired());
2025 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002026 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2027 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002028 }
2029
Brian Carlstromaded5f72011-10-07 17:15:04 -07002030 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002031 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002032 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002033 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2034 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002035 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002036 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2037 ThrowClassCircularityError(h_class.Get());
2038 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002039 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002040 }
2041 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002042 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002043 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002044 }
2045 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002046
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002047 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002048 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002049 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002050 }
2051 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002052 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002053 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002054 return klass;
2055}
2056
Ian Rogers68b56852014-08-29 20:19:11 -07002057typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2058
2059// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002060ClassPathEntry FindInClassPath(const char* descriptor,
2061 size_t hash, const std::vector<const DexFile*>& class_path) {
2062 for (const DexFile* dex_file : class_path) {
2063 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002064 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002065 return ClassPathEntry(dex_file, dex_class_def);
2066 }
2067 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002068 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002069}
2070
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002071mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2072 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002073 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002074 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08002075 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002076 if (class_loader->GetClass() !=
2077 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2078 class_loader->GetParent()->GetClass() !=
2079 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2080 return nullptr;
2081 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002082 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002083 // Check if this would be found in the parent boot class loader.
2084 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002085 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002086 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08002087 // May return null if resolution on another thread fails.
2088 klass = EnsureResolved(self, descriptor, klass);
2089 } else {
2090 // May OOME.
2091 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2092 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002093 }
Ian Rogers32427292014-11-19 14:05:21 -08002094 if (klass == nullptr) {
2095 CHECK(self->IsExceptionPending()) << descriptor;
2096 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002097 }
Ian Rogers32427292014-11-19 14:05:21 -08002098 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002099 } else {
Ian Rogers32427292014-11-19 14:05:21 -08002100 // Handle as if this is the child PathClassLoader.
2101 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002102 StackHandleScope<3> hs(self);
2103 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2104 // We need to get the DexPathList and loop through it.
2105 Handle<mirror::ArtField> cookie_field =
2106 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2107 Handle<mirror::ArtField> dex_file_field =
2108 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002109 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002110 mirror::Object* dex_path_list =
2111 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2112 GetObject(class_loader.Get());
2113 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2114 cookie_field.Get() != nullptr) {
2115 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2116 mirror::Object* dex_elements_obj =
2117 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2118 GetObject(dex_path_list);
2119 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2120 // at the mCookie which is a DexFile vector.
2121 if (dex_elements_obj != nullptr) {
2122 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2123 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2124 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2125 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2126 if (element == nullptr) {
2127 // Should never happen, fall back to java code to throw a NPE.
2128 break;
2129 }
2130 mirror::Object* dex_file = dex_file_field->GetObject(element);
2131 if (dex_file != nullptr) {
Andreas Gampe324b9bb2015-02-23 16:33:22 -08002132 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
2133 if (long_array == nullptr) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002134 // This should never happen so log a warning.
2135 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2136 break;
2137 }
Andreas Gampe324b9bb2015-02-23 16:33:22 -08002138 int32_t long_array_size = long_array->GetLength();
2139 for (int32_t j = 0; j < long_array_size; ++j) {
2140 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
2141 long_array->GetWithoutChecks(j)));
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002142 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002143 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002144 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002145 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2146 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002147 if (klass == nullptr) {
2148 CHECK(self->IsExceptionPending()) << descriptor;
2149 self->ClearException();
2150 return nullptr;
2151 }
2152 return klass;
2153 }
2154 }
2155 }
2156 }
2157 }
2158 }
Ian Rogers32427292014-11-19 14:05:21 -08002159 self->AssertNoPendingException();
2160 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002161 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002162}
2163
Ian Rogers98379392014-02-24 16:53:16 -08002164mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002165 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002166 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002167 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002168 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002169 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002170 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2171 // for primitive classes that aren't backed by dex files.
2172 return FindPrimitiveClass(descriptor[0]);
2173 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002174 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002175 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002176 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002177 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002178 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002179 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002180 // Class is not yet loaded.
2181 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002182 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002183 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002184 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002185 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002186 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002187 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002188 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002189 } else {
2190 // The boot class loader is searched ahead of the application class loader, failures are
2191 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2192 // trigger the chaining with a proper stack trace.
2193 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002194 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002195 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002196 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002197 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002198 // First try with the bootstrap class loader.
2199 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002200 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002201 if (klass != nullptr) {
2202 return EnsureResolved(self, descriptor, klass);
2203 }
2204 }
Ian Rogers63557452014-06-04 16:57:15 -07002205 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2206 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002207 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002208 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002209 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002210 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002211 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002212 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002213 const std::vector<const DexFile*>* class_path;
2214 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002215 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002216 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002217 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002218 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2219 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002220 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07002221 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002222 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07002223 } else {
2224 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2225 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002226 self->SetException(pre_allocated);
Ian Rogers7b078e82014-09-10 14:44:24 -07002227 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002228 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002229 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002230 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002231 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2232 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002233 if (cp_klass != nullptr) {
2234 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002235 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002236 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002237 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002238 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002239 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002240 {
2241 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002242 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2243 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002244 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002245 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002246 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002247 }
Ian Rogers68b56852014-08-29 20:19:11 -07002248 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002249 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2250 WellKnownClasses::java_lang_ClassLoader_loadClass,
2251 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002252 }
Ian Rogers98379392014-02-24 16:53:16 -08002253 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002254 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002255 return nullptr;
2256 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002257 // broken loader - throw NPE to be compatible with Dalvik
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00002258 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2259 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002260 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002261 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002262 // success, return mirror::Class*
2263 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002264 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002265 }
Ian Rogers07140832014-09-30 15:43:59 -07002266 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002267}
2268
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002269mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002270 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002271 const DexFile& dex_file,
2272 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002273 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002274 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002275
Brian Carlstromaded5f72011-10-07 17:15:04 -07002276 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002277 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002278 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002279 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002280 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002281 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002282 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002283 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002284 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002285 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2286 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002287 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002288 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002289 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002290 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002291 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002292 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002293 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002294 }
2295
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002296 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002297 // Allocate a class with the status of not ready.
2298 // Interface object should get the right size here. Regular class will
2299 // figure out the right size later and be replaced with one of the right
2300 // size when the class becomes resolved.
2301 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002302 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002303 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002304 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002305 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002306 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002307 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002308 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002309 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002310 if (self->IsExceptionPending()) {
2311 // An exception occured during load, set status to erroneous while holding klass' lock in case
2312 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002313 if (!klass->IsErroneous()) {
2314 klass->SetStatus(mirror::Class::kStatusError, self);
2315 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002316 return nullptr;
2317 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002318 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002319
Mathieu Chartier590fee92013-09-13 13:46:47 -07002320 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002321 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002322 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002323 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2324 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002325 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002326 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002327
Brian Carlstromaded5f72011-10-07 17:15:04 -07002328 // Finish loading (if necessary) by finding parents
2329 CHECK(!klass->IsLoaded());
2330 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2331 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002332 if (!klass->IsErroneous()) {
2333 klass->SetStatus(mirror::Class::kStatusError, self);
2334 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002335 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002336 }
2337 CHECK(klass->IsLoaded());
2338 // Link the class (if necessary)
2339 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002340 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002341 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002342
2343 mirror::Class* new_class = nullptr;
2344 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002345 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002346 if (!klass->IsErroneous()) {
2347 klass->SetStatus(mirror::Class::kStatusError, self);
2348 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002349 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002350 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002351 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002352 CHECK(new_class != nullptr) << descriptor;
2353 CHECK(new_class->IsResolved()) << descriptor;
2354
2355 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002356
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002357 // Instrumentation may have updated entrypoints for all methods of all
2358 // classes. However it could not update methods of this class while we
2359 // were loading it. Now the class is resolved, we can update entrypoints
2360 // as required by instrumentation.
2361 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2362 // We must be in the kRunnable state to prevent instrumentation from
2363 // suspending all threads to update entrypoints while we are doing it
2364 // for this class.
2365 DCHECK_EQ(self->GetState(), kRunnable);
2366 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(new_class_h.Get());
2367 }
2368
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002369 /*
2370 * We send CLASS_PREPARE events to the debugger from here. The
2371 * definition of "preparation" is creating the static fields for a
2372 * class and initializing them to the standard default values, but not
2373 * executing any code (that comes later, during "initialization").
2374 *
2375 * We did the static preparation in LinkClass.
2376 *
2377 * The class has been prepared and resolved but possibly not yet verified
2378 * at this point.
2379 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002380 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002381
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002382 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002383}
2384
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002385uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2386 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002387 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002388 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002389 size_t num_8 = 0;
2390 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002391 size_t num_32 = 0;
2392 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002393 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002394 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2395 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002396 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002397 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002398 switch (c) {
2399 case 'L':
2400 case '[':
2401 num_ref++;
2402 break;
2403 case 'J':
2404 case 'D':
2405 num_64++;
2406 break;
2407 case 'I':
2408 case 'F':
2409 num_32++;
2410 break;
2411 case 'S':
2412 case 'C':
2413 num_16++;
2414 break;
2415 case 'B':
2416 case 'Z':
2417 num_8++;
2418 break;
2419 default:
2420 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002421 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002422 }
2423 }
2424 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002425 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002426}
2427
Ian Rogers97b52f82014-08-14 11:34:07 -07002428OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2429 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002430 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002431 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2432 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002433 *found = false;
2434 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002435 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002436 *found = true;
2437 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002438}
2439
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002440static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2441 uint32_t method_idx) {
2442 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002443 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002444 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002445 ClassDataItemIterator it(dex_file, class_data);
2446 // Skip fields
2447 while (it.HasNextStaticField()) {
2448 it.Next();
2449 }
2450 while (it.HasNextInstanceField()) {
2451 it.Next();
2452 }
2453 // Process methods
2454 size_t class_def_method_index = 0;
2455 while (it.HasNextDirectMethod()) {
2456 if (it.GetMemberIndex() == method_idx) {
2457 return class_def_method_index;
2458 }
2459 class_def_method_index++;
2460 it.Next();
2461 }
2462 while (it.HasNextVirtualMethod()) {
2463 if (it.GetMemberIndex() == method_idx) {
2464 return class_def_method_index;
2465 }
2466 class_def_method_index++;
2467 it.Next();
2468 }
2469 DCHECK(!it.HasNext());
2470 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08002471 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002472}
2473
Ian Rogers97b52f82014-08-14 11:34:07 -07002474const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002475 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002476 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002477 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002478 size_t oat_method_index;
2479 if (method->IsStatic() || method->IsDirect()) {
2480 // Simple case where the oat method index was stashed at load time.
2481 oat_method_index = method->GetMethodIndex();
2482 } else {
2483 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2484 // by search for its position in the declared virtual methods.
2485 oat_method_index = declaring_class->NumDirectMethods();
2486 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002487 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002488 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002489 // Check method index instead of identity in case of duplicate method definitions.
2490 if (method->GetDexMethodIndex() ==
2491 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002492 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002493 break;
2494 }
Ian Rogersf320b632012-03-13 18:47:47 -07002495 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002496 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002497 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2498 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002499 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002500 DCHECK_EQ(oat_method_index,
2501 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002502 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002503 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002504 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2505 declaring_class->GetDexClassDefIndex(),
2506 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002507 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002508 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002509 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002510 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002511}
2512
2513// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002514const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002515 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002516 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002517 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002518 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002519 bool found;
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08002520 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2521 if (found) {
2522 auto* code = oat_method.GetQuickCode();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002523 if (code != nullptr) {
2524 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08002525 }
2526 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08002527 jit::Jit* const jit = Runtime::Current()->GetJit();
2528 if (jit != nullptr) {
2529 auto* code = jit->GetCodeCache()->GetCodeFor(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002530 if (code != nullptr) {
2531 return code;
2532 }
2533 }
2534 if (method->IsNative()) {
2535 // No code and native? Use generic trampoline.
2536 return GetQuickGenericJniStub();
2537 }
2538 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07002539}
2540
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002541const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2542 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2543 return nullptr;
2544 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08002545 bool found;
2546 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2547 if (found) {
2548 return oat_method.GetQuickCode();
2549 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002550 jit::Jit* jit = Runtime::Current()->GetJit();
2551 if (jit != nullptr) {
2552 auto* code = jit->GetCodeCache()->GetCodeFor(method);
2553 if (code != nullptr) {
2554 return code;
2555 }
2556 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002557 return nullptr;
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002558}
2559
Ian Rogersef7d42f2014-01-06 12:55:46 -08002560const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2561 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002562 bool found;
2563 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2564 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002565 return nullptr;
2566 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002567 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002568 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002569}
2570
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002571// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08002572static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07002573 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08002574 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002575 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002576 // May return true for native code, in the case of generic JNI
2577 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002578 return true;
2579 }
2580 // If interpreter mode is enabled, every method (except native and proxy) must
2581 // be run with interpreter.
2582 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2583 !method->IsNative() && !method->IsProxyMethod();
2584}
2585
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002586void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002587 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002588 if (klass->NumDirectMethods() == 0) {
2589 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002590 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002591 Runtime* runtime = Runtime::Current();
2592 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002593 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002594 return; // OAT file unavailable.
2595 }
Ian Rogers19846512012-02-24 11:42:47 -08002596 }
Alex Light64ad14d2014-08-19 14:23:13 -07002597
Mathieu Chartierf8322842014-05-16 10:59:25 -07002598 const DexFile& dex_file = klass->GetDexFile();
2599 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002600 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002601 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002602 // There should always be class data if there were direct methods.
2603 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002604 ClassDataItemIterator it(dex_file, class_data);
2605 // Skip fields
2606 while (it.HasNextStaticField()) {
2607 it.Next();
2608 }
2609 while (it.HasNextInstanceField()) {
2610 it.Next();
2611 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002612 bool has_oat_class;
2613 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2614 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002615 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002616 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002617 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002618 if (!method->IsStatic()) {
2619 // Only update static methods.
2620 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002621 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002622 const void* quick_code = nullptr;
2623 if (has_oat_class) {
2624 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002625 quick_code = oat_method.GetQuickCode();
2626 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002627 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002628 if (enter_interpreter) {
2629 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002630 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08002631 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002632 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08002633 } else {
2634 quick_code = GetQuickToInterpreterBridge();
2635 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002636 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002637 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08002638 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002639 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002640}
2641
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002642void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002643 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002644 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002645 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002646 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002647 // The following code only applies to a non-compiler runtime.
2648 return;
2649 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002650 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002651 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002652 if (oat_class != nullptr) {
2653 // Every kind of method should at least get an invoke stub from the oat_method.
2654 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002655 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002656 oat_method.LinkMethod(method.Get());
2657 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002658
Jeff Hao16743632013-05-08 10:59:04 -07002659 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002660 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08002661 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002662 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002663 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002664 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002665 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002666 }
2667
Brian Carlstrom92827a52011-10-10 15:50:01 -07002668 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002669 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002670 return;
2671 }
Ian Rogers19846512012-02-24 11:42:47 -08002672
2673 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002674 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002675 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2676 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002677 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002678 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002679 if (!method->IsNative()) {
2680 // Set entry point from compiled code if there's no code or in interpreter only mode.
2681 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002682 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002683 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002684 }
Ian Rogers0d6de042012-02-29 08:50:26 -08002685 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002686
Ian Rogers62d6c772013-02-27 08:32:07 -08002687 if (method->IsNative()) {
2688 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002689 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002690
2691 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002692 // We have a native method here without code. Then it should have either the generic JNI
2693 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2694 // TODO: this doesn't handle all the cases where trampolines may be installed.
2695 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2696 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002697 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002698 }
2699}
2700
Fred Shih37f05ef2014-07-16 18:38:08 -07002701
Fred Shih37f05ef2014-07-16 18:38:08 -07002702
Ian Rogers7b078e82014-09-10 14:44:24 -07002703void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002704 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002705 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002706 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002707 CHECK(klass.Get() != nullptr);
2708 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002709 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002710 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002711 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002712
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002713 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07002714 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002715 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002716 klass->SetAccessFlags(access_flags);
2717 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002718 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002719 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002720
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002721 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002722 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002723 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002724
Ian Rogers13735952014-10-08 12:43:28 -07002725 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002726 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002727 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002728 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002729
Ian Rogers97b52f82014-08-14 11:34:07 -07002730
2731 bool has_oat_class = false;
2732 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2733 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2734 &has_oat_class);
2735 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002736 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002737 }
2738 }
2739 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002740 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002741 }
2742}
2743
Ian Rogers7b078e82014-09-10 14:44:24 -07002744void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002745 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002746 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002747 const OatFile::OatClass* oat_class) {
2748 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002749 ClassDataItemIterator it(dex_file, class_data);
2750 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002751 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002752 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002753 CHECK(self->IsExceptionPending()); // OOME.
2754 return;
2755 }
2756 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002757 }
2758 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002759 mirror::ObjectArray<mirror::ArtField>* fields =
2760 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002761 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002762 CHECK(self->IsExceptionPending()); // OOME.
2763 return;
2764 }
2765 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002766 }
2767 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002768 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002769 StackHandleScope<1> hs(self);
2770 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002771 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002772 CHECK(self->IsExceptionPending()); // OOME.
2773 return;
2774 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002775 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002776 LoadField(dex_file, it, klass, sfield);
2777 }
2778 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002779 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002780 StackHandleScope<1> hs(self);
2781 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002782 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002783 CHECK(self->IsExceptionPending()); // OOME.
2784 return;
2785 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002786 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002787 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002788 }
2789
Ian Rogers0571d352011-11-03 19:51:38 -07002790 // Load methods.
2791 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002792 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002793 mirror::ObjectArray<mirror::ArtMethod>* directs =
2794 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002795 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002796 CHECK(self->IsExceptionPending()); // OOME.
2797 return;
2798 }
2799 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002800 }
Ian Rogers0571d352011-11-03 19:51:38 -07002801 if (it.NumVirtualMethods() != 0) {
2802 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002803 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2804 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002805 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002806 CHECK(self->IsExceptionPending()); // OOME.
2807 return;
2808 }
2809 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002810 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002811 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002812 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2813 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002814 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002815 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002816 StackHandleScope<1> hs(self);
2817 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002818 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002819 CHECK(self->IsExceptionPending()); // OOME.
2820 return;
2821 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002822 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002823 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002824 uint32_t it_method_index = it.GetMemberIndex();
2825 if (last_dex_method_index == it_method_index) {
2826 // duplicate case
2827 method->SetMethodIndex(last_class_def_method_index);
2828 } else {
2829 method->SetMethodIndex(class_def_method_index);
2830 last_dex_method_index = it_method_index;
2831 last_class_def_method_index = class_def_method_index;
2832 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002833 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002834 }
2835 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002836 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002837 StackHandleScope<1> hs(self);
2838 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002839 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002840 CHECK(self->IsExceptionPending()); // OOME.
2841 return;
2842 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002843 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002844 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002845 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002846 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002847 }
2848 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002849}
2850
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002851void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002852 Handle<mirror::Class> klass,
2853 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002854 uint32_t field_idx = it.GetMemberIndex();
2855 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002856 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002857 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002858}
2859
Brian Carlstromea46f952013-07-30 01:26:50 -07002860mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002861 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002862 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002863 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002864 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002865 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002866
Brian Carlstromea46f952013-07-30 01:26:50 -07002867 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002868 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002869 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002870 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002871 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002872 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002873
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002874 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002875 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002876 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002877 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002878
Ian Rogers19846512012-02-24 11:42:47 -08002879 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002880 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002881
Andreas Gampe51829322014-08-25 15:05:04 -07002882 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002883
Ian Rogersdfb325e2013-10-30 01:00:44 -07002884 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002885 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002886 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2887 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002888 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002889 klass->SetFinalizable();
2890 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002891 std::string temp;
2892 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002893 // The Enum class declares a "final" finalize() method to prevent subclasses from
2894 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2895 // subclasses, so we exclude it here.
2896 // We also want to avoid setting the flag on Object, where we know that finalize() is
2897 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002898 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2899 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002900 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002901 }
2902 }
2903 }
2904 } else if (method_name[0] == '<') {
2905 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002906 bool is_init = (strcmp("<init>", method_name) == 0);
2907 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002908 if (UNLIKELY(!is_init && !is_clinit)) {
2909 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2910 } else {
2911 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2912 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002913 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002914 access_flags |= kAccConstructor;
2915 }
2916 }
2917 }
2918 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002919
Mathieu Chartier66f19252012-09-18 08:57:04 -07002920 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002921}
2922
Ian Rogers7b078e82014-09-10 14:44:24 -07002923void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002924 StackHandleScope<1> hs(self);
2925 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002926 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2927 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002928 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002929}
2930
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002931void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002932 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002933 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002934 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002935 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002936}
2937
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002938bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002939 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002940 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002941 mirror::DexCache* dex_cache = GetDexCache(i);
2942 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002943 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002944 }
2945 }
2946 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002947}
2948
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002949bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002950 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002951 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002952}
2953
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002954void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002955 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002956 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002957 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002958 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2959 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002960 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002961 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002962 if (log_new_dex_caches_roots_) {
2963 // TODO: This is not safe if we can remove dex caches.
2964 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2965 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002966}
2967
Brian Carlstromaded5f72011-10-07 17:15:04 -07002968void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002969 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002970 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002971 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002972 if (IsDexFileRegisteredLocked(dex_file)) {
2973 return;
2974 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002975 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002976 // Don't alloc while holding the lock, since allocation may need to
2977 // suspend all threads and another thread may need the dex_lock_ to
2978 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002979 StackHandleScope<1> hs(self);
2980 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002981 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2982 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002983 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002984 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002985 if (IsDexFileRegisteredLocked(dex_file)) {
2986 return;
2987 }
2988 RegisterDexFileLocked(dex_file, dex_cache);
2989 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002990}
2991
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002992void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002993 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002994 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002995 RegisterDexFileLocked(dex_file, dex_cache);
2996}
2997
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002998mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002999 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003000 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003001 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003002 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003003 if (dex_cache->GetDexFile() == &dex_file) {
3004 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003005 }
3006 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003007 // Search matching by location name.
3008 std::string location(dex_file.GetLocation());
3009 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003010 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003011 if (dex_cache->GetDexFile()->GetLocation() == location) {
3012 return dex_cache;
3013 }
3014 }
3015 // Failure, dump diagnostic and abort.
3016 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003017 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003018 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3019 }
3020 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003021 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003022}
3023
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003024void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003025 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003026 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003027 mirror::DexCache* dex_cache = GetDexCache(i);
3028 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003029 }
3030}
3031
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003032mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003033 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003034 if (UNLIKELY(klass == nullptr)) {
3035 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003036 }
3037 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003038}
3039
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003040mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3041 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003042 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003043 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003044 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003045 StackHandleScope<1> hs(self);
3046 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003047 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003048 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003049 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003050 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3051 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003052 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3053 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003054 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003055 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003056}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003057
Brian Carlstrombe977852011-07-19 14:54:54 -07003058// Create an array class (i.e. the class object for the array, not the
3059// array itself). "descriptor" looks like "[C" or "[[[[B" or
3060// "[Ljava/lang/String;".
3061//
3062// If "descriptor" refers to an array of primitives, look up the
3063// primitive type's internally-generated class object.
3064//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003065// "class_loader" is the class loader of the class that's referring to
3066// us. It's used to ensure that we're looking for the element type in
3067// the right context. It does NOT become the class loader for the
3068// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003069//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003070// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003071mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003072 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003073 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003074 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003075 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003076 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3077 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003078 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003079 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003080 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003081 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3082 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003083 if (component_type.Get() == nullptr) {
3084 DCHECK(self->IsExceptionPending());
3085 return nullptr;
3086 } else {
3087 self->ClearException();
3088 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003089 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003090 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3091 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3092 return nullptr;
3093 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003094 // See if the component type is already loaded. Array classes are
3095 // always associated with the class loader of their underlying
3096 // element type -- an array of Strings goes with the loader for
3097 // java/lang/String -- so we need to look for it there. (The
3098 // caller should have checked for the existence of the class
3099 // before calling here, but they did so with *their* class loader,
3100 // not the component type's loader.)
3101 //
3102 // If we find it, the caller adds "loader" to the class' initiating
3103 // loader list, which should prevent us from going through this again.
3104 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003105 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003106 // are the same, because our caller (FindClass) just did the
3107 // lookup. (Even if we get this wrong we still have correct behavior,
3108 // because we effectively do this lookup again when we add the new
3109 // class to the hash table --- necessary because of possible races with
3110 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003111 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003112 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003113 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003114 return new_class;
3115 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003116 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003117
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003118 // Fill out the fields in the Class.
3119 //
3120 // It is possible to execute some methods against arrays, because
3121 // all arrays are subclasses of java_lang_Object_, so we need to set
3122 // up a vtable. We can just point at the one in java_lang_Object_.
3123 //
3124 // Array classes are simple enough that we don't need to do a full
3125 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003126 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003127 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003128 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003129 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003130 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003131 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003132 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003133 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003134 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003135 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003136 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003137 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003138 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003139 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003140 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003141 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003142 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003143 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003144 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003145 }
3146 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003147 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003148 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003149 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003150 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003151 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003152 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003153 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003154 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003155 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003156 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003157 new_class->SetSuperClass(java_lang_Object);
3158 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003159 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003160 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003161 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003162 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003163 StackHandleScope<mirror::Class::kImtSize> hs2(self,
3164 Runtime::Current()->GetImtUnimplementedMethod());
3165 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003166 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003167 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003168 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003169 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003170
3171
3172 // All arrays have java/lang/Cloneable and java/io/Serializable as
3173 // interfaces. We need to set that up here, so that stuff like
3174 // "instanceof" works right.
3175 //
3176 // Note: The GC could run during the call to FindSystemClass,
3177 // so we need to make sure the class object is GC-valid while we're in
3178 // there. Do this by clearing the interface list so the GC will just
3179 // think that the entries are null.
3180
3181
3182 // Use the single, global copies of "interfaces" and "iftable"
3183 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003184 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003185 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003186 CHECK(array_iftable != nullptr);
3187 new_class->SetIfTable(array_iftable);
3188 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003189
Elliott Hughes00626c22013-06-14 15:04:14 -07003190 // Inherit access flags from the component type.
3191 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3192 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3193 access_flags &= kAccJavaFlagsMask;
3194 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003195 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003196 access_flags |= kAccAbstract | kAccFinal;
3197 access_flags &= ~kAccInterface;
3198
3199 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003200
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003201 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003202 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003203 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003204 }
3205 // Another thread must have loaded the class after we
3206 // started but before we finished. Abandon what we've
3207 // done.
3208 //
3209 // (Yes, this happens.)
3210
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003211 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003212}
3213
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003214mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003215 switch (type) {
3216 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003217 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003218 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003219 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003220 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003221 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003222 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003223 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003224 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003225 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003226 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003227 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003228 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003229 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003230 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003231 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003232 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003233 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003234 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003235 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003236 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003237 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003238 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003239 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003240}
3241
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003242mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3243 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003244 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003245 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003246 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003247 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003248 source += " from ";
3249 source += dex_cache->GetLocation()->ToModifiedUtf8();
3250 }
3251 LOG(INFO) << "Loaded class " << descriptor << source;
3252 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003253 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003254 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003255 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003256 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003257 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003258 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003259 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003260 // Check a class loaded with the system class loader matches one in the image if the class
3261 // is in the image.
3262 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003263 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003264 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003265 }
3266 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003267 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003268 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003269 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003270 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003271 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003272 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003273}
3274
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003275mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3276 size_t hash) {
3277 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003278 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3279 hash);
3280 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003281 CHECK(klass->IsProxyClass());
3282 return nullptr;
3283 }
3284
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003285 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003286 CHECK_NE(existing, klass) << descriptor;
3287 CHECK(!existing->IsResolved()) << descriptor;
3288 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3289
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003290 CHECK(!klass->IsTemp()) << descriptor;
3291 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3292 dex_cache_image_class_lookup_required_) {
3293 // Check a class loaded with the system class loader matches one in the image if the class
3294 // is in the image.
3295 existing = LookupClassFromImage(descriptor);
3296 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003297 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003298 }
3299 }
3300 VerifyObject(klass);
3301
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003302 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003303 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003304 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003305 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003306 }
3307
3308 return existing;
3309}
3310
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003311bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003312 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003313 auto pair = std::make_pair(descriptor, class_loader);
3314 auto it = class_table_.Find(pair);
3315 if (it != class_table_.end()) {
3316 class_table_.Erase(it);
3317 return true;
3318 }
3319 it = pre_zygote_class_table_.Find(pair);
3320 if (it != pre_zygote_class_table_.end()) {
3321 pre_zygote_class_table_.Erase(it);
3322 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003323 }
3324 return false;
3325}
3326
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003327mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003328 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003329 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003330 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003331 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003332 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003333 return result;
3334 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003335 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003336 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3337 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003338 } else {
3339 // Lookup failed but need to search dex_caches_.
3340 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003341 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003342 InsertClass(descriptor, result, hash);
3343 } else {
3344 // Searching the image dex files/caches failed, we don't want to get into this situation
3345 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3346 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003347 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003348 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3349 MoveImageClassesToClassTable();
3350 }
3351 }
3352 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003353 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003354}
3355
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003356mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003357 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003358 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003359 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3360 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3361 if (it == pre_zygote_class_table_.end()) {
3362 it = class_table_.FindWithHash(descriptor_pair, hash);
3363 if (it == class_table_.end()) {
3364 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003365 }
3366 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003367 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003368}
3369
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003370static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3371 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3372 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003373 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003374 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3375 return root->AsObjectArray<mirror::DexCache>();
3376}
3377
3378void ClassLinker::MoveImageClassesToClassTable() {
3379 Thread* self = Thread::Current();
3380 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3381 if (!dex_cache_image_class_lookup_required_) {
3382 return; // All dex cache classes are already in the class table.
3383 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003384 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003385 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003386 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003387 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3388 mirror::DexCache* dex_cache = dex_caches->Get(i);
3389 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3390 for (int32_t j = 0; j < types->GetLength(); j++) {
3391 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003392 if (klass != nullptr) {
3393 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003394 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003395 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003396 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3397 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003398 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003399 << PrettyClassAndClassLoader(klass);
3400 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003401 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003402 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003403 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003404 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003405 }
3406 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003407 }
3408 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003409 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003410}
3411
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003412void ClassLinker::MoveClassTableToPreZygote() {
3413 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3414 DCHECK(pre_zygote_class_table_.Empty());
3415 pre_zygote_class_table_ = std::move(class_table_);
3416 class_table_.Clear();
3417}
3418
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003419mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003420 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003421 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3422 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3423 mirror::DexCache* dex_cache = dex_caches->Get(i);
3424 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003425 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003426 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003427 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003428 const DexFile::TypeId* type_id =
3429 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003430 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003431 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3432 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003433 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003434 return klass;
3435 }
3436 }
3437 }
3438 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003439 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003440}
3441
3442void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3443 result.clear();
3444 if (dex_cache_image_class_lookup_required_) {
3445 MoveImageClassesToClassTable();
3446 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003447 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3448 while (true) {
3449 auto it = class_table_.Find(descriptor);
3450 if (it == class_table_.end()) {
3451 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003452 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003453 result.push_back(it->Read());
3454 class_table_.Erase(it);
3455 }
3456 for (mirror::Class* k : result) {
3457 class_table_.Insert(GcRoot<mirror::Class>(k));
3458 }
3459 size_t pre_zygote_start = result.size();
3460 // Now handle the pre zygote table.
3461 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3462 // called from the debugger.
3463 while (true) {
3464 auto it = pre_zygote_class_table_.Find(descriptor);
3465 if (it == pre_zygote_class_table_.end()) {
3466 break;
3467 }
3468 result.push_back(it->Read());
3469 pre_zygote_class_table_.Erase(it);
3470 }
3471 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3472 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003473 }
3474}
3475
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003476void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003477 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003478 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003479
Ian Rogers9ffb0392012-09-10 11:56:50 -07003480 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003481 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003482 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003483 return;
3484 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003485 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003486 return;
3487 }
jeffhao98eacac2011-09-14 16:11:53 -07003488
Ian Rogers9ffb0392012-09-10 11:56:50 -07003489 // The class might already be erroneous, for example at compile time if we attempted to verify
3490 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003491 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003492 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003493 return;
3494 }
3495
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003496 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003497 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003498 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003499 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003500 << PrettyClass(klass.Get());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003501 CHECK(!Runtime::Current()->IsAotCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003502 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003503 }
jeffhao98eacac2011-09-14 16:11:53 -07003504
Jeff Hao4a200f52014-04-01 14:58:49 -07003505 // Skip verification if disabled.
3506 if (!Runtime::Current()->IsVerificationEnabled()) {
3507 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003508 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003509 return;
3510 }
3511
Ian Rogers9ffb0392012-09-10 11:56:50 -07003512 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003513 StackHandleScope<2> hs(self);
3514 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003515 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003516 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003517 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003518
3519 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003520 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003521 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003522 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003523 std::string error_msg(
3524 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3525 PrettyDescriptor(klass.Get()).c_str(),
3526 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08003527 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003528 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003529 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003530 self->ClearException();
3531 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003532 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3533 if (cause.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003534 self->GetException()->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003535 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003536 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003537 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003538 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3539 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003540 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003541 return;
3542 }
3543 }
3544
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003545 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003546 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003547 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003548 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003549 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003550 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003551 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003552 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003553 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3554 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003555 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003556 return;
3557 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003558 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003559 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003560 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003561 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003562 Runtime::Current()->IsAotCompiler(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003563 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003564 }
3565 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003566 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003567 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003568 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3569 << " because: " << error_msg;
3570 }
Ian Rogers1f539342012-10-03 21:09:42 -07003571 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003572 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003573 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003574 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003575 // Even though there were no verifier failures we need to respect whether the super-class
3576 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003577 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003578 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003579 } else {
3580 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003581 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003582 // Pretend a soft failure occured so that we don't consider the class verified below.
3583 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003584 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003585 } else {
3586 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3587 // Soft failures at compile time should be retried at runtime. Soft
3588 // failures at runtime will be handled by slow paths in the generated
3589 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003590 if (Runtime::Current()->IsAotCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003591 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003592 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003593 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003594 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3595 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003596 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003597 }
3598 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003599 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08003600 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003601 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3602 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003603 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003604 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003605 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003606 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003607 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003608 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003609 // Let the interpreter know it by setting the kAccPreverified flag onto each
3610 // method.
3611 // Note: we're going here during compilation and at runtime. When we set the
3612 // kAccPreverified flag when compiling image classes, the flag is recorded
3613 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003614 EnsurePreverifiedMethods(klass);
3615 }
3616}
3617
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003618void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003619 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003620 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003621 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003622 }
jeffhao98eacac2011-09-14 16:11:53 -07003623}
3624
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003625bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3626 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003627 // If we're compiling, we can only verify the class using the oat file if
3628 // we are not compiling the image or if the class we're verifying is not part of
3629 // the app. In other words, we will only check for preverification of bootclasspath
3630 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003631 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003632 // Are we compiling the bootclasspath?
3633 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3634 return false;
3635 }
3636 // We are compiling an app (not the image).
3637
3638 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003639 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003640 return false;
3641 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003642 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003643
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003644 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003645 // In case we run without an image there won't be a backing oat file.
3646 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003647 return false;
3648 }
3649
Andreas Gampe76bd8802014-12-10 16:43:58 -08003650 // We may be running with a preopted oat file but without image. In this case,
3651 // we don't skip verification of preverified classes to ensure we initialize
3652 // dex caches with all types resolved during verification.
3653 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
3654 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
3655 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
3656 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003657 if (!Runtime::Current()->IsAotCompiler() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08003658 !Runtime::Current()->GetHeap()->HasImageSpace() &&
3659 klass->GetClassLoader() != nullptr) {
3660 return false;
3661 }
3662
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003663 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003664 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003665 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3666 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003667 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003668 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003669 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003670 // Compile time verification failed with a soft error. Compile time verification can fail
3671 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003672 // class ... {
3673 // Foo x;
3674 // .... () {
3675 // if (...) {
3676 // v1 gets assigned a type of resolved class Foo
3677 // } else {
3678 // v1 gets assigned a type of unresolved class Bar
3679 // }
3680 // iput x = v1
3681 // } }
3682 // when we merge v1 following the if-the-else it results in Conflict
3683 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3684 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3685 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3686 // at compile time).
3687 return false;
3688 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003689 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003690 // Compile time verification failed with a hard error. This is caused by invalid instructions
3691 // in the class. These errors are unrecoverable.
3692 return false;
3693 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003694 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003695 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3696 // not loading the class.
3697 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3698 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003699 return false;
3700 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003701 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003702 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003703 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003704 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003705 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003706}
3707
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003708void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003709 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003710 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3711 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3712 }
3713 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3714 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3715 }
3716}
3717
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003718void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003719 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003720 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3721 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003722 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003723 return; // native or abstract method
3724 }
3725 if (code_item->tries_size_ == 0) {
3726 return; // nothing to process
3727 }
Ian Rogers13735952014-10-08 12:43:28 -07003728 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003729 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3730 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3731 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3732 CatchHandlerIterator iterator(handlers_ptr);
3733 for (; iterator.HasNext(); iterator.Next()) {
3734 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3735 // unresolved exception types will be ignored by exception delivery
3736 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003737 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003738 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003739 DCHECK(Thread::Current()->IsExceptionPending());
3740 Thread::Current()->ClearException();
3741 }
3742 }
3743 }
3744 handlers_ptr = iterator.EndDataPointer();
3745 }
3746}
3747
Brian Carlstromea46f952013-07-30 01:26:50 -07003748static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003749static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3750 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003751
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003752mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003753 jobjectArray interfaces, jobject loader,
3754 jobjectArray methods, jobjectArray throws) {
3755 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003756 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003757 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003758 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003759 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003760 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003761 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003762 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003763 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003764 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003765 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3766 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003767 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003768 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003769 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003770 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003771 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003772 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003773
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003774 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003775 {
3776 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003777 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003778 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003779 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003780 }
3781 klass->SetSFields(sfields);
3782 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003783 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3784 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003785 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3786 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003787 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003788 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003789 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003790 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003791 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003792 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003793 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3794 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003795 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3796 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003797 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003798 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003799 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003800 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003801 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003802 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003803 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003804
Ian Rogers466bb252011-10-14 03:29:56 -07003805 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003806 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003807 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003808 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003809 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003810 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003811 }
3812 klass->SetDirectMethods(directs);
3813 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003814 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003815 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003816 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003817 }
3818 klass->SetDirectMethod(0, constructor);
3819 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003820
Mathieu Chartier590fee92013-09-13 13:46:47 -07003821 // Create virtual method using specified prototypes.
3822 size_t num_virtual_methods =
3823 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003824 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003825 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3826 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003827 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003828 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003829 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003830 }
3831 klass->SetVirtualMethods(virtuals);
3832 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003833 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003834 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003835 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3836 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003837 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003838 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003839 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003840 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003841 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003842 }
3843 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003844 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003845
3846 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003847 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003848 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003849
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003850 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3851 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003852 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003853 // Must hold lock on object when resolved.
3854 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003855 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003856 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003857 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003858 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003859 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003860 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003861 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003862 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003863
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003864 CHECK(klass->IsRetired());
3865 CHECK_NE(klass.Get(), new_class);
3866 klass.Assign(new_class);
3867
3868 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003869 interfaces_sfield->SetObject<false>(klass.Get(),
3870 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003871 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003872 throws_sfield->SetObject<false>(klass.Get(),
3873 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003874
3875 {
3876 // Lock on klass is released. Lock new class object.
3877 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003878 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003879 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003880
3881 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003882 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003883 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003884 CheckProxyConstructor(klass->GetDirectMethod(0));
3885 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003886 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003887 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3888 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003889 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3890 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003891 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003892 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003893
Mathieu Chartier590fee92013-09-13 13:46:47 -07003894 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003895 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003896 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003897 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3898
3899 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
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(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003902
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003903 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003904 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003905 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003906 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003907 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003908 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3909 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003910 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003911 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003912}
3913
Ian Rogersef7d42f2014-01-06 12:55:46 -08003914std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003915 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003916 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003917 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003918 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3919}
3920
Ian Rogersef7d42f2014-01-06 12:55:46 -08003921mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3922 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003923 DCHECK(proxy_class->IsProxyClass());
3924 DCHECK(proxy_method->IsProxyMethod());
3925 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003926 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003927 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003928 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003929 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003930 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003931 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003932 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003933 break;
3934 }
3935 }
3936 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003937 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003938 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003939 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003940 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003941 return resolved_method;
3942}
3943
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003944
Brian Carlstromea46f952013-07-30 01:26:50 -07003945mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003946 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003947 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003948 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003949 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003950 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003951 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3952 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003953 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3954 // constructor method.
3955 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3956 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003957 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3958 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003959 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3960 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003961 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003962 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003963 }
Ian Rogers466bb252011-10-14 03:29:56 -07003964 // Make this constructor public and fix the class to be our Proxy version
3965 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003966 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003967 return constructor;
3968}
3969
Brian Carlstromea46f952013-07-30 01:26:50 -07003970static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003971 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003972 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003973 CHECK_STREQ(constructor->GetName(), "<init>");
3974 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3975 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003976 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003977}
3978
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003979mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003980 Handle<mirror::Class> klass,
3981 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003982 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3983 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003984 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003985 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003986 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003987 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003988 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003989 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003990 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003991 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003992 }
Ian Rogers466bb252011-10-14 03:29:56 -07003993
3994 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3995 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003996 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003997 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003998
Ian Rogers466bb252011-10-14 03:29:56 -07003999 // At runtime the method looks like a reference and argument saving method, clone the code
4000 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004001 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004002 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004003
Ian Rogersc2b44472011-12-14 21:17:17 -08004004 return method;
4005}
Jesse Wilson95caa792011-10-12 18:14:17 -04004006
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004007static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4008 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004009 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004010 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004011 CHECK(!prototype->IsFinal());
4012 CHECK(method->IsFinal());
4013 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004014
4015 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4016 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07004017 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4018 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004019 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4020
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004021 CHECK_STREQ(method->GetName(), prototype->GetName());
4022 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004023 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004024 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004025}
4026
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004027static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4028 bool can_init_parents)
4029 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004030 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004031 return true;
4032 }
4033 if (!can_init_statics) {
4034 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004035 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004036 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004037 return false;
4038 }
4039 // Check if there are encoded static values needing initialization.
4040 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004041 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004042 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004043 if (dex_class_def->static_values_off_ != 0) {
4044 return false;
4045 }
4046 }
4047 }
4048 if (!klass->IsInterface() && klass->HasSuperClass()) {
4049 mirror::Class* super_class = klass->GetSuperClass();
4050 if (!can_init_parents && !super_class->IsInitialized()) {
4051 return false;
4052 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004053 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004054 return false;
4055 }
4056 }
4057 }
4058 return true;
4059}
4060
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004061bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004062 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004063 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4064
4065 // Are we already initialized and therefore done?
4066 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4067 // an initialized class will never change its state.
4068 if (klass->IsInitialized()) {
4069 return true;
4070 }
4071
4072 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004073 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004074 return false;
4075 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004076
Ian Rogers7b078e82014-09-10 14:44:24 -07004077 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004078 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004079 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004080 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004081
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004082 // Re-check under the lock in case another thread initialized ahead of us.
4083 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004084 return true;
4085 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004086
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004087 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004088 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004089 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004090 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004091 return false;
4092 }
4093
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004094 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004095
4096 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004097 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004098 if (!klass->IsVerified()) {
4099 // We failed to verify, expect either the klass to be erroneous or verification failed at
4100 // compile time.
4101 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004102 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004103 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004104 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004105 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004106 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004107 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004108 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004109 } else {
4110 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004111 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004112 }
4113
Brian Carlstromd1422f82011-09-28 11:37:09 -07004114 // If the class is kStatusInitializing, either this thread is
4115 // initializing higher up the stack or another thread has beat us
4116 // to initializing and we need to wait. Either way, this
4117 // invocation of InitializeClass will not be responsible for
4118 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004119 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004120 // Could have got an exception during verification.
4121 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004122 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004123 return false;
4124 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004125 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004126 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004127 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004128 return true;
4129 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004130 // No. That's fine. Wait for another thread to finish initializing.
4131 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004132 }
4133
4134 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004135 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004136 return false;
4137 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004138 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004139
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004140 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004141
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004142 // From here out other threads may observe that we're initializing and so changes of state
4143 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004144 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004145 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004146
4147 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004148 }
4149
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004150 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004151 if (!klass->IsInterface() && klass->HasSuperClass()) {
4152 mirror::Class* super_class = klass->GetSuperClass();
4153 if (!super_class->IsInitialized()) {
4154 CHECK(!super_class->IsInterface());
4155 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004156 StackHandleScope<1> hs(self);
4157 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004158 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004159 if (!super_initialized) {
4160 // The super class was verified ahead of entering initializing, we should only be here if
4161 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004162 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004163 << "Super class initialization failed for "
4164 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004165 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004166 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004167 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004168 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004169 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004170 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004171 return false;
4172 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004173 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004174 }
4175
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004176 const size_t num_static_fields = klass->NumStaticFields();
4177 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004178 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004179 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004180 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004181 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004182 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004183 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004184
4185 // Eagerly fill in static fields so that the we don't have to do as many expensive
4186 // Class::FindStaticField in ResolveField.
4187 for (size_t i = 0; i < num_static_fields; ++i) {
4188 mirror::ArtField* field = klass->GetStaticField(i);
4189 const uint32_t field_idx = field->GetDexFieldIndex();
4190 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4191 if (resolved_field == nullptr) {
4192 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004193 } else {
4194 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004195 }
4196 }
4197
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004198 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4199 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004200 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004201 ClassDataItemIterator field_it(dex_file, class_data);
4202 if (value_it.HasNext()) {
4203 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004204 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004205 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004206 StackHandleScope<1> hs2(self);
4207 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004208 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004209 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004210 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004211 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004212 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004213 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004214 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004215 }
4216 }
4217 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004218
Ian Rogersd91d6d62013-09-25 20:26:14 -07004219 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004220 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004221 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004222 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004223 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004224 }
4225
Ian Rogers7b078e82014-09-10 14:44:24 -07004226 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004227 uint64_t t1 = NanoTime();
4228
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004229 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004230 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004231 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004232
4233 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004234 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004235 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004236 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004237 } else if (Runtime::Current()->IsTransactionAborted()) {
4238 // The exception thrown when the transaction aborted has been caught and cleared
4239 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01004240 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
4241 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004242 Runtime::Current()->ThrowInternalErrorForAbortedTransaction(self);
4243 klass->SetStatus(mirror::Class::kStatusError, self);
4244 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004245 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004246 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4247 RuntimeStats* thread_stats = self->GetStats();
4248 ++global_stats->class_init_count;
4249 ++thread_stats->class_init_count;
4250 global_stats->class_init_time_ns += (t1 - t0);
4251 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004252 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004253 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004254 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004255 std::string temp;
4256 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004257 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004258 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004259 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004260 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004261 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004262 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004263 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004264}
4265
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004266bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004267 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004268 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004269 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004270 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004271 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004272 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004273
4274 // When we wake up, repeat the test for init-in-progress. If
4275 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004276 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004277 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004278 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004279 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004280 return false;
4281 }
4282 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004283 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004284 continue;
4285 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004286 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
4287 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004288 // Compile time initialization failed.
4289 return false;
4290 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004291 if (klass->IsErroneous()) {
4292 // The caller wants an exception, but it was thrown in a
4293 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004294 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004295 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004296 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004297 return false;
4298 }
4299 if (klass->IsInitialized()) {
4300 return true;
4301 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004302 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004303 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004304 }
Ian Rogers07140832014-09-30 15:43:59 -07004305 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004306}
4307
Ian Rogersb5fb2072014-12-02 17:22:02 -08004308static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
4309 Handle<mirror::ArtMethod> method1,
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004310 Handle<mirror::ArtMethod> method2,
4311 std::string* error_msg)
Ian Rogersb5fb2072014-12-02 17:22:02 -08004312 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4313 {
4314 StackHandleScope<1> hs(self);
4315 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
Vladimir Marko862f43c2015-02-10 18:22:57 +00004316 mirror::Class* other_return_type = method2->GetReturnType();
4317 // NOTE: return_type.Get() must be sequenced after method2->GetReturnType().
4318 if (UNLIKELY(other_return_type != return_type.Get())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004319 *error_msg = StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
4320 PrettyClassAndClassLoader(return_type.Get()).c_str(),
4321 return_type.Get(),
4322 PrettyClassAndClassLoader(other_return_type).c_str(),
4323 other_return_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004324 return false;
4325 }
4326 }
4327 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4328 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4329 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004330 if (types2 != nullptr && types2->Size() != 0) {
4331 *error_msg = StringPrintf("Type list mismatch with %s",
4332 PrettyMethod(method2.Get(), true).c_str());
4333 return false;
4334 }
4335 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08004336 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004337 if (types1->Size() != 0) {
4338 *error_msg = StringPrintf("Type list mismatch with %s",
4339 PrettyMethod(method2.Get(), true).c_str());
4340 return false;
4341 }
4342 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08004343 }
4344 uint32_t num_types = types1->Size();
4345 if (UNLIKELY(num_types != types2->Size())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004346 *error_msg = StringPrintf("Type list mismatch with %s",
4347 PrettyMethod(method2.Get(), true).c_str());
Ian Rogersb5fb2072014-12-02 17:22:02 -08004348 return false;
4349 }
4350 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00004351 StackHandleScope<1> hs(self);
4352 Handle<mirror::Class> param_type(hs.NewHandle(
4353 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true)));
Ian Rogersb5fb2072014-12-02 17:22:02 -08004354 mirror::Class* other_param_type =
4355 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
Vladimir Marko862f43c2015-02-10 18:22:57 +00004356 // NOTE: param_type.Get() must be sequenced after method2->GetClassFromTypeIndex(...).
4357 if (UNLIKELY(param_type.Get() != other_param_type)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004358 *error_msg = StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
4359 i,
4360 PrettyClassAndClassLoader(param_type.Get()).c_str(),
4361 param_type.Get(),
4362 PrettyClassAndClassLoader(other_param_type).c_str(),
4363 other_param_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004364 return false;
4365 }
4366 }
4367 return true;
4368}
4369
4370
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004371bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004372 if (klass->IsInterface()) {
4373 return true;
4374 }
Ian Rogers151f2212014-05-06 11:27:27 -07004375 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004376 Thread* self = Thread::Current();
4377 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004378 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
4379 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004380 if (klass->HasSuperClass() &&
4381 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004382 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004383 h_m.Assign(klass->GetVTableEntry(i));
4384 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004385 if (h_m.Get() != super_h_m.Get()) {
4386 std::string error_msg;
4387 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
4388 ThrowLinkageError(klass.Get(),
4389 "Class %s method %s resolves differently in superclass %s: %s",
4390 PrettyDescriptor(klass.Get()).c_str(),
4391 PrettyMethod(h_m.Get()).c_str(),
4392 PrettyDescriptor(klass->GetSuperClass()).c_str(),
4393 error_msg.c_str());
4394 return false;
4395 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004396 }
4397 }
4398 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004399 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004400 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4401 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4402 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004403 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4404 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004405 if (h_m.Get() != super_h_m.Get()) {
4406 std::string error_msg;
4407 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
4408 ThrowLinkageError(klass.Get(),
4409 "Class %s method %s resolves differently in interface %s: %s",
4410 PrettyDescriptor(klass.Get()).c_str(),
4411 PrettyMethod(h_m.Get()).c_str(),
4412 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str(),
4413 error_msg.c_str());
4414 return false;
4415 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004416 }
4417 }
4418 }
4419 }
4420 return true;
4421}
4422
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004423bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4424 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004425 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004426 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004427 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004428 return true;
4429 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004430 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004431 if (!success) {
4432 if (can_init_fields && can_init_parents) {
4433 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4434 }
4435 } else {
4436 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004437 }
4438 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004439}
4440
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004441void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4442 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4443 if (fields != nullptr) {
4444 for (int index = 0; index < fields->GetLength(); index ++) {
4445 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4446 fields->Get(index)->SetDeclaringClass(new_class);
4447 }
4448 }
4449 }
4450
4451 fields = new_class->GetSFields();
4452 if (fields != nullptr) {
4453 for (int index = 0; index < fields->GetLength(); index ++) {
4454 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4455 fields->Get(index)->SetDeclaringClass(new_class);
4456 }
4457 }
4458 }
4459
4460 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4461 if (methods != nullptr) {
4462 for (int index = 0; index < methods->GetLength(); index ++) {
4463 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4464 methods->Get(index)->SetDeclaringClass(new_class);
4465 }
4466 }
4467 }
4468
4469 methods = new_class->GetVirtualMethods();
4470 if (methods != nullptr) {
4471 for (int index = 0; index < methods->GetLength(); index ++) {
4472 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4473 methods->Get(index)->SetDeclaringClass(new_class);
4474 }
4475 }
4476 }
4477}
4478
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004479bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4480 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004481 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004482 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004483
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004484 if (!LinkSuperClass(klass)) {
4485 return false;
4486 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004487 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4488 self, Runtime::Current()->GetImtUnimplementedMethod());
4489 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004490 return false;
4491 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004492 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004493 return false;
4494 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004495 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004496 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004497 return false;
4498 }
4499 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004500 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004501
4502 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4503 // We don't need to retire this class as it has no embedded tables or it was created the
4504 // correct size during class linker initialization.
4505 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4506
4507 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004508 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004509 }
4510
4511 // This will notify waiters on klass that saw the not yet resolved
4512 // class in the class_table_ during EnsureResolved.
4513 klass->SetStatus(mirror::Class::kStatusResolved, self);
4514 *new_class = klass.Get();
4515 } else {
4516 CHECK(!klass->IsResolved());
4517 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004518 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004519 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004520 CHECK(self->IsExceptionPending()); // Expect an OOME.
4521 klass->SetStatus(mirror::Class::kStatusError, self);
4522 return false;
4523 }
4524
4525 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4526 StackHandleScope<1> hs(self);
4527 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4528 ObjectLock<mirror::Class> lock(self, new_class_h);
4529
4530 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4531
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004532 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4533 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004534 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004535
4536 // This will notify waiters on temp class that saw the not yet resolved class in the
4537 // class_table_ during EnsureResolved.
4538 klass->SetStatus(mirror::Class::kStatusRetired, self);
4539
4540 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4541 // This will notify waiters on new_class that saw the not yet resolved
4542 // class in the class_table_ during EnsureResolved.
4543 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004544 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004545 return true;
4546}
4547
Andreas Gampefd9eb392014-11-06 16:52:58 -08004548static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
4549 size_t* virtual_methods,
4550 size_t* direct_methods,
4551 size_t* static_fields,
4552 size_t* instance_fields) {
4553 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
4554
4555 while (dex_data.HasNextStaticField()) {
4556 dex_data.Next();
4557 (*static_fields)++;
4558 }
4559 while (dex_data.HasNextInstanceField()) {
4560 dex_data.Next();
4561 (*instance_fields)++;
4562 }
4563 while (dex_data.HasNextDirectMethod()) {
4564 (*direct_methods)++;
4565 dex_data.Next();
4566 }
4567 while (dex_data.HasNextVirtualMethod()) {
4568 (*virtual_methods)++;
4569 dex_data.Next();
4570 }
4571 DCHECK(!dex_data.HasNext());
4572}
4573
4574static void DumpClass(std::ostream& os,
4575 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
4576 const char* suffix) {
4577 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
4578 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
4579 os << " Static fields:\n";
4580 while (dex_data.HasNextStaticField()) {
4581 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4582 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4583 dex_data.Next();
4584 }
4585 os << " Instance fields:\n";
4586 while (dex_data.HasNextInstanceField()) {
4587 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4588 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4589 dex_data.Next();
4590 }
4591 os << " Direct methods:\n";
4592 while (dex_data.HasNextDirectMethod()) {
4593 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4594 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4595 dex_data.Next();
4596 }
4597 os << " Virtual methods:\n";
4598 while (dex_data.HasNextVirtualMethod()) {
4599 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4600 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4601 dex_data.Next();
4602 }
4603}
4604
4605static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4606 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
4607 std::ostringstream os;
4608 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
4609 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
4610 return os.str();
4611}
4612
4613
4614// Very simple structural check on whether the classes match. Only compares the number of
4615// methods and fields.
4616static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4617 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
4618 std::string* error_msg) {
4619 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
4620 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
4621
4622 // Counters for current dex file.
4623 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
4624 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
4625 &dex_instance_fields1);
4626 // Counters for compile-time dex file.
4627 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
4628 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
4629 &dex_instance_fields2);
4630
4631 if (dex_virtual_methods1 != dex_virtual_methods2) {
4632 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4633 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
4634 dex_virtual_methods2, class_dump.c_str());
4635 return false;
4636 }
4637 if (dex_direct_methods1 != dex_direct_methods2) {
4638 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4639 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
4640 dex_direct_methods2, class_dump.c_str());
4641 return false;
4642 }
4643 if (dex_static_fields1 != dex_static_fields2) {
4644 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4645 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
4646 dex_static_fields2, class_dump.c_str());
4647 return false;
4648 }
4649 if (dex_instance_fields1 != dex_instance_fields2) {
4650 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4651 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
4652 dex_instance_fields2, class_dump.c_str());
4653 return false;
4654 }
4655
4656 return true;
4657}
4658
4659// Checks whether a the super-class changed from what we had at compile-time. This would
4660// invalidate quickening.
4661static bool CheckSuperClassChange(Handle<mirror::Class> klass,
4662 const DexFile& dex_file,
4663 const DexFile::ClassDef& class_def,
4664 mirror::Class* super_class)
4665 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4666 // Check for unexpected changes in the superclass.
4667 // Quick check 1) is the super_class class-loader the boot class loader? This always has
4668 // precedence.
4669 if (super_class->GetClassLoader() != nullptr &&
4670 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
4671 // which is implied by different dex cache.
4672 klass->GetDexCache() != super_class->GetDexCache()) {
4673 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
4674 // definition for the super-class, and (b) the files are in separate oat files. The oat files
4675 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
4676 const OatFile* class_oat_file = dex_file.GetOatFile();
4677 if (class_oat_file != nullptr) {
4678 const OatFile* loaded_super_oat_file = super_class->GetDexFile().GetOatFile();
4679 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
4680 // Now check (a).
4681 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
4682 if (super_class_def != nullptr) {
4683 // Uh-oh, we found something. Do our check.
4684 std::string error_msg;
4685 if (!SimpleStructuralCheck(dex_file, *super_class_def,
4686 super_class->GetDexFile(), *super_class->GetClassDef(),
4687 &error_msg)) {
4688 // Print a warning to the log. This exception might be caught, e.g., as common in test
4689 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
4690 // only save the type of the exception.
4691 LOG(WARNING) << "Incompatible structural change detected: " <<
4692 StringPrintf(
4693 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4694 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4695 class_oat_file->GetLocation().c_str(),
4696 loaded_super_oat_file->GetLocation().c_str(),
4697 error_msg.c_str());
4698 ThrowIncompatibleClassChangeError(klass.Get(),
4699 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4700 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4701 class_oat_file->GetLocation().c_str(),
4702 loaded_super_oat_file->GetLocation().c_str(),
4703 error_msg.c_str());
4704 return false;
4705 }
4706 }
4707 }
4708 }
4709 }
4710 return true;
4711}
4712
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004713bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004714 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004715 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4716 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004717 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004718 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004719 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004720 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004721 return false;
4722 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004723 // Verify
4724 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004725 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004726 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004727 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004728 return false;
4729 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004730 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004731 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08004732
4733 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
4734 DCHECK(Thread::Current()->IsExceptionPending());
4735 return false;
4736 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004737 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004738 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004739 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004740 for (size_t i = 0; i < interfaces->Size(); i++) {
4741 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004742 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004743 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004744 DCHECK(Thread::Current()->IsExceptionPending());
4745 return false;
4746 }
4747 // Verify
4748 if (!klass->CanAccess(interface)) {
4749 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004750 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004751 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004752 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004753 return false;
4754 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004755 }
4756 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004757 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004758 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004759 return true;
4760}
4761
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004762bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004763 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004764 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004765 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004766 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004767 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004768 return false;
4769 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004770 return true;
4771 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004772 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004773 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4774 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004775 return false;
4776 }
4777 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004778 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004779 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004780 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004781 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004782 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004783 return false;
4784 }
4785 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004786 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004787 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004788 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004789 return false;
4790 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004791
Brian Carlstromf3632832014-05-20 15:36:53 -07004792 // Inherit kAccClassIsFinalizable from the superclass in case this
4793 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004794 if (super->IsFinalizable()) {
4795 klass->SetFinalizable();
4796 }
4797
Elliott Hughes2da50362011-10-10 16:57:08 -07004798 // Inherit reference flags (if any) from the superclass.
4799 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4800 if (reference_flags != 0) {
4801 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4802 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004803 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004804 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004805 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004806 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004807 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004808 return false;
4809 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004810
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004811 if (kIsDebugBuild) {
4812 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004813 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004814 CHECK(super->IsResolved());
4815 super = super->GetSuperClass();
4816 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004817 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004818 return true;
4819}
4820
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004821// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004822bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004823 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4824 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004825 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004826 if (klass->IsInterface()) {
4827 // No vtable.
4828 size_t count = klass->NumVirtualMethods();
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004829 if (!IsUint<16>(count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004830 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004831 return false;
4832 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004833 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004834 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004835 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004836 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4837 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004838 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004839 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004840}
4841
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004842// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4843// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4844// caches in the implementation below.
4845class MethodNameAndSignatureComparator FINAL : public ValueObject {
4846 public:
4847 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4848 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4849 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4850 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004851 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4852 }
4853
4854 const char* GetName() {
4855 if (name_ == nullptr) {
4856 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4857 }
4858 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004859 }
4860
4861 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4862 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4863 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4864 const DexFile* other_dex_file = other->GetDexFile();
4865 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4866 if (dex_file_ == other_dex_file) {
4867 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4868 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004869 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004870 uint32_t other_name_len;
4871 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4872 &other_name_len);
4873 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4874 return false;
4875 }
4876 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4877 }
4878
4879 private:
4880 // Dex file for the method to compare against.
4881 const DexFile* const dex_file_;
4882 // MethodId for the method to compare against.
4883 const DexFile::MethodId* const mid_;
4884 // Lazily computed name from the dex file's strings.
4885 const char* name_;
4886 // Lazily computed name length.
4887 uint32_t name_len_;
4888};
4889
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004890class LinkVirtualHashTable {
4891 public:
4892 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4893 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4894 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4895 }
4896 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4897 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4898 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004899 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004900 uint32_t index = hash % hash_size_;
4901 // Linear probe until we have an empty slot.
4902 while (hash_table_[index] != invalid_index_) {
4903 if (++index == hash_size_) {
4904 index = 0;
4905 }
4906 }
4907 hash_table_[index] = virtual_method_index;
4908 }
4909 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4910 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4911 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004912 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004913 size_t index = hash % hash_size_;
4914 while (true) {
4915 const uint32_t value = hash_table_[index];
4916 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4917 // the block and can safely assume not found.
4918 if (value == invalid_index_) {
4919 break;
4920 }
4921 if (value != removed_index_) { // This signifies not already overriden.
4922 mirror::ArtMethod* virtual_method =
4923 klass_->GetVirtualMethodDuringLinking(value);
4924 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4925 hash_table_[index] = removed_index_;
4926 return value;
4927 }
4928 }
4929 if (++index == hash_size_) {
4930 index = 0;
4931 }
4932 }
4933 return GetNotFoundIndex();
4934 }
4935 static uint32_t GetNotFoundIndex() {
4936 return invalid_index_;
4937 }
4938
4939 private:
4940 static const uint32_t invalid_index_;
4941 static const uint32_t removed_index_;
4942
4943 Handle<mirror::Class> klass_;
4944 const size_t hash_size_;
4945 uint32_t* const hash_table_;
4946};
4947
4948const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4949const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4950
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004951bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004952 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004953 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004954 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4955 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004956 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004957 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004958 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004959 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4960 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4961 if (UNLIKELY(vtable.Get() == nullptr)) {
4962 CHECK(self->IsExceptionPending()); // OOME.
4963 return false;
4964 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004965 for (size_t i = 0; i < super_vtable_length; i++) {
4966 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004967 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004968 if (num_virtual_methods == 0) {
4969 klass->SetVTable(vtable.Get());
4970 return true;
4971 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004972 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004973 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4974 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4975 if (num_virtual_methods == 0) {
4976 klass->SetVTable(super_vtable);
4977 return true;
4978 }
4979 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004980 if (UNLIKELY(vtable.Get() == nullptr)) {
4981 CHECK(self->IsExceptionPending()); // OOME.
4982 return false;
4983 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004984 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004985 // How the algorithm works:
4986 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4987 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4988 // method which has not been matched to a vtable method, and j if the virtual method at the
4989 // index overrode the super virtual method at index j.
4990 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4991 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4992 // the need for the initial vtable which we later shrink back down).
4993 // 3. Add non overridden methods to the end of the vtable.
4994 static constexpr size_t kMaxStackHash = 250;
4995 const size_t hash_table_size = num_virtual_methods * 3;
4996 uint32_t* hash_table_ptr;
4997 std::unique_ptr<uint32_t[]> hash_heap_storage;
4998 if (hash_table_size <= kMaxStackHash) {
4999 hash_table_ptr = reinterpret_cast<uint32_t*>(
5000 alloca(hash_table_size * sizeof(*hash_table_ptr)));
5001 } else {
5002 hash_heap_storage.reset(new uint32_t[hash_table_size]);
5003 hash_table_ptr = hash_heap_storage.get();
5004 }
5005 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
5006 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005007 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005008 hash_table.Add(i);
5009 }
5010 // Loop through each super vtable method and see if they are overriden by a method we added to
5011 // the hash table.
5012 for (size_t j = 0; j < super_vtable_length; ++j) {
5013 // Search the hash table to see if we are overidden by any method.
5014 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
5015 MethodNameAndSignatureComparator super_method_name_comparator(
5016 super_method->GetInterfaceMethodIfProxy());
5017 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5018 if (hash_index != hash_table.GetNotFoundIndex()) {
5019 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
5020 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
5021 super_method->GetAccessFlags())) {
5022 if (super_method->IsFinal()) {
5023 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5024 PrettyMethod(virtual_method).c_str(),
5025 super_method->GetDeclaringClassDescriptor());
5026 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005027 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005028 vtable->SetWithoutChecks<false>(j, virtual_method);
5029 virtual_method->SetMethodIndex(j);
5030 } else {
5031 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005032 << " would have incorrectly overridden the package-private method in "
5033 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005034 }
5035 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005036 }
5037 // Add the non overridden methods at the end.
5038 size_t actual_count = super_vtable_length;
5039 for (size_t i = 0; i < num_virtual_methods; ++i) {
5040 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
5041 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5042 if (method_idx < super_vtable_length &&
5043 local_method == vtable->GetWithoutChecks(method_idx)) {
5044 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005045 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005046 vtable->SetWithoutChecks<false>(actual_count, local_method);
5047 local_method->SetMethodIndex(actual_count);
5048 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005049 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005050 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005051 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005052 return false;
5053 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005054 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005055 CHECK_LE(actual_count, max_count);
5056 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005057 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005058 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005059 CHECK(self->IsExceptionPending()); // OOME.
5060 return false;
5061 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005062 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005063 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005064 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005065 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005066 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005067 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5068 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005069 return false;
5070 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005071 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
5072 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005073 CHECK(self->IsExceptionPending()); // OOME.
5074 return false;
5075 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005076 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005077 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005078 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005079 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005080 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005081 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005082 }
5083 return true;
5084}
5085
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005086bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
5087 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
5088 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07005089 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005090 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005091 const bool has_superclass = klass->HasSuperClass();
5092 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
5093 const bool have_interfaces = interfaces.Get() != nullptr;
5094 const size_t num_interfaces =
5095 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
5096 if (num_interfaces == 0) {
5097 if (super_ifcount == 0) {
5098 // Class implements no interfaces.
5099 DCHECK_EQ(klass->GetIfTableCount(), 0);
5100 DCHECK(klass->GetIfTable() == nullptr);
5101 return true;
5102 }
Ian Rogers9bc81912012-10-11 21:43:36 -07005103 // Class implements same interfaces as parent, are any of these not marker interfaces?
5104 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005105 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005106 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005107 if (super_iftable->GetMethodArrayCount(i) > 0) {
5108 has_non_marker_interface = true;
5109 break;
5110 }
5111 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005112 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07005113 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005114 klass->SetIfTable(super_iftable);
5115 return true;
5116 }
5117 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005118 size_t ifcount = super_ifcount + num_interfaces;
5119 for (size_t i = 0; i < num_interfaces; i++) {
5120 mirror::Class* interface = have_interfaces ?
5121 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
5122 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005123 if (UNLIKELY(!interface->IsInterface())) {
5124 std::string temp;
5125 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
5126 PrettyDescriptor(klass.Get()).c_str(),
5127 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
5128 return false;
5129 }
5130 ifcount += interface->GetIfTableCount();
5131 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005132 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005133 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005134 CHECK(self->IsExceptionPending()); // OOME.
5135 return false;
5136 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005137 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005138 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005139 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005140 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07005141 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005142 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005143 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005144 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005145 // Flatten the interface inheritance hierarchy.
5146 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005147 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07005148 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
5149 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005150 // Check if interface is already in iftable
5151 bool duplicate = false;
5152 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005153 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005154 if (existing_interface == interface) {
5155 duplicate = true;
5156 break;
5157 }
5158 }
5159 if (!duplicate) {
5160 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07005161 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005162 // Add this interface's non-duplicate super-interfaces.
5163 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005164 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005165 bool super_duplicate = false;
5166 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005167 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005168 if (existing_interface == super_interface) {
5169 super_duplicate = true;
5170 break;
5171 }
5172 }
5173 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005174 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005175 }
5176 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005177 }
5178 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005179 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08005180 // Shrink iftable in case duplicates were found
5181 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005182 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005183 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005184 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005185 CHECK(self->IsExceptionPending()); // OOME.
5186 return false;
5187 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08005188 ifcount = idx;
5189 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005190 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005191 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005192 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07005193 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07005194 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005195 return true;
5196 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005197 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005198 size_t max_miranda_methods = 0; // The max size of miranda_list.
5199 for (size_t i = 0; i < ifcount; ++i) {
5200 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
5201 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005202 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005203 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005204 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
5205 hs.NewHandle(klass->GetVTableDuringLinking()));
5206 // Copy the IMT from the super class if possible.
5207 bool extend_super_iftable = false;
5208 if (has_superclass) {
5209 mirror::Class* super_class = klass->GetSuperClass();
5210 extend_super_iftable = true;
5211 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5212 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5213 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
5214 }
5215 } else {
5216 // No imt in the super class, need to reconstruct from the iftable.
5217 mirror::IfTable* if_table = super_class->GetIfTable();
5218 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5219 const size_t length = super_class->GetIfTableCount();
5220 for (size_t i = 0; i < length; ++i) {
5221 mirror::Class* interface = iftable->GetInterface(i);
5222 const size_t num_virtuals = interface->NumVirtualMethods();
5223 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5224 DCHECK_EQ(num_virtuals, method_array_count);
5225 if (method_array_count == 0) {
5226 continue;
5227 }
5228 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5229 for (size_t j = 0; j < num_virtuals; ++j) {
5230 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5231 if (method->IsMiranda()) {
5232 continue;
5233 }
5234 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5235 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5236 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5237 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5238 out_imt->SetReference(imt_index, method);
5239 } else if (imt_ref != conflict_method) {
5240 out_imt->SetReference(imt_index, conflict_method);
5241 }
5242 }
5243 }
5244 }
5245 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005246 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005247 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005248 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005249 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005250 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005251 const bool is_super = i < super_ifcount;
5252 const bool super_interface = is_super && extend_super_iftable;
5253 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5254 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5255 if (super_interface) {
5256 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5257 DCHECK(if_table != nullptr);
5258 DCHECK(if_table->GetMethodArray(i) != nullptr);
5259 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005260 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005261 AsObjectArray<mirror::ArtMethod>());
5262 // We are overwriting a super class interface, try to only virtual methods instead of the
5263 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005264 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005265 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005266 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005267 // A new interface, we need the whole vtable incase a new interface method is implemented
5268 // in the whole superclass.
5269 input_array = vtable;
5270 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005271 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005272 CHECK(self->IsExceptionPending()); // OOME.
5273 return false;
5274 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005275 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005276 if (input_array.Get() == nullptr) {
5277 // If the added virtual methods is empty, do nothing.
5278 DCHECK(super_interface);
5279 continue;
5280 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005281 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005282 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005283 MethodNameAndSignatureComparator interface_name_comparator(
5284 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005285 int32_t k;
5286 // For each method listed in the interface's method list, find the
5287 // matching method in our class's method list. We want to favor the
5288 // subclass over the superclass, which just requires walking
5289 // back from the end of the vtable. (This only matters if the
5290 // superclass defines a private method and this class redefines
5291 // it -- otherwise it would use the same vtable slot. In .dex files
5292 // those don't end up in the virtual method table, so it shouldn't
5293 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005294 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5295 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005296 mirror::ArtMethod* vtable_method_for_name_comparison =
5297 vtable_method->GetInterfaceMethodIfProxy();
5298 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005299 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005300 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005301 ThrowIllegalAccessError(
5302 klass.Get(),
5303 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005304 PrettyMethod(vtable_method).c_str(),
5305 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005306 return false;
5307 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005308 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005309 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005310 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5311 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5312 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5313 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5314 out_imt->SetReference(imt_index, vtable_method);
5315 } else if (imt_ref != conflict_method) {
5316 // If we are not a conflict and we have the same signature and name as the imt entry,
5317 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005318 MethodNameAndSignatureComparator imt_ref_name_comparator(
5319 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005320 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005321 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005322 out_imt->SetReference(imt_index, vtable_method);
5323 } else {
5324 out_imt->SetReference(imt_index, conflict_method);
5325 }
Jeff Hao88474b42013-10-23 16:24:40 -07005326 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005327 break;
5328 }
5329 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005330 if (k < 0 && !super_interface) {
5331 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005332 for (size_t l = 0; l < miranda_list_size; ++l) {
5333 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005334 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005335 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005336 break;
5337 }
5338 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005339 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005340 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005341 miranda_method = interface_method->Clone(self)->AsArtMethod();
5342 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005343 CHECK(self->IsExceptionPending()); // OOME.
5344 return false;
5345 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005346 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005347 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005348 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005349 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005350 }
5351 }
5352 }
5353 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005354 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005355 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005356 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005357 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5358 if (old_method_count == 0) {
5359 virtuals = AllocArtMethodArray(self, new_method_count);
5360 } else {
5361 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5362 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005363 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005364 CHECK(self->IsExceptionPending()); // OOME.
5365 return false;
5366 }
5367 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005368
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005369 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005370 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005371 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005372 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005373 CHECK(self->IsExceptionPending()); // OOME.
5374 return false;
5375 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005376 for (size_t i = 0; i < miranda_list_size; ++i) {
5377 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005378 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005379 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5380 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5381 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005382 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005383 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005384 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005385 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005386 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005387
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005388 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005389 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5390 for (int i = 0; i < check_vtable->GetLength(); ++i) {
5391 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005392 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005393 }
5394
Ian Rogers7b078e82014-09-10 14:44:24 -07005395 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005396 return true;
5397}
5398
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005399bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005400 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005401 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005402}
5403
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005404bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005405 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005406 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005407}
5408
Brian Carlstromdbc05252011-09-09 01:59:59 -07005409struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005410 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5411 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005412 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005413 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005414 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005415 // 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 -07005416 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5417 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005418 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005419 if (type1 == Primitive::kPrimNot) {
5420 // Reference always goes first.
5421 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005422 }
Vladimir Markod5777482014-11-12 17:02:02 +00005423 if (type2 == Primitive::kPrimNot) {
5424 // Reference always goes first.
5425 return false;
5426 }
5427 size_t size1 = Primitive::ComponentSize(type1);
5428 size_t size2 = Primitive::ComponentSize(type2);
5429 if (size1 != size2) {
5430 // Larger primitive types go first.
5431 return size1 > size2;
5432 }
5433 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5434 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005435 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005436 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5437 // by name and for equal names by type id index.
5438 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5439 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005440 }
5441};
5442
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005443bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005444 size_t* class_size) {
5445 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005446 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005447 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005448
Brian Carlstromea46f952013-07-30 01:26:50 -07005449 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005450 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005451
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005452 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005453 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005454 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00005455 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005456 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005457 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005458 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005459 CHECK(super_class->IsResolved())
5460 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005461 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005462 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005463 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005464
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005465 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005466
Brian Carlstromdbc05252011-09-09 01:59:59 -07005467 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005468 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005469 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005470 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005471 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005472 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005473 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005474 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005475 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005476 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005477 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5478 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005479
Fred Shih381e4ca2014-08-25 17:24:27 -07005480 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005481 size_t current_field = 0;
5482 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005483 FieldGaps gaps;
5484
Brian Carlstromdbc05252011-09-09 01:59:59 -07005485 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005486 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005487 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005488 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005489 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005490 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005491 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005492 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5493 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005494 MemberOffset old_offset = field_offset;
5495 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5496 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5497 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005498 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005499 grouped_and_sorted_fields.pop_front();
5500 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005501 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005502 field_offset = MemberOffset(field_offset.Uint32Value() +
5503 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005504 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005505 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5506 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005507 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5508 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5509 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5510 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005511 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5512 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005513 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005514
Elliott Hughesadb460d2011-10-05 17:02:34 -07005515 // 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 -07005516 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005517 // We know there are no non-reference fields in the Reference classes, and we know
5518 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005519 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005520 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005521 --num_reference_fields;
5522 }
5523
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005524 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005525 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005526 if (is_static) {
5527 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005528 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005529 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005530 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005531 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08005532 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
Jeff Haoc7d11882015-02-03 15:08:39 -08005533 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
5534 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartier2d721012014-11-10 11:08:06 -08005535 } else {
5536 std::string temp;
5537 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5538 size_t previous_size = klass->GetObjectSize();
5539 if (previous_size != 0) {
5540 // Make sure that we didn't originally have an incorrect size.
5541 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5542 }
5543 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005544 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005545 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005546 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005547
5548 if (kIsDebugBuild) {
5549 // Make sure that the fields array is ordered by name but all reference
5550 // offsets are at the beginning as far as alignment allows.
5551 MemberOffset start_ref_offset = is_static
5552 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5553 : klass->GetFirstReferenceInstanceFieldOffset();
5554 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5555 num_reference_fields *
5556 sizeof(mirror::HeapReference<mirror::Object>));
5557 MemberOffset current_ref_offset = start_ref_offset;
5558 for (size_t i = 0; i < num_fields; i++) {
5559 mirror::ArtField* field = fields->Get(i);
5560 if ((false)) { // enable to debug field layout
5561 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5562 << " class=" << PrettyClass(klass.Get())
5563 << " field=" << PrettyField(field)
5564 << " offset="
5565 << field->GetField32(mirror::ArtField::OffsetOffset());
5566 }
5567 if (i != 0) {
5568 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005569 // NOTE: The field names can be the same. This is not possible in the Java language
5570 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5571 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005572 }
5573 Primitive::Type type = field->GetTypeAsPrimitiveType();
5574 bool is_primitive = type != Primitive::kPrimNot;
5575 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5576 strcmp("referent", field->GetName()) == 0) {
5577 is_primitive = true; // We lied above, so we have to expect a lie here.
5578 }
5579 MemberOffset offset = field->GetOffsetDuringLinking();
5580 if (is_primitive) {
5581 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5582 // Shuffled before references.
5583 size_t type_size = Primitive::ComponentSize(type);
5584 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5585 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5586 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5587 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5588 }
5589 } else {
5590 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5591 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5592 sizeof(mirror::HeapReference<mirror::Object>));
5593 }
5594 }
5595 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5596 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005597 return true;
5598}
5599
Vladimir Marko76649e82014-11-10 18:32:59 +00005600// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005601void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005602 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005603 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005604 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005605 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005606 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005607 // Compute reference offsets unless our superclass overflowed.
5608 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5609 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005610 if (num_reference_fields != 0u) {
5611 // All of the fields that contain object references are guaranteed be grouped in memory
5612 // starting at an appropriately aligned address after super class object data.
5613 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5614 sizeof(mirror::HeapReference<mirror::Object>));
5615 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005616 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005617 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005618 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005619 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005620 reference_offsets |= (0xffffffffu << start_bit) &
5621 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005622 }
5623 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005624 }
5625 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005626 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005627}
5628
Mathieu Chartier590fee92013-09-13 13:46:47 -07005629mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005630 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005631 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005632 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005633 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005634 return resolved;
5635 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005636 uint32_t utf16_length;
5637 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005638 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005639 dex_cache->SetResolvedString(string_idx, string);
5640 return string;
5641}
5642
Mathieu Chartier590fee92013-09-13 13:46:47 -07005643mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005644 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005645 StackHandleScope<2> hs(Thread::Current());
5646 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5647 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005648 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5649}
5650
5651mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005652 Handle<mirror::DexCache> dex_cache,
5653 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005654 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005655 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005656 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005657 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005658 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005659 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005660 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005661 // TODO: we used to throw here if resolved's class loader was not the
5662 // boot class loader. This was to permit different classes with the
5663 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005664 dex_cache->SetResolvedType(type_idx, resolved);
5665 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005666 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005667 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005668 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005669 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005670 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08005671 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005672 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005673 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005674 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005675 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005676 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005677 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005678 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005679 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005680 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005681 return resolved;
5682}
5683
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005684mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005685 Handle<mirror::DexCache> dex_cache,
5686 Handle<mirror::ClassLoader> class_loader,
5687 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005688 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005689 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005690 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005691 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005692 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005693 return resolved;
5694 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005695 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005696 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005697 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005698 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005699 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005700 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005701 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005702 // Scan using method_idx, this saves string compares but will only hit for matching dex
5703 // caches/files.
5704 switch (type) {
5705 case kDirect: // Fall-through.
5706 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005707 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005708 break;
5709 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005710 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005711 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005712 break;
5713 case kSuper: // Fall-through.
5714 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005715 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005716 break;
5717 default:
5718 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005719 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005720 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005721 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005722 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005723 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005724 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005725 switch (type) {
5726 case kDirect: // Fall-through.
5727 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005728 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005729 break;
5730 case kInterface:
5731 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005732 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005733 break;
5734 case kSuper: // Fall-through.
5735 case kVirtual:
5736 resolved = klass->FindVirtualMethod(name, signature);
5737 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005738 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005739 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005740 // If we found a method, check for incompatible class changes.
5741 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005742 // Be a good citizen and update the dex cache to speed subsequent calls.
5743 dex_cache->SetResolvedMethod(method_idx, resolved);
5744 return resolved;
5745 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005746 // If we had a method, it's an incompatible-class-change error.
5747 if (resolved != nullptr) {
5748 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5749 } else {
5750 // We failed to find the method which means either an access error, an incompatible class
5751 // change, or no such method. First try to find the method among direct and virtual methods.
5752 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5753 const Signature signature = dex_file.GetMethodSignature(method_id);
5754 switch (type) {
5755 case kDirect:
5756 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005757 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005758 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5759 // have had a resolved method before, which triggers the "true" branch above.
5760 break;
5761 case kInterface:
5762 case kVirtual:
5763 case kSuper:
5764 resolved = klass->FindDirectMethod(name, signature);
5765 break;
5766 }
5767
5768 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005769 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005770 if (resolved != nullptr && referrer.Get() != nullptr) {
5771 mirror::Class* methods_class = resolved->GetDeclaringClass();
5772 mirror::Class* referring_class = referrer->GetDeclaringClass();
5773 if (!referring_class->CanAccess(methods_class)) {
5774 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5775 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005776 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005777 } else if (!referring_class->CanAccessMember(methods_class,
5778 resolved->GetAccessFlags())) {
5779 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005780 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005781 }
5782 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005783 if (!exception_generated) {
5784 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5785 // interface methods and throw if we find the method there. If we find nothing, throw a
5786 // NoSuchMethodError.
5787 switch (type) {
5788 case kDirect:
5789 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005790 if (resolved != nullptr) {
5791 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5792 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005793 resolved = klass->FindInterfaceMethod(name, signature);
5794 if (resolved != nullptr) {
5795 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5796 } else {
5797 ThrowNoSuchMethodError(type, klass, name, signature);
5798 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005799 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005800 break;
5801 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005802 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005803 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5804 } else {
5805 resolved = klass->FindVirtualMethod(name, signature);
5806 if (resolved != nullptr) {
5807 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5808 } else {
5809 ThrowNoSuchMethodError(type, klass, name, signature);
5810 }
5811 }
5812 break;
5813 case kSuper:
5814 if (resolved != nullptr) {
5815 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005816 } else {
5817 ThrowNoSuchMethodError(type, klass, name, signature);
5818 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005819 break;
5820 case kVirtual:
5821 if (resolved != nullptr) {
5822 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5823 } else {
5824 resolved = klass->FindInterfaceMethod(name, signature);
5825 if (resolved != nullptr) {
5826 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5827 } else {
5828 ThrowNoSuchMethodError(type, klass, name, signature);
5829 }
5830 }
5831 break;
5832 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005833 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005834 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005835 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005836 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005837 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005838}
5839
Mathieu Chartier590fee92013-09-13 13:46:47 -07005840mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005841 Handle<mirror::DexCache> dex_cache,
5842 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005843 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005844 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005845 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005846 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005847 return resolved;
5848 }
5849 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005850 Thread* const self = Thread::Current();
5851 StackHandleScope<1> hs(self);
5852 Handle<mirror::Class> klass(
5853 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005854 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005855 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005856 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005857 }
5858
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005859 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005860 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005861 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005862 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005863 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005864
Andreas Gampe58a5af82014-07-31 16:23:49 -07005865 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005866 const char* name = dex_file.GetFieldName(field_id);
5867 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5868 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005869 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005870 } else {
5871 resolved = klass->FindInstanceField(name, type);
5872 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005873 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005874 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005875 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005876 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005877 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005878 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005879 return resolved;
5880}
5881
Brian Carlstromea46f952013-07-30 01:26:50 -07005882mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005883 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005884 Handle<mirror::DexCache> dex_cache,
5885 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005886 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005887 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005888 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005889 return resolved;
5890 }
5891 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005892 Thread* self = Thread::Current();
5893 StackHandleScope<1> hs(self);
5894 Handle<mirror::Class> klass(
5895 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005896 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005897 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005898 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005899 }
5900
Ian Rogersdfb325e2013-10-30 01:00:44 -07005901 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5902 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005903 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005904 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005905 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005906 dex_cache->SetResolvedField(field_idx, resolved);
5907 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005908 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005909 }
5910 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005911}
5912
Brian Carlstromea46f952013-07-30 01:26:50 -07005913const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005914 uint32_t* length) {
5915 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5916 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005917 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005918 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005919 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005920}
5921
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005922void ClassLinker::DumpAllClasses(int flags) {
5923 if (dex_cache_image_class_lookup_required_) {
5924 MoveImageClassesToClassTable();
5925 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005926 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5927 // 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 -08005928 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005929 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005930 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005931 for (GcRoot<mirror::Class>& it : class_table_) {
5932 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005933 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005934 }
5935
5936 for (size_t i = 0; i < all_classes.size(); ++i) {
5937 all_classes[i]->DumpClass(std::cerr, flags);
5938 }
5939}
5940
Elliott Hughes956af0f2014-12-11 14:34:28 -08005941static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005942 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005943 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5944 base -= sizeof(void*); // Move backward so that code_offset != 0.
5945 const uint32_t code_offset = sizeof(void*);
5946 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005947}
5948
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005949bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5950 return (entry_point == GetQuickResolutionStub()) ||
5951 (quick_resolution_trampoline_ == entry_point);
5952}
5953
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005954bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5955 return (entry_point == GetQuickToInterpreterBridge()) ||
5956 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5957}
5958
5959bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5960 return (entry_point == GetQuickGenericJniStub()) ||
5961 (quick_generic_jni_trampoline_ == entry_point);
5962}
5963
5964const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5965 return GetQuickGenericJniStub();
5966}
5967
Elliott Hughes956af0f2014-12-11 14:34:28 -08005968void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5969 const void* method_code) const {
5970 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005971 oat_method.LinkMethod(method);
5972 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005973}
5974
5975void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5976 if (!method->IsNative()) {
5977 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005978 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5979 } else {
5980 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005981 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005982 oat_method.LinkMethod(method);
5983 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005984 }
5985}
5986
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005987void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005988 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005989 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005990 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005991 MoveImageClassesToClassTable();
5992 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005993 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005994 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5995 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005996}
5997
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005998size_t ClassLinker::NumLoadedClasses() {
5999 if (dex_cache_image_class_lookup_required_) {
6000 MoveImageClassesToClassTable();
6001 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07006002 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006003 // Only return non zygote classes since these are the ones which apps which care about.
6004 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07006005}
6006
Brian Carlstrom47d237a2011-10-18 15:08:33 -07006007pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07006008 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07006009}
6010
6011pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07006012 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07006013}
6014
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08006015void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006016 DCHECK(!init_done_);
6017
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006018 DCHECK(klass != nullptr);
6019 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006020
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07006021 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006022 DCHECK(class_roots != nullptr);
6023 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07006024 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006025}
6026
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006027const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
6028 static const char* class_roots_descriptors[] = {
6029 "Ljava/lang/Class;",
6030 "Ljava/lang/Object;",
6031 "[Ljava/lang/Class;",
6032 "[Ljava/lang/Object;",
6033 "Ljava/lang/String;",
6034 "Ljava/lang/DexCache;",
6035 "Ljava/lang/ref/Reference;",
6036 "Ljava/lang/reflect/ArtField;",
6037 "Ljava/lang/reflect/ArtMethod;",
6038 "Ljava/lang/reflect/Proxy;",
6039 "[Ljava/lang/String;",
6040 "[Ljava/lang/reflect/ArtField;",
6041 "[Ljava/lang/reflect/ArtMethod;",
6042 "Ljava/lang/ClassLoader;",
6043 "Ljava/lang/Throwable;",
6044 "Ljava/lang/ClassNotFoundException;",
6045 "Ljava/lang/StackTraceElement;",
6046 "Z",
6047 "B",
6048 "C",
6049 "D",
6050 "F",
6051 "I",
6052 "J",
6053 "S",
6054 "V",
6055 "[Z",
6056 "[B",
6057 "[C",
6058 "[D",
6059 "[F",
6060 "[I",
6061 "[J",
6062 "[S",
6063 "[Ljava/lang/StackTraceElement;",
6064 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08006065 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
6066 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006067
6068 const char* descriptor = class_roots_descriptors[class_root];
6069 CHECK(descriptor != nullptr);
6070 return descriptor;
6071}
6072
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006073std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
6074 const {
6075 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006076 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006077}
6078
6079bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
6080 const GcRoot<mirror::Class>& b) {
6081 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
6082 return false;
6083 }
6084 std::string temp;
6085 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
6086}
6087
6088std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
6089 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006090 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006091}
6092
6093bool ClassLinker::ClassDescriptorHashEquals::operator()(
6094 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
6095 if (a.Read()->GetClassLoader() != b.second) {
6096 return false;
6097 }
6098 return a.Read()->DescriptorEquals(b.first);
6099}
6100
6101bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
6102 const char* descriptor) {
6103 return a.Read()->DescriptorEquals(descriptor);
6104}
6105
6106std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006107 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006108}
6109
Sebastien Hertz6963e442014-11-26 22:11:27 +01006110bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
6111 // Non-image methods don't use direct code pointer.
6112 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
6113 return false;
6114 }
6115 if (m->IsPrivate()) {
6116 // The method can only be called inside its own oat file. Therefore it won't be called using
6117 // its direct code if the oat file has been compiled in PIC mode.
6118 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
6119 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
6120 const OatFile::OatDexFile* oat_dex_file = class_linker->FindOpenedOatDexFileForDexFile(dex_file);
6121 if (oat_dex_file == nullptr) {
6122 // No oat file: the method has not been compiled.
6123 return false;
6124 }
6125 const OatFile* oat_file = oat_dex_file->GetOatFile();
6126 return oat_file != nullptr && !oat_file->IsPic();
6127 } else {
6128 // The method can be called outside its own oat file. Therefore it won't be called using its
6129 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
6130 ReaderMutexLock mu(Thread::Current(), dex_lock_);
6131 for (const OatFile* oat_file : oat_files_) {
6132 if (!oat_file->IsPic()) {
6133 return true;
6134 }
6135 }
6136 return false;
6137 }
6138}
6139
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006140} // namespace art