blob: 8bf3e4bd0d97086183effe8afec27b3c90eeb001 [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"
Ian Rogers0571d352011-11-03 19:51:38 -070046#include "leb128.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080047#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070048#include "oat_file.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070049#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070050#include "mirror/art_field-inl.h"
51#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/class.h"
53#include "mirror/class-inl.h"
54#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070055#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/object-inl.h"
58#include "mirror/object_array-inl.h"
59#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070060#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070062#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080063#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070064#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070065#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070066#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070067#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070068#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070069#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070070#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080071#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070072#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070073
74namespace art {
75
Ian Rogers00f7d0e2012-07-19 15:28:27 -070076static void ThrowNoClassDefFoundError(const char* fmt, ...)
77 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070078 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070079static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070080 va_list args;
81 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080082 Thread* self = Thread::Current();
83 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
84 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080085 va_end(args);
86}
87
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080088static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070089 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070090 // The class failed to initialize on a previous attempt, so we want to throw
91 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
92 // failed in verification, in which case v2 5.4.1 says we need to re-throw
93 // the previous error.
Ian Rogers7b078e82014-09-10 14:44:24 -070094 Runtime* runtime = Runtime::Current();
95 bool is_compiler = runtime->IsCompiler();
96 if (!is_compiler) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -070097 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
98 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -070099
Elliott Hughes5c599942012-06-13 16:45:05 -0700100 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800101 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700102 if (is_compiler) {
103 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
104 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
105 self->SetException(ThrowLocation(), pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700106 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700107 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
108 if (c->GetVerifyErrorClass() != NULL) {
109 // TODO: change the verifier to store an _instance_, with a useful detail message?
110 std::string temp;
111 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
112 PrettyDescriptor(c).c_str());
113 } else {
114 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
115 PrettyDescriptor(c).c_str());
116 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700117 }
118}
119
Brian Carlstromb23eab12014-10-08 17:55:21 -0700120static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
121 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
122 if (VLOG_IS_ON(class_linker)) {
123 std::string temp;
124 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
125 << klass->GetLocation() << "\n" << Thread::Current()->GetException(nullptr)->Dump();
126 }
127}
128
129static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
130 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700131 Thread* self = Thread::Current();
132 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700133
134 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700135 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700136
137 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700138 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
139 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700140
Elliott Hughesa4f94742012-05-29 16:28:38 -0700141 // We only wrap non-Error exceptions; an Error can just be used as-is.
142 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800143 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700144 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;",
145 nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700146 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700147 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700148}
149
Fred Shih381e4ca2014-08-25 17:24:27 -0700150// Gap between two fields in object layout.
151struct FieldGap {
152 uint32_t start_offset; // The offset from the start of the object.
153 uint32_t size; // The gap size of 1, 2, or 4 bytes.
154};
155struct FieldGapsComparator {
156 explicit FieldGapsComparator() {
157 }
158 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
159 NO_THREAD_SAFETY_ANALYSIS {
160 // Sort by gap size, largest first.
161 return lhs.size > rhs.size;
162 }
163};
164typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
165
166// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800167static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700168 DCHECK(gaps != nullptr);
169
170 uint32_t current_offset = gap_start;
171 while (current_offset != gap_end) {
172 size_t remaining = gap_end - current_offset;
173 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
174 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
175 current_offset += sizeof(uint32_t);
176 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
177 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
178 current_offset += sizeof(uint16_t);
179 } else {
180 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
181 current_offset += sizeof(uint8_t);
182 }
183 DCHECK_LE(current_offset, gap_end) << "Overran gap";
184 }
185}
186// Shuffle fields forward, making use of gaps whenever possible.
187template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000188static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700189 MemberOffset* field_offset,
Fred Shih381e4ca2014-08-25 17:24:27 -0700190 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
191 FieldGaps* gaps)
192 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
193 DCHECK(current_field_idx != nullptr);
194 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700195 DCHECK(gaps != nullptr);
196 DCHECK(field_offset != nullptr);
197
198 DCHECK(IsPowerOfTwo(n));
199 while (!grouped_and_sorted_fields->empty()) {
200 mirror::ArtField* field = grouped_and_sorted_fields->front();
201 Primitive::Type type = field->GetTypeAsPrimitiveType();
202 if (Primitive::ComponentSize(type) < n) {
203 break;
204 }
205 if (!IsAligned<n>(field_offset->Uint32Value())) {
206 MemberOffset old_offset = *field_offset;
207 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
208 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
209 }
210 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
211 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700212 if (!gaps->empty() && gaps->top().size >= n) {
213 FieldGap gap = gaps->top();
214 gaps->pop();
215 DCHECK(IsAligned<n>(gap.start_offset));
216 field->SetOffset(MemberOffset(gap.start_offset));
217 if (gap.size > n) {
218 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
219 }
220 } else {
221 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
222 field->SetOffset(*field_offset);
223 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
224 }
225 ++(*current_field_idx);
226 }
227}
228
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800229ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700230 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700231 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700232 dex_cache_image_class_lookup_required_(false),
233 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800234 class_roots_(nullptr),
235 array_iftable_(nullptr),
236 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700237 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800238 log_new_dex_caches_roots_(false),
239 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700240 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800241 portable_resolution_trampoline_(nullptr),
242 quick_resolution_trampoline_(nullptr),
243 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800244 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100245 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800246 quick_to_interpreter_bridge_trampoline_(nullptr),
247 image_pointer_size_(sizeof(void*)) {
Ian Rogers98379392014-02-24 16:53:16 -0800248 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700249}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700250
Alex Light64ad14d2014-08-19 14:23:13 -0700251void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800252 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700253 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700254
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700255 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700256
Elliott Hughes30646832011-10-13 16:59:46 -0700257 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700258 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700259 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700260 // 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 -0800261 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700262 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
263 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700264 heap->AllocNonMovableObject<true>(self, nullptr,
265 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700266 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700267 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700268 mirror::Class::SetClassClass(java_lang_Class.Get());
269 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700270 if (kUseBakerOrBrooksReadBarrier) {
271 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800272 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700273 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700274 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800275 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800276 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700277
Elliott Hughes418d20f2011-09-22 14:00:39 -0700278 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700279 Handle<mirror::Class> class_array_class(hs.NewHandle(
280 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700281 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700282
Ian Rogers23435d02012-09-24 11:23:12 -0700283 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700284 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
285 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700286 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700287 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700288 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700289 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700290
Ian Rogers23435d02012-09-24 11:23:12 -0700291 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700292 Handle<mirror::Class> object_array_class(hs.NewHandle(
293 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700294 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700295
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700296 // Setup the char (primitive) class to be used for char[].
297 Handle<mirror::Class> char_class(hs.NewHandle(
298 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700299 // The primitive char class won't be initialized by
300 // InitializePrimitiveClass until line 459, but strings (and
301 // internal char arrays) will be allocated before that and the
302 // component size, which is computed from the primitive type, needs
303 // to be set here.
304 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700305
Ian Rogers23435d02012-09-24 11:23:12 -0700306 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700307 Handle<mirror::Class> char_array_class(hs.NewHandle(
308 AllocClass(self, java_lang_Class.Get(),
309 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700310 char_array_class->SetComponentType(char_class.Get());
311 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700312
Ian Rogers23435d02012-09-24 11:23:12 -0700313 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700314 Handle<mirror::Class> java_lang_String(hs.NewHandle(
315 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700316 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700317 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700318 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400319
Fred Shih4ee7a662014-07-11 09:59:27 -0700320 // Setup Reference.
321 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
322 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
323 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
324 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
325 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
326
Ian Rogers23435d02012-09-24 11:23:12 -0700327 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700328 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
329 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
330 kClassRootsMax));
331 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700332 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
333 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
334 SetClassRoot(kClassArrayClass, class_array_class.Get());
335 SetClassRoot(kObjectArrayClass, object_array_class.Get());
336 SetClassRoot(kCharArrayClass, char_array_class.Get());
337 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700338 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700339
340 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700341 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
342 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
343 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
344 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
345 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
346 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
347 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
348 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349
Ian Rogers23435d02012-09-24 11:23:12 -0700350 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700351 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700352
Ian Rogers23435d02012-09-24 11:23:12 -0700353 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700354 Handle<mirror::Class> int_array_class(hs.NewHandle(
355 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700356 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700357 mirror::IntArray::SetArrayClass(int_array_class.Get());
358 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700360 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700361
Ian Rogers52813c92012-10-11 11:50:38 -0700362 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700363 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
364 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700365 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700366 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700367 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700368
Brian Carlstromf3632832014-05-20 15:36:53 -0700369 // Constructor, Field, Method, and AbstractMethod are necessary so
370 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700371 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
372 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700373 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700374 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700375 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700376 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700377 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700378
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700379 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
380 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700381 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800382 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700383 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700384 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700385 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700386
387 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700388 Handle<mirror::Class> object_array_string(hs.NewHandle(
389 AllocClass(self, java_lang_Class.Get(),
390 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700391 object_array_string->SetComponentType(java_lang_String.Get());
392 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700393
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700394 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
395 AllocClass(self, java_lang_Class.Get(),
396 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700397 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
398 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700399
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700400 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
401 AllocClass(self, java_lang_Class.Get(),
402 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700403 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
404 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700405
Ian Rogers23435d02012-09-24 11:23:12 -0700406 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
407 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
408 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700409 CHECK_NE(0U, boot_class_path.size());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800410 for (const DexFile* dex_file : boot_class_path) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700411 CHECK(dex_file != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700412 AppendToBootClassPath(self, *dex_file);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700413 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700414
415 // now we can use FindSystemClass
416
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700417 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700418 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
419 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700420
Jeff Hao88474b42013-10-23 16:24:40 -0700421 // Create runtime resolution and imt conflict methods. Also setup the default imt.
422 Runtime* runtime = Runtime::Current();
423 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
424 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700425 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700426 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
427
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700428 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
429 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700430 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Alex Light64ad14d2014-08-19 14:23:13 -0700431 if (!runtime->IsCompiler()) {
432 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700433 quick_resolution_trampoline_ = GetQuickResolutionStub();
434 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
435 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700436 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700437
Mathieu Chartier66f19252012-09-18 08:57:04 -0700438 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700439 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800440 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700441 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700442 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700443 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800444 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700445 std::ostringstream os1, os2;
446 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
447 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
448 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
449 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700450 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800451 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700452 CHECK_EQ(java_lang_String.Get(), String_class);
453 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700454 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455
Ian Rogers23435d02012-09-24 11:23:12 -0700456 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800457 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800458 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459
Ian Rogers98379392014-02-24 16:53:16 -0800460 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800461 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700462
Ian Rogers98379392014-02-24 16:53:16 -0800463 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700464 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700465
Ian Rogers98379392014-02-24 16:53:16 -0800466 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800467 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700468
Ian Rogers98379392014-02-24 16:53:16 -0800469 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700470 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700471
Ian Rogers98379392014-02-24 16:53:16 -0800472 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800473 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700474
Ian Rogers98379392014-02-24 16:53:16 -0800475 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800476 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700477
Ian Rogers98379392014-02-24 16:53:16 -0800478 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800479 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700480
Ian Rogers98379392014-02-24 16:53:16 -0800481 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700482 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700483
Ian Rogers98379392014-02-24 16:53:16 -0800484 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700485 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700486
Ian Rogers23435d02012-09-24 11:23:12 -0700487 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800488 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700489 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800490 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700491 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700492 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
493 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700494 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700495 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700496 array_iftable->SetInterface(0, java_lang_Cloneable);
497 array_iftable->SetInterface(1, java_io_Serializable);
498 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700499
Ian Rogers23435d02012-09-24 11:23:12 -0700500 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700501 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
502 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
503 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
504 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700505 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700506 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800507 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700508 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700509
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700510 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800511 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700512 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700513
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700514 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800515 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700516 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700517
Brian Carlstromf3632832014-05-20 15:36:53 -0700518 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700519 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700520 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700521
Brian Carlstromea46f952013-07-30 01:26:50 -0700522 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700523 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700524 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700525
Brian Carlstromea46f952013-07-30 01:26:50 -0700526 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700527 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700528 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700529
Ian Rogers23435d02012-09-24 11:23:12 -0700530 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700531
Ian Rogers23435d02012-09-24 11:23:12 -0700532 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800533 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700534 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
535
Brian Carlstrom1f870082011-08-23 16:02:11 -0700536 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700537 // finish initializing Reference class
538 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
539 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
540 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
541 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
542 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700543 mirror::Class* java_lang_ref_FinalizerReference =
544 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700545 java_lang_ref_FinalizerReference->SetAccessFlags(
546 java_lang_ref_FinalizerReference->GetAccessFlags() |
547 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700548 mirror::Class* java_lang_ref_PhantomReference =
549 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700550 java_lang_ref_PhantomReference->SetAccessFlags(
551 java_lang_ref_PhantomReference->GetAccessFlags() |
552 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700553 mirror::Class* java_lang_ref_SoftReference =
554 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700555 java_lang_ref_SoftReference->SetAccessFlags(
556 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700557 mirror::Class* java_lang_ref_WeakReference =
558 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559 java_lang_ref_WeakReference->SetAccessFlags(
560 java_lang_ref_WeakReference->GetAccessFlags() |
561 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700562
Ian Rogers23435d02012-09-24 11:23:12 -0700563 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800564 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700565 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700566 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
567
jeffhao8cd6dda2012-02-22 10:15:34 -0800568 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700569 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800570 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800571 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700572 SetClassRoot(kJavaLangClassNotFoundException,
573 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800574 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700575 SetClassRoot(kJavaLangStackTraceElementArrayClass,
576 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800577 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700578
Andreas Gampe76bd8802014-12-10 16:43:58 -0800579 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
580 // initialized.
581 {
582 const DexFile& dex_file = java_lang_Object->GetDexFile();
583 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
584 CHECK(void_string_id != nullptr);
585 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
586 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
587 CHECK(void_type_id != nullptr);
588 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
589 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
590 // as referrer so the used dex cache is core's one.
591 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
592 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
593 self->AssertNoPendingException();
594 }
595
Ian Rogers98379392014-02-24 16:53:16 -0800596 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700597
Brian Carlstroma004aa92012-02-08 18:05:09 -0800598 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700599}
600
Ian Rogers98379392014-02-24 16:53:16 -0800601void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800602 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700603
604 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700605 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700606 // as the types of the field can't be resolved prior to the runtime being
607 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800608 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700609 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800610 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800611
Brian Carlstromea46f952013-07-30 01:26:50 -0700612 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700613 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
614 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700615
Brian Carlstromea46f952013-07-30 01:26:50 -0700616 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700617 CHECK_STREQ(queue->GetName(), "queue");
618 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700619
Brian Carlstromea46f952013-07-30 01:26:50 -0700620 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700621 CHECK_STREQ(queueNext->GetName(), "queueNext");
622 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700623
Brian Carlstromea46f952013-07-30 01:26:50 -0700624 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700625 CHECK_STREQ(referent->GetName(), "referent");
626 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700627
Brian Carlstromea46f952013-07-30 01:26:50 -0700628 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700629 CHECK_STREQ(zombie->GetName(), "zombie");
630 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700631
Brian Carlstroma663ea52011-08-19 23:33:41 -0700632 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700633 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700634 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800635 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700636 CHECK(klass != nullptr);
637 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700638 // note SetClassRoot does additional validation.
639 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700640 }
641
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700642 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700643
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700644 // disable the slow paths in FindClass and CreatePrimitiveClass now
645 // that Object, Class, and Object[] are setup
646 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700647
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800648 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700649}
650
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700651void ClassLinker::RunRootClinits() {
652 Thread* self = Thread::Current();
653 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800654 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700655 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700656 StackHandleScope<1> hs(self);
657 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700658 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700659 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700660 }
661 }
662}
663
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700664bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800665 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000666 const char* oat_cache_filename,
667 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700668 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700669 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800670
Ian Rogers1d54e732013-05-02 21:10:01 -0700671 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800672 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700673 if (heap->GetImageSpace() == nullptr) {
674 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
675 // out of space anyway it might not matter.
676 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
677 "without an image.", dex_filename);
678 return false;
679 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700680 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800681
Brian Carlstrom6449c622014-02-10 23:48:36 -0800682 std::string dex_file_option("--dex-file=");
683 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800684
Brian Carlstrom6449c622014-02-10 23:48:36 -0800685 std::string oat_fd_option("--oat-fd=");
686 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800687
Brian Carlstrom6449c622014-02-10 23:48:36 -0800688 std::string oat_location_option("--oat-location=");
689 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800690
Brian Carlstrom6449c622014-02-10 23:48:36 -0800691 std::vector<std::string> argv;
692 argv.push_back(dex2oat);
693 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800694 argv.push_back("-classpath");
695 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800696 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800697
Ian Rogers8afeb852014-04-02 14:55:49 -0700698 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800699
Jeff Hao4a200f52014-04-01 14:58:49 -0700700 if (!Runtime::Current()->IsVerificationEnabled()) {
701 argv.push_back("--compiler-filter=verify-none");
702 }
703
Alex Light6e183f22014-07-18 14:57:04 -0700704 if (Runtime::Current()->MustRelocateIfPossible()) {
705 argv.push_back("--runtime-arg");
706 argv.push_back("-Xrelocate");
707 } else {
708 argv.push_back("--runtime-arg");
709 argv.push_back("-Xnorelocate");
710 }
711
Brian Carlstrom6449c622014-02-10 23:48:36 -0800712 if (!kIsTargetBuild) {
713 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700714 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700715
Brian Carlstrom6449c622014-02-10 23:48:36 -0800716 argv.push_back(boot_image_option);
717 argv.push_back(dex_file_option);
718 argv.push_back(oat_fd_option);
719 argv.push_back(oat_location_option);
720 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800721 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800722 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700723 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800724
Andreas Gampea696c0a2014-12-10 20:51:45 -0800725 if (!Exec(argv, error_msg)) {
726 // Manually delete the file. Ensures there is no garbage left over if the process unexpectedly
727 // died. Ignore unlink failure, propagate the original error.
728 TEMP_FAILURE_RETRY(unlink(oat_cache_filename));
729 return false;
730 }
731
732 return true;
jeffhao262bf462011-10-20 18:36:32 -0700733}
734
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700735const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700736 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800737 if (kIsDebugBuild) {
738 for (size_t i = 0; i < oat_files_.size(); ++i) {
739 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700740 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800741 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700742 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
743 oat_files_.push_back(oat_file);
744 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800745}
746
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700747OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
748 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700749 OatFile* oat_file = space->ReleaseOatFile();
750 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700751 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700752 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700753}
754
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100755const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800756 const char* dex_location = dex_file.GetLocation().c_str();
757 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100758 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800759}
760
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100761const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
762 const char* dex_location,
763 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700764 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100765 for (const OatFile* oat_file : oat_files_) {
766 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700767
768 if (oat_location != nullptr) {
769 if (oat_file->GetLocation() != oat_location) {
770 continue;
771 }
772 }
773
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700774 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800775 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700776 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100777 if (oat_dex_file != nullptr) {
778 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800779 }
780 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100781 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800782}
783
Calin Juravle621962a2014-09-02 15:53:55 +0100784
785// Loads all multi dex files from the given oat file returning true on success.
786//
787// Parameters:
788// oat_file - the oat file to load from
789// dex_location - the dex location used to generate the oat file
790// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
791// generated - whether or not the oat_file existed before or was just (re)generated
792// error_msgs - any error messages will be appended here
793// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
794static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
795 const char* dex_location,
796 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700797 bool generated,
798 std::vector<std::string>* error_msgs,
799 std::vector<const DexFile*>* dex_files) {
800 if (oat_file == nullptr) {
801 return false;
802 }
803
804 size_t old_size = dex_files->size(); // To rollback on error.
805
806 bool success = true;
807 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100808 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700809 const char* next_name = next_name_str.c_str();
810
Calin Juravle621962a2014-09-02 15:53:55 +0100811 uint32_t next_location_checksum;
812 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700813 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100814 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
815 // When i=0 the multidex name should be the same as the location name. We already have the
816 // checksum it so we don't need to recompute it.
817 if (dex_location_checksum == nullptr) {
818 next_location_checksum_pointer = nullptr;
819 } else {
820 next_location_checksum = *dex_location_checksum;
821 }
822 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700823 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100824 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700825 }
826
827 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
828
829 if (oat_dex_file == nullptr) {
830 if (i == 0 && generated) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700831 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100832 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700833 oat_file->GetLocation().c_str());
834 error_msgs->push_back(error_msg);
835 }
836 break; // Not found, done.
837 }
838
839 // Checksum test. Test must succeed when generated.
840 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100841 if (next_location_checksum_pointer != nullptr) {
842 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700843 }
844
845 if (success) {
846 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
847 if (dex_file == nullptr) {
848 success = false;
849 error_msgs->push_back(error_msg);
850 } else {
851 dex_files->push_back(dex_file);
852 }
853 }
854
855 // When we generated the file, we expect success, or something is terribly wrong.
856 CHECK_EQ(false, generated && !success)
857 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100858 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700859 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
860 }
861
862 if (dex_files->size() == old_size) {
863 success = false; // We did not even find classes.dex
864 }
865
866 if (success) {
867 return true;
868 } else {
869 // Free all the dex files we have loaded.
870 auto it = dex_files->begin() + old_size;
871 auto it_end = dex_files->end();
872 for (; it != it_end; it++) {
873 delete *it;
874 }
875 dex_files->erase(dex_files->begin() + old_size, it_end);
876
877 return false;
878 }
879}
880
881// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
882// complicates the loading process, as we should not use an iterative loading process, because that
883// would register the oat file and dex files that come before the broken one. Instead, check all
884// multidex ahead of time.
885bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
886 std::vector<std::string>* error_msgs,
887 std::vector<const DexFile*>* dex_files) {
888 // 1) Check whether we have an open oat file.
889 // This requires a dex checksum, use the "primary" one.
890 uint32_t dex_location_checksum;
891 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
892 bool have_checksum = true;
893 std::string checksum_error_msg;
894 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100895 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700896 dex_location_checksum_pointer = nullptr;
897 have_checksum = false;
898 }
899
900 bool needs_registering = false;
901
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100902 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
903 dex_location_checksum_pointer);
904 std::unique_ptr<const OatFile> open_oat_file(
905 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700906
907 // 2) If we do not have an open one, maybe there's one on disk already.
908
909 // In case the oat file is not open, we play a locking game here so
910 // that if two different processes race to load and register or generate
911 // (or worse, one tries to open a partial generated file) we will be okay.
912 // This is actually common with apps that use DexClassLoader to work
913 // around the dex method reference limit and that have a background
914 // service running in a separate process.
915 ScopedFlock scoped_flock;
916
917 if (open_oat_file.get() == nullptr) {
918 if (oat_location != nullptr) {
919 // Can only do this if we have a checksum, else error.
920 if (!have_checksum) {
921 error_msgs->push_back(checksum_error_msg);
922 return false;
923 }
924
925 std::string error_msg;
926
927 // We are loading or creating one in the future. Time to set up the file lock.
928 if (!scoped_flock.Init(oat_location, &error_msg)) {
929 error_msgs->push_back(error_msg);
930 return false;
931 }
932
Alex Lighta59dd802014-07-02 16:28:08 -0700933 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700934 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
935 oat_location, &error_msg));
936
937 if (open_oat_file.get() == nullptr) {
938 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
939 dex_location, oat_location, error_msg.c_str());
940 VLOG(class_linker) << compound_msg;
941 error_msgs->push_back(compound_msg);
942 }
943 } else {
944 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100945 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700946 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
947 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100948 kRuntimeISA, error_msgs,
949 &obsolete_file_cleanup_failed));
950 // There's no point in going forward and eventually try to regenerate the
951 // file if we couldn't remove the obsolete one. Mostly likely we will fail
952 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100953 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
954 if (obsolete_file_cleanup_failed) {
955 return false;
956 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700957 }
958 needs_registering = true;
959 }
960
961 // 3) If we have an oat file, check all contained multidex files for our dex_location.
962 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100963 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
964 dex_location_checksum_pointer,
965 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700966 if (success) {
967 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
968 if (needs_registering) {
969 // We opened the oat file, so we must register it.
970 RegisterOatFile(oat_file);
971 }
Alex Light9dcc4572014-08-14 14:16:26 -0700972 // If the file isn't executable we failed patchoat but did manage to get the dex files.
973 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700974 } else {
975 if (needs_registering) {
976 // We opened it, delete it.
977 open_oat_file.reset();
978 } else {
979 open_oat_file.release(); // Do not delete open oat files.
980 }
981 }
982
983 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
984
985 // Need a checksum, fail else.
986 if (!have_checksum) {
987 error_msgs->push_back(checksum_error_msg);
988 return false;
989 }
990
991 // Look in cache location if no oat_location is given.
992 std::string cache_location;
993 if (oat_location == nullptr) {
994 // Use the dalvik cache.
995 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
996 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
997 oat_location = cache_location.c_str();
998 }
999
Alex Light64ad14d2014-08-19 14:23:13 -07001000 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -07001001 // Definitely need to lock now.
1002 if (!scoped_flock.HasFile()) {
1003 std::string error_msg;
1004 if (!scoped_flock.Init(oat_location, &error_msg)) {
1005 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -07001006 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -07001007 }
1008 }
1009
Alex Light64ad14d2014-08-19 14:23:13 -07001010 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001011 // Create the oat file.
1012 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1013 oat_location, error_msgs));
1014 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001015
1016 // Failed, bail.
1017 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001018 std::string error_msg;
1019 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1020 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1021 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001022 return false;
1023 }
1024
1025 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001026 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1027 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001028 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001029 if (success) {
1030 RegisterOatFile(open_oat_file.release());
1031 return true;
1032 } else {
1033 return false;
1034 }
1035}
1036
1037const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1038 uint32_t dex_location_checksum,
1039 const char* oat_location,
1040 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001041 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001042 !Runtime::Current()->IsCompiler(),
1043 error_msg));
1044 if (oat_file.get() == nullptr) {
1045 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1046 error_msg->c_str());
1047 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001048 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001049 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001050 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1051 if (image_space != nullptr) {
1052 const ImageHeader& image_header = image_space->GetImageHeader();
1053 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1054 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1055 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1056 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1057 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1058 actual_image_oat_checksum);
1059 return nullptr;
1060 }
1061
1062 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1063 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1064 if (expected_image_oat_offset != actual_image_oat_offset) {
1065 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1066 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1067 actual_image_oat_offset);
1068 return nullptr;
1069 }
1070 int32_t expected_patch_delta = image_header.GetPatchDelta();
1071 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1072 if (expected_patch_delta != actual_patch_delta) {
1073 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1074 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1075 return nullptr;
1076 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001077 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001078
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001079 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1080 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001081 if (oat_dex_file == nullptr) {
1082 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1083 dex_location);
1084 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001085 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001086 uint32_t expected_dex_checksum = dex_location_checksum;
1087 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1088 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001089 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1090 "found 0x%x", oat_location, expected_dex_checksum,
1091 actual_dex_checksum);
1092 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001093 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001094 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1095 if (dex_file.get() != nullptr) {
1096 return oat_file.release();
1097 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001098 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001099 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001100}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001101
Andreas Gampe833a4852014-05-21 18:46:59 -07001102const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1103 int fd, const char* oat_location,
1104 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001105 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001106 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001107 std::string error_msg;
1108 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001109 CHECK(!error_msg.empty());
1110 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001111 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001112 }
Igor Murashkin46774762014-10-22 11:37:02 -07001113 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001114 !Runtime::Current()->IsCompiler(),
1115 &error_msg));
1116 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001117 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1118 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001119 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001120 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001121 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001122
1123 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001124}
1125
Alex Light6e183f22014-07-18 14:57:04 -07001126bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1127 const InstructionSet instruction_set) {
1128 Runtime* runtime = Runtime::Current();
1129 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001130 if (image_space == nullptr) {
1131 return false;
1132 }
Alex Light6e183f22014-07-18 14:57:04 -07001133 uint32_t image_oat_checksum = 0;
1134 if (instruction_set == kRuntimeISA) {
1135 const ImageHeader& image_header = image_space->GetImageHeader();
1136 image_oat_checksum = image_header.GetOatChecksum();
1137 } else {
1138 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1139 image_space->GetImageLocation().c_str(), instruction_set));
1140 image_oat_checksum = image_header->GetOatChecksum();
1141 }
1142 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1143}
1144
1145bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1146 const InstructionSet instruction_set,
1147 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001148 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001149 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001150 if (image_space == nullptr) {
1151 *error_msg = "No image space for verification against";
1152 return false;
1153 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001154
1155 // If the requested instruction set is the same as the current runtime,
1156 // we can use the checksums directly. If it isn't, we'll have to read the
1157 // image header from the image for the right instruction set.
1158 uint32_t image_oat_checksum = 0;
1159 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001160 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001161 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001162 const ImageHeader& image_header = image_space->GetImageHeader();
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 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001167 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001168 image_space->GetImageLocation().c_str(), instruction_set));
1169 image_oat_checksum = image_header->GetOatChecksum();
1170 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001171 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001172 }
1173 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin96e83932014-10-29 19:45:42 -07001174 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1175
1176 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1177 if (!oat_file->IsPic()) {
1178 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1179 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1180 }
Alex Light6e183f22014-07-18 14:57:04 -07001181 if (!ret) {
1182 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1183 oat_file->GetLocation().c_str(),
1184 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1185 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1186 oat_file->GetOatHeader().GetImagePatchDelta(),
1187 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1188 }
1189 return ret;
1190}
1191
1192bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1193 const char* dex_location,
1194 uint32_t dex_location_checksum,
1195 const InstructionSet instruction_set,
1196 std::string* error_msg) {
1197 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1198 return false;
1199 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001200
Brian Carlstromf3632832014-05-20 15:36:53 -07001201 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1202 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001203 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001204 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1205 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001206 for (const OatFile::OatDexFile* oat_dex_file_in : oat_file->GetOatDexFiles()) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001207 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001208 oat_file->GetLocation().c_str(),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001209 oat_dex_file_in->GetDexFileLocation().c_str(),
1210 oat_dex_file_in->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001211 }
1212 return false;
1213 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001214
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001215 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001216 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001217}
1218
Alex Lighta59dd802014-07-02 16:28:08 -07001219bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1220 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001221 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001222 std::string* error_msg) {
1223 CHECK(oat_file != nullptr);
1224 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001225 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001226 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001227 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1228 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1229 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001230 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001231 if (oat_dex_file == nullptr) {
1232 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001233 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001234 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001235 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001236 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001237 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001238 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001239 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001240 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001241 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001242 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001243 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001244 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001245 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001246 }
Alex Lighta59dd802014-07-02 16:28:08 -07001247 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001248}
1249
Andreas Gampe833a4852014-05-21 18:46:59 -07001250const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001251 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001252 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001253 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001254 std::vector<std::string>* error_msgs,
1255 bool* obsolete_file_cleanup_failed) {
1256 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001257 bool already_opened = false;
1258 std::string dex_location_str(dex_location);
1259 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1260 &already_opened,
1261 obsolete_file_cleanup_failed,
1262 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001263 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001264 if (oat_file.get() == nullptr) {
1265 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1266 dex_location));
1267 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001268 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001269 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1270 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001271 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1272 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001273 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001274 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001275 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001276 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001277 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1278 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1279 "dex location '%s'. Image checksum incorrect.",
1280 oat_file->GetLocation().c_str(), dex_location));
1281 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001282 } else {
1283 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001284 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001285}
1286
Brian Carlstromae826982011-11-09 01:33:42 -08001287const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001288 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001289 for (size_t i = 0; i < oat_files_.size(); i++) {
1290 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001291 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001292 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001293 return oat_file;
1294 }
1295 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001296 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001297}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001298
Alex Lighta59dd802014-07-02 16:28:08 -07001299const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1300 InstructionSet isa,
1301 bool *already_opened,
1302 bool *obsolete_file_cleanup_failed,
1303 std::vector<std::string>* error_msgs) {
1304 // Find out if we've already opened the file
1305 const OatFile* ret = nullptr;
1306 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1307 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1308 if (ret != nullptr) {
1309 *already_opened = true;
1310 return ret;
1311 }
1312
1313 std::string dalvik_cache;
1314 bool have_android_data = false;
1315 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001316 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001317 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001318 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001319 std::string cache_filename;
1320 if (have_dalvik_cache) {
1321 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1322 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1323 if (ret != nullptr) {
1324 *already_opened = true;
1325 return ret;
1326 }
1327 } else {
1328 // If we need to relocate we should just place odex back where it started.
1329 cache_filename = odex_filename;
1330 }
1331
1332 ret = nullptr;
1333
1334 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1335 //
1336 // Now we do the following:
1337 // 1) Try and open the odex version
1338 // 2) If present, checksum-verified & relocated correctly return it
1339 // 3) Close the odex version to free up its address space.
1340 // 4) Try and open the cache version
1341 // 5) If present, checksum-verified & relocated correctly return it
1342 // 6) Close the cache version to free up its address space.
1343 // 7) If we should relocate:
1344 // a) If we have opened and checksum-verified the odex version relocate it to
1345 // 'cache_filename' and return it
1346 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1347 // it. This should not happen often (I think only the run-test's will hit this case).
1348 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1349 // this point.
1350 // 9) Return nullptr
1351
1352 *already_opened = false;
1353 const Runtime* runtime = Runtime::Current();
1354 CHECK(runtime != nullptr);
1355 bool executable = !runtime->IsCompiler();
1356
1357 std::string odex_error_msg;
1358 bool should_patch_system = false;
1359 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001360 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001361 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001362 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001363 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001364 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001365 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001366 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001367 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001368 &odex_checksum_verified,
1369 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001370 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001371 } else {
1372 if (odex_checksum_verified) {
1373 // We can just relocate
1374 should_patch_system = true;
1375 odex_error_msg = "Image Patches are incorrect";
1376 }
1377 if (odex_oat_file.get() != nullptr) {
1378 have_system_odex = true;
1379 }
Alex Lighta59dd802014-07-02 16:28:08 -07001380 }
1381 }
1382
Alex Lighta59dd802014-07-02 16:28:08 -07001383 std::string cache_error_msg;
1384 bool should_patch_cache = false;
1385 bool cache_checksum_verified = false;
1386 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001387 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001388 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001389 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001390 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001391 &cache_checksum_verified,
1392 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001393 return cache_oat_file.release();
1394 } else if (cache_checksum_verified) {
1395 // We can just relocate
1396 should_patch_cache = true;
1397 cache_error_msg = "Image Patches are incorrect";
1398 }
1399 } else if (have_android_data) {
1400 // dalvik_cache does not exist but android data does. This means we should be able to create
1401 // it, so we should try.
1402 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1403 }
1404
1405 ret = nullptr;
1406 std::string error_msg;
1407 if (runtime->CanRelocate()) {
1408 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001409 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1410 if (space != nullptr) {
1411 const std::string& image_location = space->GetImageLocation();
1412 if (odex_checksum_verified && should_patch_system) {
1413 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1414 } else if (cache_checksum_verified && should_patch_cache) {
1415 CHECK(have_dalvik_cache);
1416 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1417 }
Alex Light84d76052014-08-22 17:49:35 -07001418 } else if (have_system_odex) {
1419 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001420 }
1421 }
1422 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1423 // implicitly: were able to fine where the cached version is but we were unable to use it,
1424 // either as a destination for relocation or to open a file. We should delete it if it is
1425 // there.
1426 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1427 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1428 "searching for dex file %s: %s",
1429 cache_filename.c_str(), dex_location.c_str(),
1430 strerror(errno));
1431 error_msgs->push_back(rm_error_msg);
1432 VLOG(class_linker) << rm_error_msg;
1433 // Let the caller know that we couldn't remove the obsolete file.
1434 // This is a good indication that further writes may fail as well.
1435 *obsolete_file_cleanup_failed = true;
1436 }
1437 }
1438 if (ret == nullptr) {
1439 VLOG(class_linker) << error_msg;
1440 error_msgs->push_back(error_msg);
1441 std::string relocation_msg;
1442 if (runtime->CanRelocate()) {
1443 relocation_msg = StringPrintf(" and relocation failed");
1444 }
1445 if (have_dalvik_cache && cache_checksum_verified) {
1446 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1447 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1448 cache_filename.c_str(), cache_error_msg.c_str(),
1449 relocation_msg.c_str());
1450 } else {
1451 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1452 "dalvik_cache availible)%s.", odex_filename.c_str(),
1453 odex_error_msg.c_str(), relocation_msg.c_str());
1454 }
1455 VLOG(class_linker) << error_msg;
1456 error_msgs->push_back(error_msg);
1457 }
1458 return ret;
1459}
1460
Alex Light9dcc4572014-08-14 14:16:26 -07001461const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1462 InstructionSet isa,
1463 std::string* error_msg) {
1464 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001465 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001466 if (output.get() == nullptr) {
1467 return nullptr;
1468 }
Alex Light84d76052014-08-22 17:49:35 -07001469 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1470 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001471 return output.release();
1472 } else {
1473 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1474 oat_path.c_str());
1475 return nullptr;
1476 }
1477}
1478
Alex Lighta59dd802014-07-02 16:28:08 -07001479const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1480 const std::string& output_oat,
1481 const std::string& image_location,
1482 InstructionSet isa,
1483 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001484 Runtime* runtime = Runtime::Current();
1485 DCHECK(runtime != nullptr);
1486 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001487 // We don't have an image space so there is no point in trying to patchoat.
1488 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1489 << "running without an image. Attempting to use oat file for interpretation.";
1490 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1491 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001492 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001493 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1494 // input_oat but make sure we only do interpretation on it's dex files.
1495 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1496 << "disabled. Attempting to use oat file for interpretation";
1497 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1498 }
Alex Lighta59dd802014-07-02 16:28:08 -07001499 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001500 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001501
1502 std::string isa_arg("--instruction-set=");
1503 isa_arg += GetInstructionSetString(isa);
1504 std::string input_oat_filename_arg("--input-oat-file=");
1505 input_oat_filename_arg += input_oat;
1506 std::string output_oat_filename_arg("--output-oat-file=");
1507 output_oat_filename_arg += output_oat;
1508 std::string patched_image_arg("--patched-image-location=");
1509 patched_image_arg += image_location;
1510
1511 std::vector<std::string> argv;
1512 argv.push_back(patchoat);
1513 argv.push_back(isa_arg);
1514 argv.push_back(input_oat_filename_arg);
1515 argv.push_back(output_oat_filename_arg);
1516 argv.push_back(patched_image_arg);
1517
1518 std::string command_line(Join(argv, ' '));
1519 LOG(INFO) << "Relocate Oat File: " << command_line;
1520 bool success = Exec(argv, error_msg);
1521 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001522 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gampe7ba64962014-10-23 11:37:40 -07001523 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001524 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001525 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1526 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001527 return output.release();
1528 } else if (output.get() != nullptr) {
1529 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1530 "but output file '%s' failed verifcation: %s",
1531 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1532 } else {
1533 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1534 "but was unable to open output file '%s': %s",
1535 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1536 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001537 } else if (!runtime->IsCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001538 // patchoat failed which means we probably don't have enough room to place the output oat file,
1539 // instead of failing we should just run the interpreter from the dex files in the input oat.
1540 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1541 << "for interpretation. patchoat failure was: " << *error_msg;
1542 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001543 } else {
1544 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1545 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1546 error_msg->c_str());
1547 }
1548 return nullptr;
1549}
1550
Andreas Gampe7ba64962014-10-23 11:37:40 -07001551bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001552 bool* checksum_verified,
1553 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001554 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001555 if (image_space == nullptr) {
1556 *error_msg = "No image space present";
1557 return false;
1558 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001559 uint32_t real_image_checksum;
1560 void* real_image_oat_offset;
1561 int32_t real_patch_delta;
1562 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001563 const ImageHeader& image_header = image_space->GetImageHeader();
1564 real_image_checksum = image_header.GetOatChecksum();
1565 real_image_oat_offset = image_header.GetOatDataBegin();
1566 real_patch_delta = image_header.GetPatchDelta();
1567 } else {
1568 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1569 image_space->GetImageLocation().c_str(), isa));
1570 real_image_checksum = image_header->GetOatChecksum();
1571 real_image_oat_offset = image_header->GetOatDataBegin();
1572 real_patch_delta = image_header->GetPatchDelta();
1573 }
1574
1575 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001576 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001577
1578 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1579 *checksum_verified = oat_image_checksum == real_image_checksum;
1580 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001581 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1582 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001583 }
1584
Andreas Gampe7ba64962014-10-23 11:37:40 -07001585 bool offset_verified;
1586 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001587
Andreas Gampe7ba64962014-10-23 11:37:40 -07001588 if (!oat_file->IsPic()) {
1589 // If an oat file is not PIC, we need to check that the image is at the expected location and
1590 // patched in the same way.
1591 void* oat_image_oat_offset =
1592 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1593 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1594 if (!offset_verified) {
1595 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1596 real_image_oat_offset, oat_image_oat_offset);
1597 }
1598
1599 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1600 patch_delta_verified = oat_patch_delta == real_patch_delta;
1601 if (!patch_delta_verified) {
1602 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1603 "received 0x%x)", real_patch_delta, oat_patch_delta);
1604 }
1605 } else {
1606 // If an oat file is PIC, we ignore offset and patching delta.
1607 offset_verified = true;
1608 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001609 }
1610
1611 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001612 if (!ret) {
1613 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001614 }
1615 return ret;
1616}
1617
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001618const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1619 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001620 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001621 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001622 return oat_file;
1623 }
1624
Igor Murashkin46774762014-10-22 11:37:02 -07001625 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001626 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001627}
1628
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001629void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001630 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001631 DCHECK(obj != nullptr);
1632 DCHECK(class_linker != nullptr);
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001633 size_t pointer_size = class_linker->image_pointer_size_;
Ian Rogers848871b2013-08-05 10:56:33 -07001634
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001635 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001636 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001637 if (!method->IsNative()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001638 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001639 if (method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001640 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1641 pointer_size);
1642 method->SetEntryPointFromPortableCompiledCodePtrSize(GetPortableToInterpreterBridge(),
1643 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001644 }
1645 }
1646 }
1647}
1648
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001649void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001650 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001651 CHECK(!init_done_);
1652
Mathieu Chartier590fee92013-09-13 13:46:47 -07001653 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001654 gc::Heap* heap = Runtime::Current()->GetHeap();
1655 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001656 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001657 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001658 OatFile& oat_file = GetImageOatFile(space);
1659 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1660 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001661 const char* image_file_location = oat_file.GetOatHeader().
1662 GetStoreValueByKey(OatHeader::kImageLocationKey);
1663 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001664 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1665 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001666 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1667 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001668 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001669 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001670 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1671 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1672 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001673
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001674 StackHandleScope<1> hs(self);
1675 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1676 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1677 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001678 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001679
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001680 // Special case of setting up the String class early so that we can test arbitrary objects
1681 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001682 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001683
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001684 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001685 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001686 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001687 StackHandleScope<1> hs2(self);
1688 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001689 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001690 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1691 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001692 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001693 std::string error_msg;
1694 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001695 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001696 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001697 << " from within oat file " << oat_file.GetLocation()
1698 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -08001699 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001700 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001701
1702 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1703
1704 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001705 }
1706
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001707 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1708 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001709 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001710 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
1711 if (!Runtime::Current()->IsCompiler()) {
1712 // Compiler supports having an image with a different pointer size than the runtime. This
1713 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
1714 // also use 32 bit dex2oat on a system with 64 bit apps.
1715 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
1716 << sizeof(void*);
1717 }
1718 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
1719 image_pointer_size_ = 4;
1720 } else {
1721 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
1722 image_pointer_size_ = 8;
1723 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001724
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001725 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001726 Runtime* runtime = Runtime::Current();
1727 if (!runtime->IsCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001728 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001729 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001730 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001731
1732 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001733 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001734 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001735
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001736 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001737 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001738 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001739 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001740 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001741 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001742 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1743 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1744 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1745 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1746 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1747 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1748 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1749 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1750 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1751 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001752
Ian Rogers98379392014-02-24 16:53:16 -08001753 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001754
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001755 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001756}
1757
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001758void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1759 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1760 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001761 for (GcRoot<mirror::Class>& root : class_table_) {
1762 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1763 }
1764 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1765 root.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001766 }
1767 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001768 for (auto& root : new_class_roots_) {
1769 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
1770 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1771 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001772 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001773 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1774 // corresponding object. This is slow, but luckily for us, this may only happen with a
1775 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001776 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
1777 class_table_.Erase(it);
1778 class_table_.Insert(GcRoot<mirror::Class>(new_ref));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001779 }
1780 }
1781 }
1782 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1783 new_class_roots_.clear();
1784 }
1785 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1786 log_new_class_table_roots_ = true;
1787 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1788 log_new_class_table_roots_ = false;
1789 }
1790 // We deliberately ignore the class roots in the image since we
1791 // handle image roots by using the MS/CMS rescanning of dirty cards.
1792}
1793
Brian Carlstroma663ea52011-08-19 23:33:41 -07001794// Keep in sync with InitCallback. Anything we visit, we need to
1795// reinit references to when reinitializing a ClassLinker from a
1796// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001797void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001798 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001799 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001800 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001801 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001802 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001803 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1804 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001805 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001806 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1807 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001808 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001809 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001810 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001811 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1812 new_dex_cache_roots_.clear();
1813 }
1814 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1815 log_new_dex_caches_roots_ = true;
1816 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1817 log_new_dex_caches_roots_ = false;
1818 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001819 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001820 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001821 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1822 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001823 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001824 if (!find_array_class_cache_[i].IsNull()) {
1825 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001826 }
1827 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001828}
1829
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001830void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1831 if (dex_cache_image_class_lookup_required_) {
1832 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001833 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001834 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001835 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001836 for (GcRoot<mirror::Class>& root : class_table_) {
1837 if (!visitor(root.Read(), arg)) {
1838 return;
1839 }
1840 }
1841 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1842 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001843 return;
1844 }
1845 }
1846}
1847
Ian Rogersdbf3be02014-08-29 15:40:08 -07001848static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001849 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001850 classes->insert(c);
1851 return true;
1852}
1853
Ian Rogersdbf3be02014-08-29 15:40:08 -07001854struct GetClassesVisitorArrayArg {
1855 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1856 int32_t index;
1857 bool success;
1858};
1859
1860static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1861 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1862 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1863 if (arg->index < (*arg->classes)->GetLength()) {
1864 (*arg->classes)->Set(arg->index, c);
1865 arg->index++;
1866 return true;
1867 } else {
1868 arg->success = false;
1869 return false;
1870 }
1871}
1872
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001873void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001874 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1875 // is avoiding duplicates.
1876 if (!kMovingClasses) {
1877 std::set<mirror::Class*> classes;
1878 VisitClasses(GetClassesVisitorSet, &classes);
1879 for (mirror::Class* klass : classes) {
1880 if (!visitor(klass, arg)) {
1881 return;
1882 }
1883 }
1884 } else {
1885 Thread* self = Thread::Current();
1886 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001887 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001888 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1889 GetClassesVisitorArrayArg local_arg;
1890 local_arg.classes = &classes;
1891 local_arg.success = false;
1892 // We size the array assuming classes won't be added to the class table during the visit.
1893 // If this assumption fails we iterate again.
1894 while (!local_arg.success) {
1895 size_t class_table_size;
1896 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001897 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001898 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001899 }
1900 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1901 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1902 classes.Assign(
1903 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1904 CHECK(classes.Get() != nullptr); // OOME.
1905 local_arg.index = 0;
1906 local_arg.success = true;
1907 VisitClasses(GetClassesVisitorArray, &local_arg);
1908 }
1909 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1910 // If the class table shrank during creation of the clases array we expect null elements. If
1911 // the class table grew then the loop repeats. If classes are created after the loop has
1912 // finished then we don't visit.
1913 mirror::Class* klass = classes->Get(i);
1914 if (klass != nullptr && !visitor(klass, arg)) {
1915 return;
1916 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001917 }
1918 }
1919}
1920
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001921ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001922 mirror::Class::ResetClass();
1923 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001924 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001925 mirror::ArtField::ResetClass();
1926 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001927 mirror::BooleanArray::ResetArrayClass();
1928 mirror::ByteArray::ResetArrayClass();
1929 mirror::CharArray::ResetArrayClass();
1930 mirror::DoubleArray::ResetArrayClass();
1931 mirror::FloatArray::ResetArrayClass();
1932 mirror::IntArray::ResetArrayClass();
1933 mirror::LongArray::ResetArrayClass();
1934 mirror::ShortArray::ResetArrayClass();
1935 mirror::Throwable::ResetClass();
1936 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001937 STLDeleteElements(&boot_class_path_);
1938 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001939}
1940
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001941mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001942 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001943 StackHandleScope<16> hs(self);
1944 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1945 Handle<mirror::DexCache> dex_cache(
1946 hs.NewHandle(down_cast<mirror::DexCache*>(
1947 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1948 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001949 if (dex_cache.Get() == nullptr) {
1950 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001951 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001952 Handle<mirror::String>
1953 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001954 if (location.Get() == nullptr) {
1955 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001956 }
Ian Rogers700a4022014-05-19 16:49:03 -07001957 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001958 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001959 if (strings.Get() == nullptr) {
1960 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001961 }
Ian Rogers700a4022014-05-19 16:49:03 -07001962 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001963 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001964 if (types.Get() == nullptr) {
1965 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001966 }
Ian Rogers700a4022014-05-19 16:49:03 -07001967 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001968 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001969 if (methods.Get() == nullptr) {
1970 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001971 }
Ian Rogers700a4022014-05-19 16:49:03 -07001972 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001973 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001974 if (fields.Get() == nullptr) {
1975 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001976 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001977 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1978 fields.Get());
1979 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001980}
1981
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001982mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001983 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001984 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001985 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001986 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001987 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001988 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1989 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001990 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001991 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001992 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001993 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001994 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001995}
1996
Ian Rogers6fac4472014-02-25 17:01:10 -08001997mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001998 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001999}
2000
Brian Carlstromea46f952013-07-30 01:26:50 -07002001mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002002 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002003 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07002004}
2005
Brian Carlstromea46f952013-07-30 01:26:50 -07002006mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002007 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002008 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002009}
2010
Mathieu Chartier590fee92013-09-13 13:46:47 -07002011mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
2012 Thread* self, size_t length) {
2013 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2014 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002015}
2016
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002017mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
2018 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002019 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002020
2021 // For temporary classes we must wait for them to be retired.
2022 if (init_done_ && klass->IsTemp()) {
2023 CHECK(!klass->IsResolved());
2024 if (klass->IsErroneous()) {
2025 ThrowEarlierClassFailure(klass);
2026 return nullptr;
2027 }
2028 StackHandleScope<1> hs(self);
2029 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2030 ObjectLock<mirror::Class> lock(self, h_class);
2031 // Loop and wait for the resolving thread to retire this class.
2032 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2033 lock.WaitIgnoringInterrupts();
2034 }
2035 if (h_class->IsErroneous()) {
2036 ThrowEarlierClassFailure(h_class.Get());
2037 return nullptr;
2038 }
2039 CHECK(h_class->IsRetired());
2040 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002041 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2042 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002043 }
2044
Brian Carlstromaded5f72011-10-07 17:15:04 -07002045 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002046 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002047 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002048 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2049 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002050 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002051 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2052 ThrowClassCircularityError(h_class.Get());
2053 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002054 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002055 }
2056 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002057 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002058 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002059 }
2060 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002061
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002062 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002063 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002064 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002065 }
2066 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002067 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002068 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002069 return klass;
2070}
2071
Ian Rogers68b56852014-08-29 20:19:11 -07002072typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2073
2074// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002075ClassPathEntry FindInClassPath(const char* descriptor,
2076 size_t hash, const std::vector<const DexFile*>& class_path) {
2077 for (const DexFile* dex_file : class_path) {
2078 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002079 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002080 return ClassPathEntry(dex_file, dex_class_def);
2081 }
2082 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002083 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002084}
2085
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002086mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2087 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002088 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002089 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08002090 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002091 if (class_loader->GetClass() !=
2092 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2093 class_loader->GetParent()->GetClass() !=
2094 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2095 return nullptr;
2096 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002097 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002098 // Check if this would be found in the parent boot class loader.
2099 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002100 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002101 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08002102 // May return null if resolution on another thread fails.
2103 klass = EnsureResolved(self, descriptor, klass);
2104 } else {
2105 // May OOME.
2106 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2107 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002108 }
Ian Rogers32427292014-11-19 14:05:21 -08002109 if (klass == nullptr) {
2110 CHECK(self->IsExceptionPending()) << descriptor;
2111 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002112 }
Ian Rogers32427292014-11-19 14:05:21 -08002113 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002114 } else {
Ian Rogers32427292014-11-19 14:05:21 -08002115 // Handle as if this is the child PathClassLoader.
2116 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002117 StackHandleScope<3> hs(self);
2118 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2119 // We need to get the DexPathList and loop through it.
2120 Handle<mirror::ArtField> cookie_field =
2121 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2122 Handle<mirror::ArtField> dex_file_field =
2123 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002124 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002125 mirror::Object* dex_path_list =
2126 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2127 GetObject(class_loader.Get());
2128 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2129 cookie_field.Get() != nullptr) {
2130 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2131 mirror::Object* dex_elements_obj =
2132 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2133 GetObject(dex_path_list);
2134 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2135 // at the mCookie which is a DexFile vector.
2136 if (dex_elements_obj != nullptr) {
2137 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2138 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2139 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2140 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2141 if (element == nullptr) {
2142 // Should never happen, fall back to java code to throw a NPE.
2143 break;
2144 }
2145 mirror::Object* dex_file = dex_file_field->GetObject(element);
2146 if (dex_file != nullptr) {
2147 const uint64_t cookie = cookie_field->GetLong(dex_file);
2148 auto* dex_files =
2149 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2150 if (dex_files == nullptr) {
2151 // This should never happen so log a warning.
2152 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2153 break;
2154 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002155 for (const DexFile* cp_dex_file : *dex_files) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002156 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002157 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002158 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002159 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2160 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002161 if (klass == nullptr) {
2162 CHECK(self->IsExceptionPending()) << descriptor;
2163 self->ClearException();
2164 return nullptr;
2165 }
2166 return klass;
2167 }
2168 }
2169 }
2170 }
2171 }
2172 }
Ian Rogers32427292014-11-19 14:05:21 -08002173 self->AssertNoPendingException();
2174 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002175 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002176}
2177
Ian Rogers98379392014-02-24 16:53:16 -08002178mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002179 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002180 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002181 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002182 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002183 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002184 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2185 // for primitive classes that aren't backed by dex files.
2186 return FindPrimitiveClass(descriptor[0]);
2187 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002188 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002189 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002190 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002191 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002192 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002193 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002194 // Class is not yet loaded.
2195 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002196 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002197 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002198 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002199 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002200 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002201 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002202 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002203 } else {
2204 // The boot class loader is searched ahead of the application class loader, failures are
2205 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2206 // trigger the chaining with a proper stack trace.
2207 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2208 self->SetException(ThrowLocation(), pre_allocated);
2209 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002210 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002211 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002212 // First try with the bootstrap class loader.
2213 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002214 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002215 if (klass != nullptr) {
2216 return EnsureResolved(self, descriptor, klass);
2217 }
2218 }
Ian Rogers63557452014-06-04 16:57:15 -07002219 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2220 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002221 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002222 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002223 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002224 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002225 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002226 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002227 const std::vector<const DexFile*>* class_path;
2228 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002229 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002230 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002231 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002232 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2233 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002234 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07002235 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002236 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07002237 } else {
2238 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2239 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2240 self->SetException(ThrowLocation(), pre_allocated);
2241 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002242 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002243 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002244 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002245 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2246 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002247 if (cp_klass != nullptr) {
2248 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002249 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002250 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002251 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002252 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002253 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002254 {
2255 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002256 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2257 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002258 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002259 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002260 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002261 }
Ian Rogers68b56852014-08-29 20:19:11 -07002262 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002263 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2264 WellKnownClasses::java_lang_ClassLoader_loadClass,
2265 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002266 }
Ian Rogers98379392014-02-24 16:53:16 -08002267 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002268 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002269 return nullptr;
2270 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002271 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002272 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002273 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002274 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002275 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002276 // success, return mirror::Class*
2277 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002278 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002279 }
Ian Rogers07140832014-09-30 15:43:59 -07002280 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002281}
2282
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002283mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002284 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002285 const DexFile& dex_file,
2286 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002287 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002288 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002289
Brian Carlstromaded5f72011-10-07 17:15:04 -07002290 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002291 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002292 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002293 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002294 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002295 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002296 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002297 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002298 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002299 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2300 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002301 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002302 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002303 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002304 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002305 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002306 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002307 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002308 }
2309
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002310 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002311 // Allocate a class with the status of not ready.
2312 // Interface object should get the right size here. Regular class will
2313 // figure out the right size later and be replaced with one of the right
2314 // size when the class becomes resolved.
2315 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002316 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002317 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002318 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002319 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002320 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002321 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002322 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002323 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002324 if (self->IsExceptionPending()) {
2325 // An exception occured during load, set status to erroneous while holding klass' lock in case
2326 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002327 if (!klass->IsErroneous()) {
2328 klass->SetStatus(mirror::Class::kStatusError, self);
2329 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002330 return nullptr;
2331 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002332 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002333
Mathieu Chartier590fee92013-09-13 13:46:47 -07002334 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002335 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002336 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002337 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2338 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002339 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002340 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002341
Brian Carlstromaded5f72011-10-07 17:15:04 -07002342 // Finish loading (if necessary) by finding parents
2343 CHECK(!klass->IsLoaded());
2344 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2345 // Loading 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 }
2351 CHECK(klass->IsLoaded());
2352 // Link the class (if necessary)
2353 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002354 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002355 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002356
2357 mirror::Class* new_class = nullptr;
2358 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002359 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002360 if (!klass->IsErroneous()) {
2361 klass->SetStatus(mirror::Class::kStatusError, self);
2362 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002363 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002364 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002365 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002366 CHECK(new_class != nullptr) << descriptor;
2367 CHECK(new_class->IsResolved()) << descriptor;
2368
2369 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002370
2371 /*
2372 * We send CLASS_PREPARE events to the debugger from here. The
2373 * definition of "preparation" is creating the static fields for a
2374 * class and initializing them to the standard default values, but not
2375 * executing any code (that comes later, during "initialization").
2376 *
2377 * We did the static preparation in LinkClass.
2378 *
2379 * The class has been prepared and resolved but possibly not yet verified
2380 * at this point.
2381 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002382 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002383
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002384 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002385}
2386
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002387uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2388 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002389 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002390 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002391 size_t num_8 = 0;
2392 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002393 size_t num_32 = 0;
2394 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002395 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002396 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2397 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002398 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002399 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002400 switch (c) {
2401 case 'L':
2402 case '[':
2403 num_ref++;
2404 break;
2405 case 'J':
2406 case 'D':
2407 num_64++;
2408 break;
2409 case 'I':
2410 case 'F':
2411 num_32++;
2412 break;
2413 case 'S':
2414 case 'C':
2415 num_16++;
2416 break;
2417 case 'B':
2418 case 'Z':
2419 num_8++;
2420 break;
2421 default:
2422 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002423 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002424 }
2425 }
2426 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002427 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002428}
2429
Ian Rogers97b52f82014-08-14 11:34:07 -07002430OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2431 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002432 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002433 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2434 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002435 *found = false;
2436 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002437 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002438 *found = true;
2439 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002440}
2441
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002442static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2443 uint32_t method_idx) {
2444 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002445 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002446 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002447 ClassDataItemIterator it(dex_file, class_data);
2448 // Skip fields
2449 while (it.HasNextStaticField()) {
2450 it.Next();
2451 }
2452 while (it.HasNextInstanceField()) {
2453 it.Next();
2454 }
2455 // Process methods
2456 size_t class_def_method_index = 0;
2457 while (it.HasNextDirectMethod()) {
2458 if (it.GetMemberIndex() == method_idx) {
2459 return class_def_method_index;
2460 }
2461 class_def_method_index++;
2462 it.Next();
2463 }
2464 while (it.HasNextVirtualMethod()) {
2465 if (it.GetMemberIndex() == method_idx) {
2466 return class_def_method_index;
2467 }
2468 class_def_method_index++;
2469 it.Next();
2470 }
2471 DCHECK(!it.HasNext());
2472 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08002473 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002474}
2475
Ian Rogers97b52f82014-08-14 11:34:07 -07002476const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002477 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002478 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002479 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002480 size_t oat_method_index;
2481 if (method->IsStatic() || method->IsDirect()) {
2482 // Simple case where the oat method index was stashed at load time.
2483 oat_method_index = method->GetMethodIndex();
2484 } else {
2485 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2486 // by search for its position in the declared virtual methods.
2487 oat_method_index = declaring_class->NumDirectMethods();
2488 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002489 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002490 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002491 // Check method index instead of identity in case of duplicate method definitions.
2492 if (method->GetDexMethodIndex() ==
2493 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002494 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002495 break;
2496 }
Ian Rogersf320b632012-03-13 18:47:47 -07002497 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002498 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002499 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2500 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002501 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002502 DCHECK_EQ(oat_method_index,
2503 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002504 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002505 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002506 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2507 declaring_class->GetDexClassDefIndex(),
2508 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002509 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002510 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002511 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002512 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002513}
2514
2515// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002516const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002517 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002518 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002519 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002520 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002521 bool found;
2522 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002523 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002524 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002525 result = oat_method.GetQuickCode();
2526 }
2527
Ian Rogersef7d42f2014-01-06 12:55:46 -08002528 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002529 if (method->IsNative()) {
2530 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002531 result = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002532 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002533 // No code? Do we expect portable code?
2534 result = GetQuickToPortableBridge();
2535 } else {
2536 // No code? You must mean to go into the interpreter.
2537 result = GetQuickToInterpreterBridge();
2538 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002539 }
2540 return result;
TDYa12785321912012-04-01 15:24:56 -07002541}
2542
Ian Rogersef7d42f2014-01-06 12:55:46 -08002543const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2544 bool* have_portable_code) {
2545 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2546 *have_portable_code = false;
2547 if (method->IsProxyMethod()) {
2548 return GetPortableProxyInvokeHandler();
2549 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002550 bool found;
2551 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002552 const void* result = nullptr;
2553 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002554 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002555 result = oat_method.GetPortableCode();
2556 quick_code = oat_method.GetQuickCode();
2557 }
2558
Ian Rogersef7d42f2014-01-06 12:55:46 -08002559 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002560 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002561 // No code? You must mean to go into the interpreter.
2562 result = GetPortableToInterpreterBridge();
2563 } else {
2564 // No code? But there's quick code, so use a bridge.
2565 result = GetPortableToQuickBridge();
2566 }
2567 } else {
2568 *have_portable_code = true;
2569 }
2570 return result;
2571}
2572
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002573const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2574 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2575 return nullptr;
2576 }
2577 bool found;
2578 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2579 return found ? oat_method.GetQuickCode() : nullptr;
2580}
2581
2582const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2583 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2584 return nullptr;
2585 }
2586 bool found;
2587 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2588 return found ? oat_method.GetPortableCode() : nullptr;
2589}
2590
Ian Rogersef7d42f2014-01-06 12:55:46 -08002591const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2592 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002593 bool found;
2594 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2595 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002596 return nullptr;
2597 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002598 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002599 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002600}
2601
2602const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2603 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002604 bool found;
2605 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2606 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002607 return nullptr;
2608 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002609 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002610 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002611}
2612
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002613// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002614static bool NeedsInterpreter(
2615 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2616 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002617 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002618 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002619 // May return true for native code, in the case of generic JNI
2620 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002621 return true;
2622 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002623#ifdef ART_SEA_IR_MODE
2624 ScopedObjectAccess soa(Thread::Current());
2625 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2626 LOG(INFO) << "Found " << PrettyMethod(method);
2627 return false;
2628 }
2629#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002630 // If interpreter mode is enabled, every method (except native and proxy) must
2631 // be run with interpreter.
2632 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2633 !method->IsNative() && !method->IsProxyMethod();
2634}
2635
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002636void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002637 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002638 if (klass->NumDirectMethods() == 0) {
2639 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002640 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002641 Runtime* runtime = Runtime::Current();
2642 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002643 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2644 return; // OAT file unavailable.
2645 }
Ian Rogers19846512012-02-24 11:42:47 -08002646 }
Alex Light64ad14d2014-08-19 14:23:13 -07002647
Mathieu Chartierf8322842014-05-16 10:59:25 -07002648 const DexFile& dex_file = klass->GetDexFile();
2649 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002650 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002651 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002652 // There should always be class data if there were direct methods.
2653 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002654 ClassDataItemIterator it(dex_file, class_data);
2655 // Skip fields
2656 while (it.HasNextStaticField()) {
2657 it.Next();
2658 }
2659 while (it.HasNextInstanceField()) {
2660 it.Next();
2661 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002662 bool has_oat_class;
2663 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2664 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002665 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002666 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002667 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002668 if (!method->IsStatic()) {
2669 // Only update static methods.
2670 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002671 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002672 const void* portable_code = nullptr;
2673 const void* quick_code = nullptr;
2674 if (has_oat_class) {
2675 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2676 portable_code = oat_method.GetPortableCode();
2677 quick_code = oat_method.GetQuickCode();
2678 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002679 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2680 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002681 if (enter_interpreter) {
2682 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002683 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002684 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002685 quick_code = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002686 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002687 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002688 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002689 quick_code = GetQuickToInterpreterBridge();
2690 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002691 } else {
2692 if (portable_code == nullptr) {
2693 portable_code = GetPortableToQuickBridge();
2694 } else {
2695 have_portable_code = true;
2696 }
2697 if (quick_code == nullptr) {
2698 quick_code = GetQuickToPortableBridge();
2699 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002700 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002701 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2702 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002703 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002704 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002705}
2706
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002707void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002708 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002709 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002710 Runtime* runtime = Runtime::Current();
2711 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002712 // The following code only applies to a non-compiler runtime.
2713 return;
2714 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002715 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002716 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2717 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002718 if (oat_class != nullptr) {
2719 // Every kind of method should at least get an invoke stub from the oat_method.
2720 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002721 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002722 oat_method.LinkMethod(method.Get());
2723 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002724
Jeff Hao16743632013-05-08 10:59:04 -07002725 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002726 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002727 method->GetEntryPointFromQuickCompiledCode(),
2728 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002729 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002730 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002731 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002732 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002733 }
2734
Brian Carlstrom92827a52011-10-10 15:50:01 -07002735 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002736 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2737 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002738 return;
2739 }
Ian Rogers19846512012-02-24 11:42:47 -08002740
Ian Rogersef7d42f2014-01-06 12:55:46 -08002741 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002742 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002743 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002744 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2745 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002746 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2747 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002748 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002749 if (!method->IsNative()) {
2750 // Set entry point from compiled code if there's no code or in interpreter only mode.
2751 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2752 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2753 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002754 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002755 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2756 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002757 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2758 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2759 have_portable_code = true;
2760 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2761 } else {
2762 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2763 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002764 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002765
Ian Rogers62d6c772013-02-27 08:32:07 -08002766 if (method->IsNative()) {
2767 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002768 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002769
2770 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002771 // We have a native method here without code. Then it should have either the generic JNI
2772 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2773 // TODO: this doesn't handle all the cases where trampolines may be installed.
2774 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2775 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002776 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002777 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002778
Ian Rogers62d6c772013-02-27 08:32:07 -08002779 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002780 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002781 method->GetEntryPointFromQuickCompiledCode(),
2782 method->GetEntryPointFromPortableCompiledCode(),
2783 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002784}
2785
Fred Shih37f05ef2014-07-16 18:38:08 -07002786
Fred Shih37f05ef2014-07-16 18:38:08 -07002787
Ian Rogers7b078e82014-09-10 14:44:24 -07002788void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002789 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002790 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002791 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002792 CHECK(klass.Get() != nullptr);
2793 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002794 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002795 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002796 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002797
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002798 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002799 if (kUseBakerOrBrooksReadBarrier) {
2800 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002801 }
Andreas Gampe51829322014-08-25 15:05:04 -07002802 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002803 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002804 klass->SetAccessFlags(access_flags);
2805 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002806 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002807 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002808
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002809 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002810 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002811 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002812
Ian Rogers13735952014-10-08 12:43:28 -07002813 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002814 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002815 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002816 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002817
Ian Rogers97b52f82014-08-14 11:34:07 -07002818
2819 bool has_oat_class = false;
2820 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2821 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2822 &has_oat_class);
2823 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002824 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002825 }
2826 }
2827 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002828 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002829 }
2830}
2831
Ian Rogers7b078e82014-09-10 14:44:24 -07002832void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002833 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002834 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002835 const OatFile::OatClass* oat_class) {
2836 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002837 ClassDataItemIterator it(dex_file, class_data);
2838 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002839 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002840 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002841 CHECK(self->IsExceptionPending()); // OOME.
2842 return;
2843 }
2844 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002845 }
2846 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002847 mirror::ObjectArray<mirror::ArtField>* fields =
2848 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002849 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002850 CHECK(self->IsExceptionPending()); // OOME.
2851 return;
2852 }
2853 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002854 }
2855 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002856 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002857 StackHandleScope<1> hs(self);
2858 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002859 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002860 CHECK(self->IsExceptionPending()); // OOME.
2861 return;
2862 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002863 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002864 LoadField(dex_file, it, klass, sfield);
2865 }
2866 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002867 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002868 StackHandleScope<1> hs(self);
2869 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002870 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002871 CHECK(self->IsExceptionPending()); // OOME.
2872 return;
2873 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002874 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002875 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002876 }
2877
Ian Rogers0571d352011-11-03 19:51:38 -07002878 // Load methods.
2879 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002880 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002881 mirror::ObjectArray<mirror::ArtMethod>* directs =
2882 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002883 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002884 CHECK(self->IsExceptionPending()); // OOME.
2885 return;
2886 }
2887 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002888 }
Ian Rogers0571d352011-11-03 19:51:38 -07002889 if (it.NumVirtualMethods() != 0) {
2890 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002891 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2892 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002893 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002894 CHECK(self->IsExceptionPending()); // OOME.
2895 return;
2896 }
2897 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002898 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002899 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002900 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2901 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002902 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002903 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002904 StackHandleScope<1> hs(self);
2905 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002906 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002907 CHECK(self->IsExceptionPending()); // OOME.
2908 return;
2909 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002910 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002911 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002912 uint32_t it_method_index = it.GetMemberIndex();
2913 if (last_dex_method_index == it_method_index) {
2914 // duplicate case
2915 method->SetMethodIndex(last_class_def_method_index);
2916 } else {
2917 method->SetMethodIndex(class_def_method_index);
2918 last_dex_method_index = it_method_index;
2919 last_class_def_method_index = class_def_method_index;
2920 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002921 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002922 }
2923 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002924 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002925 StackHandleScope<1> hs(self);
2926 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002927 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002928 CHECK(self->IsExceptionPending()); // OOME.
2929 return;
2930 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002931 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002932 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002933 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002934 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002935 }
2936 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002937}
2938
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002939void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002940 Handle<mirror::Class> klass,
2941 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002942 uint32_t field_idx = it.GetMemberIndex();
2943 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002944 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002945 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002946}
2947
Brian Carlstromea46f952013-07-30 01:26:50 -07002948mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002949 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002950 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002951 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002952 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002953 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002954
Brian Carlstromea46f952013-07-30 01:26:50 -07002955 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002956 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002957 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002958 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002959 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002960 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002961
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002962 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002963 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002964 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002965 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002966
Ian Rogers19846512012-02-24 11:42:47 -08002967 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002968 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002969
Andreas Gampe51829322014-08-25 15:05:04 -07002970 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002971
Ian Rogersdfb325e2013-10-30 01:00:44 -07002972 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002973 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002974 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2975 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002976 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002977 klass->SetFinalizable();
2978 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002979 std::string temp;
2980 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002981 // The Enum class declares a "final" finalize() method to prevent subclasses from
2982 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2983 // subclasses, so we exclude it here.
2984 // We also want to avoid setting the flag on Object, where we know that finalize() is
2985 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002986 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2987 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002988 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002989 }
2990 }
2991 }
2992 } else if (method_name[0] == '<') {
2993 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002994 bool is_init = (strcmp("<init>", method_name) == 0);
2995 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002996 if (UNLIKELY(!is_init && !is_clinit)) {
2997 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2998 } else {
2999 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3000 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003001 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003002 access_flags |= kAccConstructor;
3003 }
3004 }
3005 }
3006 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003007
Mathieu Chartier66f19252012-09-18 08:57:04 -07003008 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07003009}
3010
Ian Rogers7b078e82014-09-10 14:44:24 -07003011void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003012 StackHandleScope<1> hs(self);
3013 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003014 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3015 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003016 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003017}
3018
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003019void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003020 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003021 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003022 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003023 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003024}
3025
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003026bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003027 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07003028 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003029 mirror::DexCache* dex_cache = GetDexCache(i);
3030 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08003031 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003032 }
3033 }
3034 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07003035}
3036
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003037bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003038 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07003039 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003040}
3041
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003042void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003043 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003044 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003045 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003046 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3047 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003048 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003049 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003050 if (log_new_dex_caches_roots_) {
3051 // TODO: This is not safe if we can remove dex caches.
3052 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3053 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003054}
3055
Brian Carlstromaded5f72011-10-07 17:15:04 -07003056void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003057 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003058 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003059 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003060 if (IsDexFileRegisteredLocked(dex_file)) {
3061 return;
3062 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003063 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003064 // Don't alloc while holding the lock, since allocation may need to
3065 // suspend all threads and another thread may need the dex_lock_ to
3066 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003067 StackHandleScope<1> hs(self);
3068 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003069 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3070 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003071 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003072 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003073 if (IsDexFileRegisteredLocked(dex_file)) {
3074 return;
3075 }
3076 RegisterDexFileLocked(dex_file, dex_cache);
3077 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003078}
3079
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003080void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003081 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003082 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003083 RegisterDexFileLocked(dex_file, dex_cache);
3084}
3085
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003086mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003087 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003088 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003089 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003090 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003091 if (dex_cache->GetDexFile() == &dex_file) {
3092 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003093 }
3094 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003095 // Search matching by location name.
3096 std::string location(dex_file.GetLocation());
3097 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003098 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003099 if (dex_cache->GetDexFile()->GetLocation() == location) {
3100 return dex_cache;
3101 }
3102 }
3103 // Failure, dump diagnostic and abort.
3104 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003105 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003106 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3107 }
3108 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003109 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003110}
3111
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003112void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003113 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003114 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003115 mirror::DexCache* dex_cache = GetDexCache(i);
3116 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003117 }
3118}
3119
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003120mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003121 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003122 if (UNLIKELY(klass == nullptr)) {
3123 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003124 }
3125 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003126}
3127
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003128mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3129 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003130 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003131 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003132 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003133 StackHandleScope<1> hs(self);
3134 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003135 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003136 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003137 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003138 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3139 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003140 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3141 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003142 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003143 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003144}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003145
Brian Carlstrombe977852011-07-19 14:54:54 -07003146// Create an array class (i.e. the class object for the array, not the
3147// array itself). "descriptor" looks like "[C" or "[[[[B" or
3148// "[Ljava/lang/String;".
3149//
3150// If "descriptor" refers to an array of primitives, look up the
3151// primitive type's internally-generated class object.
3152//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003153// "class_loader" is the class loader of the class that's referring to
3154// us. It's used to ensure that we're looking for the element type in
3155// the right context. It does NOT become the class loader for the
3156// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003157//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003158// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003159mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003160 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003161 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003162 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003163 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003164 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3165 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003166 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003167 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003168 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003169 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3170 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003171 if (component_type.Get() == nullptr) {
3172 DCHECK(self->IsExceptionPending());
3173 return nullptr;
3174 } else {
3175 self->ClearException();
3176 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003177 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003178 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3179 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3180 return nullptr;
3181 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003182 // See if the component type is already loaded. Array classes are
3183 // always associated with the class loader of their underlying
3184 // element type -- an array of Strings goes with the loader for
3185 // java/lang/String -- so we need to look for it there. (The
3186 // caller should have checked for the existence of the class
3187 // before calling here, but they did so with *their* class loader,
3188 // not the component type's loader.)
3189 //
3190 // If we find it, the caller adds "loader" to the class' initiating
3191 // loader list, which should prevent us from going through this again.
3192 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003193 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003194 // are the same, because our caller (FindClass) just did the
3195 // lookup. (Even if we get this wrong we still have correct behavior,
3196 // because we effectively do this lookup again when we add the new
3197 // class to the hash table --- necessary because of possible races with
3198 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003199 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003200 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003201 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003202 return new_class;
3203 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003204 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003205
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003206 // Fill out the fields in the Class.
3207 //
3208 // It is possible to execute some methods against arrays, because
3209 // all arrays are subclasses of java_lang_Object_, so we need to set
3210 // up a vtable. We can just point at the one in java_lang_Object_.
3211 //
3212 // Array classes are simple enough that we don't need to do a full
3213 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003214 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003215 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003216 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003217 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003218 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003219 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003220 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003221 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003222 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003223 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003224 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003225 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003226 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003227 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003228 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003229 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003230 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003231 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003232 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003233 }
3234 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003235 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003236 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003237 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003238 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003239 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003240 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003241 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003242 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003243 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003244 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003245 new_class->SetSuperClass(java_lang_Object);
3246 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003247 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003248 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003249 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003250 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003251 StackHandleScope<mirror::Class::kImtSize> hs2(self,
3252 Runtime::Current()->GetImtUnimplementedMethod());
3253 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003254 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003255 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003256 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003257 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003258
3259
3260 // All arrays have java/lang/Cloneable and java/io/Serializable as
3261 // interfaces. We need to set that up here, so that stuff like
3262 // "instanceof" works right.
3263 //
3264 // Note: The GC could run during the call to FindSystemClass,
3265 // so we need to make sure the class object is GC-valid while we're in
3266 // there. Do this by clearing the interface list so the GC will just
3267 // think that the entries are null.
3268
3269
3270 // Use the single, global copies of "interfaces" and "iftable"
3271 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003272 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003273 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003274 CHECK(array_iftable != nullptr);
3275 new_class->SetIfTable(array_iftable);
3276 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003277
Elliott Hughes00626c22013-06-14 15:04:14 -07003278 // Inherit access flags from the component type.
3279 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3280 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3281 access_flags &= kAccJavaFlagsMask;
3282 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003283 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003284 access_flags |= kAccAbstract | kAccFinal;
3285 access_flags &= ~kAccInterface;
3286
3287 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003288
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003289 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003290 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003291 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003292 }
3293 // Another thread must have loaded the class after we
3294 // started but before we finished. Abandon what we've
3295 // done.
3296 //
3297 // (Yes, this happens.)
3298
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003299 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003300}
3301
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003302mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003303 switch (type) {
3304 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003305 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003306 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003307 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003308 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003309 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003310 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003311 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003312 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003313 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003314 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003315 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003316 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003317 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003318 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003319 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003320 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003321 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003322 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003323 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003324 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003325 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003326 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003327 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003328}
3329
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003330mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3331 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003332 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003333 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003334 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003335 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003336 source += " from ";
3337 source += dex_cache->GetLocation()->ToModifiedUtf8();
3338 }
3339 LOG(INFO) << "Loaded class " << descriptor << source;
3340 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003341 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003342 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003343 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003344 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003345 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003346 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003347 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003348 // Check a class loaded with the system class loader matches one in the image if the class
3349 // is in the image.
3350 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003351 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003352 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003353 }
3354 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003355 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003356 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003357 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003358 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003359 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003360 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003361}
3362
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003363mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3364 size_t hash) {
3365 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003366 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3367 hash);
3368 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003369 CHECK(klass->IsProxyClass());
3370 return nullptr;
3371 }
3372
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003373 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003374 CHECK_NE(existing, klass) << descriptor;
3375 CHECK(!existing->IsResolved()) << descriptor;
3376 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3377
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003378 CHECK(!klass->IsTemp()) << descriptor;
3379 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3380 dex_cache_image_class_lookup_required_) {
3381 // Check a class loaded with the system class loader matches one in the image if the class
3382 // is in the image.
3383 existing = LookupClassFromImage(descriptor);
3384 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003385 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003386 }
3387 }
3388 VerifyObject(klass);
3389
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003390 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003391 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003392 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003393 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003394 }
3395
3396 return existing;
3397}
3398
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003399bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003400 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003401 auto pair = std::make_pair(descriptor, class_loader);
3402 auto it = class_table_.Find(pair);
3403 if (it != class_table_.end()) {
3404 class_table_.Erase(it);
3405 return true;
3406 }
3407 it = pre_zygote_class_table_.Find(pair);
3408 if (it != pre_zygote_class_table_.end()) {
3409 pre_zygote_class_table_.Erase(it);
3410 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003411 }
3412 return false;
3413}
3414
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003415mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003416 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003417 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003418 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003419 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003420 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003421 return result;
3422 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003423 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003424 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3425 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003426 } else {
3427 // Lookup failed but need to search dex_caches_.
3428 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003429 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003430 InsertClass(descriptor, result, hash);
3431 } else {
3432 // Searching the image dex files/caches failed, we don't want to get into this situation
3433 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3434 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003435 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003436 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3437 MoveImageClassesToClassTable();
3438 }
3439 }
3440 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003441 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003442}
3443
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003444mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003445 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003446 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003447 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3448 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3449 if (it == pre_zygote_class_table_.end()) {
3450 it = class_table_.FindWithHash(descriptor_pair, hash);
3451 if (it == class_table_.end()) {
3452 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003453 }
3454 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003455 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003456}
3457
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003458static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3459 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3460 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003461 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003462 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3463 return root->AsObjectArray<mirror::DexCache>();
3464}
3465
3466void ClassLinker::MoveImageClassesToClassTable() {
3467 Thread* self = Thread::Current();
3468 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3469 if (!dex_cache_image_class_lookup_required_) {
3470 return; // All dex cache classes are already in the class table.
3471 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003472 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003473 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003474 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003475 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3476 mirror::DexCache* dex_cache = dex_caches->Get(i);
3477 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3478 for (int32_t j = 0; j < types->GetLength(); j++) {
3479 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003480 if (klass != nullptr) {
3481 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003482 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003483 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003484 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3485 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003486 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003487 << PrettyClassAndClassLoader(klass);
3488 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003489 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003490 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003491 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003492 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003493 }
3494 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003495 }
3496 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003497 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003498}
3499
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003500void ClassLinker::MoveClassTableToPreZygote() {
3501 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3502 DCHECK(pre_zygote_class_table_.Empty());
3503 pre_zygote_class_table_ = std::move(class_table_);
3504 class_table_.Clear();
3505}
3506
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003507mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003508 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003509 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3510 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3511 mirror::DexCache* dex_cache = dex_caches->Get(i);
3512 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003513 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003514 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003515 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003516 const DexFile::TypeId* type_id =
3517 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003518 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003519 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3520 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003521 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003522 return klass;
3523 }
3524 }
3525 }
3526 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003527 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003528}
3529
3530void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3531 result.clear();
3532 if (dex_cache_image_class_lookup_required_) {
3533 MoveImageClassesToClassTable();
3534 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003535 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3536 while (true) {
3537 auto it = class_table_.Find(descriptor);
3538 if (it == class_table_.end()) {
3539 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003540 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003541 result.push_back(it->Read());
3542 class_table_.Erase(it);
3543 }
3544 for (mirror::Class* k : result) {
3545 class_table_.Insert(GcRoot<mirror::Class>(k));
3546 }
3547 size_t pre_zygote_start = result.size();
3548 // Now handle the pre zygote table.
3549 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3550 // called from the debugger.
3551 while (true) {
3552 auto it = pre_zygote_class_table_.Find(descriptor);
3553 if (it == pre_zygote_class_table_.end()) {
3554 break;
3555 }
3556 result.push_back(it->Read());
3557 pre_zygote_class_table_.Erase(it);
3558 }
3559 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3560 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003561 }
3562}
3563
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003564void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003565 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003566 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003567
Ian Rogers9ffb0392012-09-10 11:56:50 -07003568 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003569 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003570 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003571 return;
3572 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003573 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3574 return;
3575 }
jeffhao98eacac2011-09-14 16:11:53 -07003576
Ian Rogers9ffb0392012-09-10 11:56:50 -07003577 // The class might already be erroneous, for example at compile time if we attempted to verify
3578 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003579 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003580 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003581 return;
3582 }
3583
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003584 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003585 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003586 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003587 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003588 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003589 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003590 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003591 }
jeffhao98eacac2011-09-14 16:11:53 -07003592
Jeff Hao4a200f52014-04-01 14:58:49 -07003593 // Skip verification if disabled.
3594 if (!Runtime::Current()->IsVerificationEnabled()) {
3595 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003596 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003597 return;
3598 }
3599
Ian Rogers9ffb0392012-09-10 11:56:50 -07003600 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003601 StackHandleScope<2> hs(self);
3602 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003603 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003604 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003605 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003606
3607 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003608 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003609 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003610 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003611 std::string error_msg(
3612 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3613 PrettyDescriptor(klass.Get()).c_str(),
3614 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003615 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003616 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3617 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003618 self->ClearException();
3619 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003620 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3621 if (cause.Get() != nullptr) {
3622 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003623 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003624 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003625 if (Runtime::Current()->IsCompiler()) {
3626 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3627 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003628 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003629 return;
3630 }
3631 }
3632
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003633 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003634 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003635 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003636 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003637 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003638 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003639 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003640 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003641 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3642 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003643 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003644 return;
3645 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003646 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003647 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003648 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003649 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003650 Runtime::Current()->IsCompiler(),
3651 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003652 }
3653 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003654 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003655 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003656 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3657 << " because: " << error_msg;
3658 }
Ian Rogers1f539342012-10-03 21:09:42 -07003659 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003660 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003661 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003662 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003663 // Even though there were no verifier failures we need to respect whether the super-class
3664 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003665 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003666 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003667 } else {
3668 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003669 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003670 // Pretend a soft failure occured so that we don't consider the class verified below.
3671 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003672 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003673 } else {
3674 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3675 // Soft failures at compile time should be retried at runtime. Soft
3676 // failures at runtime will be handled by slow paths in the generated
3677 // code. Set status accordingly.
3678 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003679 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003680 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003681 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003682 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3683 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003684 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003685 }
3686 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003687 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003688 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003689 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3690 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003691 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003692 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003693 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003694 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003695 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003696 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003697 // Let the interpreter know it by setting the kAccPreverified flag onto each
3698 // method.
3699 // Note: we're going here during compilation and at runtime. When we set the
3700 // kAccPreverified flag when compiling image classes, the flag is recorded
3701 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003702 EnsurePreverifiedMethods(klass);
3703 }
3704}
3705
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003706void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003707 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003708 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003709 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003710 }
jeffhao98eacac2011-09-14 16:11:53 -07003711}
3712
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003713bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3714 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003715 // If we're compiling, we can only verify the class using the oat file if
3716 // we are not compiling the image or if the class we're verifying is not part of
3717 // the app. In other words, we will only check for preverification of bootclasspath
3718 // classes.
3719 if (Runtime::Current()->IsCompiler()) {
3720 // Are we compiling the bootclasspath?
3721 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3722 return false;
3723 }
3724 // We are compiling an app (not the image).
3725
3726 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003727 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003728 return false;
3729 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003730 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003731
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003732 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003733 // In case we run without an image there won't be a backing oat file.
3734 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003735 return false;
3736 }
3737
Andreas Gampe76bd8802014-12-10 16:43:58 -08003738 // We may be running with a preopted oat file but without image. In this case,
3739 // we don't skip verification of preverified classes to ensure we initialize
3740 // dex caches with all types resolved during verification.
3741 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
3742 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
3743 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
3744 // already pre-opted, as then the runtime is started.
3745 if (!Runtime::Current()->IsCompiler() &&
3746 !Runtime::Current()->GetHeap()->HasImageSpace() &&
3747 klass->GetClassLoader() != nullptr) {
3748 return false;
3749 }
3750
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003751 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003752 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003753 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3754 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003755 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003756 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003757 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003758 // Compile time verification failed with a soft error. Compile time verification can fail
3759 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003760 // class ... {
3761 // Foo x;
3762 // .... () {
3763 // if (...) {
3764 // v1 gets assigned a type of resolved class Foo
3765 // } else {
3766 // v1 gets assigned a type of unresolved class Bar
3767 // }
3768 // iput x = v1
3769 // } }
3770 // when we merge v1 following the if-the-else it results in Conflict
3771 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3772 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3773 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3774 // at compile time).
3775 return false;
3776 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003777 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003778 // Compile time verification failed with a hard error. This is caused by invalid instructions
3779 // in the class. These errors are unrecoverable.
3780 return false;
3781 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003782 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003783 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3784 // not loading the class.
3785 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3786 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003787 return false;
3788 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003789 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003790 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003791 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003792 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003793 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003794}
3795
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003796void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003797 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003798 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3799 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3800 }
3801 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3802 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3803 }
3804}
3805
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003806void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003807 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003808 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3809 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003810 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003811 return; // native or abstract method
3812 }
3813 if (code_item->tries_size_ == 0) {
3814 return; // nothing to process
3815 }
Ian Rogers13735952014-10-08 12:43:28 -07003816 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003817 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3818 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3819 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3820 CatchHandlerIterator iterator(handlers_ptr);
3821 for (; iterator.HasNext(); iterator.Next()) {
3822 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3823 // unresolved exception types will be ignored by exception delivery
3824 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003825 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003826 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003827 DCHECK(Thread::Current()->IsExceptionPending());
3828 Thread::Current()->ClearException();
3829 }
3830 }
3831 }
3832 handlers_ptr = iterator.EndDataPointer();
3833 }
3834}
3835
Brian Carlstromea46f952013-07-30 01:26:50 -07003836static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003837static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3838 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003839
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003840mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003841 jobjectArray interfaces, jobject loader,
3842 jobjectArray methods, jobjectArray throws) {
3843 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003844 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003845 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003846 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003847 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003848 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003849 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003850 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003851 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003852 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003853 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3854 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003855 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003856 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003857 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003858 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003859 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003860 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003861
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003862 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003863 {
3864 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003865 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003866 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003867 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003868 }
3869 klass->SetSFields(sfields);
3870 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003871 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3872 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003873 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3874 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003875 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003876 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003877 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003878 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003879 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003880 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003881 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3882 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003883 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3884 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003885 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003886 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003887 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003888 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003889 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003890 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003891 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003892
Ian Rogers466bb252011-10-14 03:29:56 -07003893 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003894 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003895 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003896 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003897 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003898 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003899 }
3900 klass->SetDirectMethods(directs);
3901 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003902 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003903 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003904 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003905 }
3906 klass->SetDirectMethod(0, constructor);
3907 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003908
Mathieu Chartier590fee92013-09-13 13:46:47 -07003909 // Create virtual method using specified prototypes.
3910 size_t num_virtual_methods =
3911 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003912 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003913 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3914 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003915 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003916 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003917 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003918 }
3919 klass->SetVirtualMethods(virtuals);
3920 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003921 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003922 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003923 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3924 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003925 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003926 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003927 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003928 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003929 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003930 }
3931 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003932 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003933
3934 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003935 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003936 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003937
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003938 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3939 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003940 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003941 // Must hold lock on object when resolved.
3942 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003943 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003944 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003945 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003946 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003947 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003948 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003949 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003950 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003951
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003952 CHECK(klass->IsRetired());
3953 CHECK_NE(klass.Get(), new_class);
3954 klass.Assign(new_class);
3955
3956 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003957 interfaces_sfield->SetObject<false>(klass.Get(),
3958 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003959 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003960 throws_sfield->SetObject<false>(klass.Get(),
3961 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003962
3963 {
3964 // Lock on klass is released. Lock new class object.
3965 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003966 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003967 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003968
3969 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003970 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003971 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003972 CheckProxyConstructor(klass->GetDirectMethod(0));
3973 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003974 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003975 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3976 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003977 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3978 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003979 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003980 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003981
Mathieu Chartier590fee92013-09-13 13:46:47 -07003982 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003983 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003984 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003985 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3986
3987 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003988 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003989 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003990
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003991 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003992 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003993 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003994 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003995 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003996 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3997 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003998 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003999 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004000}
4001
Ian Rogersef7d42f2014-01-06 12:55:46 -08004002std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004003 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004004 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004005 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004006 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4007}
4008
Ian Rogersef7d42f2014-01-06 12:55:46 -08004009mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
4010 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08004011 DCHECK(proxy_class->IsProxyClass());
4012 DCHECK(proxy_method->IsProxyMethod());
4013 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07004014 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08004015 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07004016 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08004017 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004018 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07004019 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004020 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08004021 break;
4022 }
4023 }
4024 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07004025 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08004026 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07004027 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07004028 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08004029 return resolved_method;
4030}
4031
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004032
Brian Carlstromea46f952013-07-30 01:26:50 -07004033mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004034 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07004035 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07004036 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07004037 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004038 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07004039 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
4040 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02004041 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4042 // constructor method.
4043 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
4044 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07004045 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4046 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07004047 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
4048 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004049 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07004050 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004051 }
Ian Rogers466bb252011-10-14 03:29:56 -07004052 // Make this constructor public and fix the class to be our Proxy version
4053 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004054 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004055 return constructor;
4056}
4057
Brian Carlstromea46f952013-07-30 01:26:50 -07004058static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004059 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004060 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004061 CHECK_STREQ(constructor->GetName(), "<init>");
4062 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4063 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004064 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004065}
4066
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004067mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004068 Handle<mirror::Class> klass,
4069 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004070 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4071 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004072 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004073 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004074 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004075 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004076 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004077 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004078 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004079 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004080 }
Ian Rogers466bb252011-10-14 03:29:56 -07004081
4082 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4083 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004084 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004085 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004086
Ian Rogers466bb252011-10-14 03:29:56 -07004087 // At runtime the method looks like a reference and argument saving method, clone the code
4088 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004089 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4090 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004091 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004092
Ian Rogersc2b44472011-12-14 21:17:17 -08004093 return method;
4094}
Jesse Wilson95caa792011-10-12 18:14:17 -04004095
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004096static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4097 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004098 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004099 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004100 CHECK(!prototype->IsFinal());
4101 CHECK(method->IsFinal());
4102 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004103
4104 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4105 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07004106 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4107 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004108 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4109
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004110 CHECK_STREQ(method->GetName(), prototype->GetName());
4111 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004112 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004113 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004114}
4115
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004116static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4117 bool can_init_parents)
4118 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004119 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004120 return true;
4121 }
4122 if (!can_init_statics) {
4123 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004124 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004125 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004126 return false;
4127 }
4128 // Check if there are encoded static values needing initialization.
4129 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004130 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004131 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004132 if (dex_class_def->static_values_off_ != 0) {
4133 return false;
4134 }
4135 }
4136 }
4137 if (!klass->IsInterface() && klass->HasSuperClass()) {
4138 mirror::Class* super_class = klass->GetSuperClass();
4139 if (!can_init_parents && !super_class->IsInitialized()) {
4140 return false;
4141 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004142 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004143 return false;
4144 }
4145 }
4146 }
4147 return true;
4148}
4149
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004150bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004151 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004152 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4153
4154 // Are we already initialized and therefore done?
4155 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4156 // an initialized class will never change its state.
4157 if (klass->IsInitialized()) {
4158 return true;
4159 }
4160
4161 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004162 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004163 return false;
4164 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004165
Ian Rogers7b078e82014-09-10 14:44:24 -07004166 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004167 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004168 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004169 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004170
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004171 // Re-check under the lock in case another thread initialized ahead of us.
4172 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004173 return true;
4174 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004175
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004176 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004177 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004178 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004179 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004180 return false;
4181 }
4182
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004183 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004184
4185 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004186 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004187 if (!klass->IsVerified()) {
4188 // We failed to verify, expect either the klass to be erroneous or verification failed at
4189 // compile time.
4190 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004191 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004192 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004193 } else {
4194 CHECK(Runtime::Current()->IsCompiler());
4195 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004196 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004197 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004198 } else {
4199 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004200 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004201 }
4202
Brian Carlstromd1422f82011-09-28 11:37:09 -07004203 // If the class is kStatusInitializing, either this thread is
4204 // initializing higher up the stack or another thread has beat us
4205 // to initializing and we need to wait. Either way, this
4206 // invocation of InitializeClass will not be responsible for
4207 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004208 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004209 // Could have got an exception during verification.
4210 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004211 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004212 return false;
4213 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004214 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004215 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004216 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004217 return true;
4218 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004219 // No. That's fine. Wait for another thread to finish initializing.
4220 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004221 }
4222
4223 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004224 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004225 return false;
4226 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004227 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004228
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004229 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004230
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004231 // From here out other threads may observe that we're initializing and so changes of state
4232 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004233 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004234 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004235
4236 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004237 }
4238
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004239 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004240 if (!klass->IsInterface() && klass->HasSuperClass()) {
4241 mirror::Class* super_class = klass->GetSuperClass();
4242 if (!super_class->IsInitialized()) {
4243 CHECK(!super_class->IsInterface());
4244 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004245 StackHandleScope<1> hs(self);
4246 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004247 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004248 if (!super_initialized) {
4249 // The super class was verified ahead of entering initializing, we should only be here if
4250 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004251 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004252 << "Super class initialization failed for "
4253 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004254 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004255 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004256 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004257 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004258 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004259 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004260 return false;
4261 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004262 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004263 }
4264
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004265 const size_t num_static_fields = klass->NumStaticFields();
4266 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004267 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004268 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004269 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004270 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004271 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004272 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004273
4274 // Eagerly fill in static fields so that the we don't have to do as many expensive
4275 // Class::FindStaticField in ResolveField.
4276 for (size_t i = 0; i < num_static_fields; ++i) {
4277 mirror::ArtField* field = klass->GetStaticField(i);
4278 const uint32_t field_idx = field->GetDexFieldIndex();
4279 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4280 if (resolved_field == nullptr) {
4281 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004282 } else {
4283 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004284 }
4285 }
4286
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004287 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4288 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004289 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004290 ClassDataItemIterator field_it(dex_file, class_data);
4291 if (value_it.HasNext()) {
4292 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004293 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004294 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004295 StackHandleScope<1> hs2(self);
4296 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004297 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004298 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004299 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004300 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004301 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004302 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004303 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004304 }
4305 }
4306 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004307
Ian Rogersd91d6d62013-09-25 20:26:14 -07004308 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004309 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004310 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004311 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004312 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004313 }
4314
Ian Rogers7b078e82014-09-10 14:44:24 -07004315 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004316 uint64_t t1 = NanoTime();
4317
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004318 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004319 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004320 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004321
4322 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004323 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004324 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004325 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004326 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004327 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4328 RuntimeStats* thread_stats = self->GetStats();
4329 ++global_stats->class_init_count;
4330 ++thread_stats->class_init_count;
4331 global_stats->class_init_time_ns += (t1 - t0);
4332 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004333 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004334 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004335 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004336 std::string temp;
4337 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004338 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004339 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004340 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004341 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004342 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004343 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004344 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004345}
4346
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004347bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004348 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004349 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004350 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004351 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004352 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004353 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004354
4355 // When we wake up, repeat the test for init-in-progress. If
4356 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004357 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004358 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004359 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004360 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004361 return false;
4362 }
4363 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004364 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004365 continue;
4366 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004367 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004368 // Compile time initialization failed.
4369 return false;
4370 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004371 if (klass->IsErroneous()) {
4372 // The caller wants an exception, but it was thrown in a
4373 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004374 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004375 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004376 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004377 return false;
4378 }
4379 if (klass->IsInitialized()) {
4380 return true;
4381 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004382 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004383 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004384 }
Ian Rogers07140832014-09-30 15:43:59 -07004385 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004386}
4387
Ian Rogersb5fb2072014-12-02 17:22:02 -08004388static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
4389 Handle<mirror::ArtMethod> method1,
4390 Handle<mirror::ArtMethod> method2)
4391 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4392 {
4393 StackHandleScope<1> hs(self);
4394 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
4395 if (UNLIKELY(method2->GetReturnType() != return_type.Get())) {
4396 return false;
4397 }
4398 }
4399 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4400 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4401 if (types1 == nullptr) {
4402 return (types2 == nullptr) || (types2->Size() == 0);
4403 } else if (UNLIKELY(types2 == nullptr)) {
4404 return types1->Size() == 0;
4405 }
4406 uint32_t num_types = types1->Size();
4407 if (UNLIKELY(num_types != types2->Size())) {
4408 return false;
4409 }
4410 for (uint32_t i = 0; i < num_types; ++i) {
4411 mirror::Class* param_type =
4412 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true);
4413 mirror::Class* other_param_type =
4414 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
4415 if (UNLIKELY(param_type != other_param_type)) {
4416 return false;
4417 }
4418 }
4419 return true;
4420}
4421
4422
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004423bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004424 if (klass->IsInterface()) {
4425 return true;
4426 }
Ian Rogers151f2212014-05-06 11:27:27 -07004427 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004428 Thread* self = Thread::Current();
4429 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004430 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
4431 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004432 if (klass->HasSuperClass() &&
4433 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004434 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004435 h_m.Assign(klass->GetVTableEntry(i));
4436 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
4437 if (h_m.Get() != super_h_m.Get() &&
4438 !HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004439 ThrowLinkageError(klass.Get(),
4440 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004441 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogersb5fb2072014-12-02 17:22:02 -08004442 PrettyMethod(h_m.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004443 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004444 return false;
4445 }
4446 }
4447 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004448 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004449 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4450 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4451 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004452 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4453 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
4454 if (h_m.Get() != super_h_m.Get() &&
4455 !HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004456 ThrowLinkageError(klass.Get(),
4457 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004458 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogersb5fb2072014-12-02 17:22:02 -08004459 PrettyMethod(h_m.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004460 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004461 return false;
4462 }
4463 }
4464 }
4465 }
4466 return true;
4467}
4468
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004469bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4470 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004471 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004472 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004473 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004474 return true;
4475 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004476 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004477 if (!success) {
4478 if (can_init_fields && can_init_parents) {
4479 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4480 }
4481 } else {
4482 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004483 }
4484 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004485}
4486
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004487void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4488 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4489 if (fields != nullptr) {
4490 for (int index = 0; index < fields->GetLength(); index ++) {
4491 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4492 fields->Get(index)->SetDeclaringClass(new_class);
4493 }
4494 }
4495 }
4496
4497 fields = new_class->GetSFields();
4498 if (fields != nullptr) {
4499 for (int index = 0; index < fields->GetLength(); index ++) {
4500 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4501 fields->Get(index)->SetDeclaringClass(new_class);
4502 }
4503 }
4504 }
4505
4506 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4507 if (methods != nullptr) {
4508 for (int index = 0; index < methods->GetLength(); index ++) {
4509 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4510 methods->Get(index)->SetDeclaringClass(new_class);
4511 }
4512 }
4513 }
4514
4515 methods = new_class->GetVirtualMethods();
4516 if (methods != nullptr) {
4517 for (int index = 0; index < methods->GetLength(); index ++) {
4518 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4519 methods->Get(index)->SetDeclaringClass(new_class);
4520 }
4521 }
4522 }
4523}
4524
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004525bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4526 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004527 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004528 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004529
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004530 if (!LinkSuperClass(klass)) {
4531 return false;
4532 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004533 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4534 self, Runtime::Current()->GetImtUnimplementedMethod());
4535 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004536 return false;
4537 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004538 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004539 return false;
4540 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004541 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004542 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004543 return false;
4544 }
4545 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004546 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004547
4548 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4549 // We don't need to retire this class as it has no embedded tables or it was created the
4550 // correct size during class linker initialization.
4551 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4552
4553 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004554 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004555 }
4556
4557 // This will notify waiters on klass that saw the not yet resolved
4558 // class in the class_table_ during EnsureResolved.
4559 klass->SetStatus(mirror::Class::kStatusResolved, self);
4560 *new_class = klass.Get();
4561 } else {
4562 CHECK(!klass->IsResolved());
4563 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004564 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004565 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004566 CHECK(self->IsExceptionPending()); // Expect an OOME.
4567 klass->SetStatus(mirror::Class::kStatusError, self);
4568 return false;
4569 }
4570
4571 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4572 StackHandleScope<1> hs(self);
4573 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4574 ObjectLock<mirror::Class> lock(self, new_class_h);
4575
4576 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4577
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004578 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4579 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004580 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004581
4582 // This will notify waiters on temp class that saw the not yet resolved class in the
4583 // class_table_ during EnsureResolved.
4584 klass->SetStatus(mirror::Class::kStatusRetired, self);
4585
4586 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4587 // This will notify waiters on new_class that saw the not yet resolved
4588 // class in the class_table_ during EnsureResolved.
4589 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004590 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004591 return true;
4592}
4593
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004594bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004595 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004596 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4597 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004598 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004599 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004600 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004601 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004602 return false;
4603 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004604 // Verify
4605 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004606 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004607 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004608 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004609 return false;
4610 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004611 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004612 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004613 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004614 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004615 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004616 for (size_t i = 0; i < interfaces->Size(); i++) {
4617 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004618 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004619 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004620 DCHECK(Thread::Current()->IsExceptionPending());
4621 return false;
4622 }
4623 // Verify
4624 if (!klass->CanAccess(interface)) {
4625 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004626 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004627 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004628 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004629 return false;
4630 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004631 }
4632 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004633 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004634 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004635 return true;
4636}
4637
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004638bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004639 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004640 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004641 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004642 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004643 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004644 return false;
4645 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004646 return true;
4647 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004648 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004649 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4650 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004651 return false;
4652 }
4653 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004654 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004655 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004656 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004657 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004658 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004659 return false;
4660 }
4661 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004662 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004663 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004664 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004665 return false;
4666 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004667
Brian Carlstromf3632832014-05-20 15:36:53 -07004668 // Inherit kAccClassIsFinalizable from the superclass in case this
4669 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004670 if (super->IsFinalizable()) {
4671 klass->SetFinalizable();
4672 }
4673
Elliott Hughes2da50362011-10-10 16:57:08 -07004674 // Inherit reference flags (if any) from the superclass.
4675 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4676 if (reference_flags != 0) {
4677 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4678 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004679 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004680 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004681 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004682 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004683 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004684 return false;
4685 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004686
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004687 if (kIsDebugBuild) {
4688 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004689 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004690 CHECK(super->IsResolved());
4691 super = super->GetSuperClass();
4692 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004693 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004694 return true;
4695}
4696
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004697// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004698bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004699 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4700 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004701 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004702 if (klass->IsInterface()) {
4703 // No vtable.
4704 size_t count = klass->NumVirtualMethods();
4705 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004706 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004707 return false;
4708 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004709 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004710 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004711 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004712 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4713 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004714 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004715 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004716}
4717
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004718// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4719// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4720// caches in the implementation below.
4721class MethodNameAndSignatureComparator FINAL : public ValueObject {
4722 public:
4723 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4724 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4725 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4726 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004727 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4728 }
4729
4730 const char* GetName() {
4731 if (name_ == nullptr) {
4732 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4733 }
4734 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004735 }
4736
4737 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4738 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4739 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4740 const DexFile* other_dex_file = other->GetDexFile();
4741 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4742 if (dex_file_ == other_dex_file) {
4743 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4744 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004745 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004746 uint32_t other_name_len;
4747 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4748 &other_name_len);
4749 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4750 return false;
4751 }
4752 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4753 }
4754
4755 private:
4756 // Dex file for the method to compare against.
4757 const DexFile* const dex_file_;
4758 // MethodId for the method to compare against.
4759 const DexFile::MethodId* const mid_;
4760 // Lazily computed name from the dex file's strings.
4761 const char* name_;
4762 // Lazily computed name length.
4763 uint32_t name_len_;
4764};
4765
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004766class LinkVirtualHashTable {
4767 public:
4768 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4769 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4770 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4771 }
4772 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4773 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4774 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004775 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004776 uint32_t index = hash % hash_size_;
4777 // Linear probe until we have an empty slot.
4778 while (hash_table_[index] != invalid_index_) {
4779 if (++index == hash_size_) {
4780 index = 0;
4781 }
4782 }
4783 hash_table_[index] = virtual_method_index;
4784 }
4785 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4786 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4787 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004788 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004789 size_t index = hash % hash_size_;
4790 while (true) {
4791 const uint32_t value = hash_table_[index];
4792 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4793 // the block and can safely assume not found.
4794 if (value == invalid_index_) {
4795 break;
4796 }
4797 if (value != removed_index_) { // This signifies not already overriden.
4798 mirror::ArtMethod* virtual_method =
4799 klass_->GetVirtualMethodDuringLinking(value);
4800 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4801 hash_table_[index] = removed_index_;
4802 return value;
4803 }
4804 }
4805 if (++index == hash_size_) {
4806 index = 0;
4807 }
4808 }
4809 return GetNotFoundIndex();
4810 }
4811 static uint32_t GetNotFoundIndex() {
4812 return invalid_index_;
4813 }
4814
4815 private:
4816 static const uint32_t invalid_index_;
4817 static const uint32_t removed_index_;
4818
4819 Handle<mirror::Class> klass_;
4820 const size_t hash_size_;
4821 uint32_t* const hash_table_;
4822};
4823
4824const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4825const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4826
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004827bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004828 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004829 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004830 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4831 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004832 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004833 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004834 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004835 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4836 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4837 if (UNLIKELY(vtable.Get() == nullptr)) {
4838 CHECK(self->IsExceptionPending()); // OOME.
4839 return false;
4840 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004841 for (size_t i = 0; i < super_vtable_length; i++) {
4842 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004843 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004844 if (num_virtual_methods == 0) {
4845 klass->SetVTable(vtable.Get());
4846 return true;
4847 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004848 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004849 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4850 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4851 if (num_virtual_methods == 0) {
4852 klass->SetVTable(super_vtable);
4853 return true;
4854 }
4855 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004856 if (UNLIKELY(vtable.Get() == nullptr)) {
4857 CHECK(self->IsExceptionPending()); // OOME.
4858 return false;
4859 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004860 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004861 // How the algorithm works:
4862 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4863 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4864 // method which has not been matched to a vtable method, and j if the virtual method at the
4865 // index overrode the super virtual method at index j.
4866 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4867 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4868 // the need for the initial vtable which we later shrink back down).
4869 // 3. Add non overridden methods to the end of the vtable.
4870 static constexpr size_t kMaxStackHash = 250;
4871 const size_t hash_table_size = num_virtual_methods * 3;
4872 uint32_t* hash_table_ptr;
4873 std::unique_ptr<uint32_t[]> hash_heap_storage;
4874 if (hash_table_size <= kMaxStackHash) {
4875 hash_table_ptr = reinterpret_cast<uint32_t*>(
4876 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4877 } else {
4878 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4879 hash_table_ptr = hash_heap_storage.get();
4880 }
4881 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4882 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004883 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004884 hash_table.Add(i);
4885 }
4886 // Loop through each super vtable method and see if they are overriden by a method we added to
4887 // the hash table.
4888 for (size_t j = 0; j < super_vtable_length; ++j) {
4889 // Search the hash table to see if we are overidden by any method.
4890 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4891 MethodNameAndSignatureComparator super_method_name_comparator(
4892 super_method->GetInterfaceMethodIfProxy());
4893 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4894 if (hash_index != hash_table.GetNotFoundIndex()) {
4895 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4896 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4897 super_method->GetAccessFlags())) {
4898 if (super_method->IsFinal()) {
4899 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4900 PrettyMethod(virtual_method).c_str(),
4901 super_method->GetDeclaringClassDescriptor());
4902 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004903 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004904 vtable->SetWithoutChecks<false>(j, virtual_method);
4905 virtual_method->SetMethodIndex(j);
4906 } else {
4907 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004908 << " would have incorrectly overridden the package-private method in "
4909 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004910 }
4911 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004912 }
4913 // Add the non overridden methods at the end.
4914 size_t actual_count = super_vtable_length;
4915 for (size_t i = 0; i < num_virtual_methods; ++i) {
4916 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4917 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4918 if (method_idx < super_vtable_length &&
4919 local_method == vtable->GetWithoutChecks(method_idx)) {
4920 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004921 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004922 vtable->SetWithoutChecks<false>(actual_count, local_method);
4923 local_method->SetMethodIndex(actual_count);
4924 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004925 }
4926 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004927 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004928 return false;
4929 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004930 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004931 CHECK_LE(actual_count, max_count);
4932 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004933 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004934 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004935 CHECK(self->IsExceptionPending()); // OOME.
4936 return false;
4937 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004938 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004939 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004940 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004941 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004942 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004943 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4944 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004945 return false;
4946 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004947 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4948 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004949 CHECK(self->IsExceptionPending()); // OOME.
4950 return false;
4951 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004952 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004953 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004954 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004955 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004956 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004957 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004958 }
4959 return true;
4960}
4961
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004962bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4963 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4964 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004965 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004966 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004967 const bool has_superclass = klass->HasSuperClass();
4968 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4969 const bool have_interfaces = interfaces.Get() != nullptr;
4970 const size_t num_interfaces =
4971 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4972 if (num_interfaces == 0) {
4973 if (super_ifcount == 0) {
4974 // Class implements no interfaces.
4975 DCHECK_EQ(klass->GetIfTableCount(), 0);
4976 DCHECK(klass->GetIfTable() == nullptr);
4977 return true;
4978 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004979 // Class implements same interfaces as parent, are any of these not marker interfaces?
4980 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004981 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004982 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004983 if (super_iftable->GetMethodArrayCount(i) > 0) {
4984 has_non_marker_interface = true;
4985 break;
4986 }
4987 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004988 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004989 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004990 klass->SetIfTable(super_iftable);
4991 return true;
4992 }
4993 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004994 size_t ifcount = super_ifcount + num_interfaces;
4995 for (size_t i = 0; i < num_interfaces; i++) {
4996 mirror::Class* interface = have_interfaces ?
4997 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4998 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004999 if (UNLIKELY(!interface->IsInterface())) {
5000 std::string temp;
5001 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
5002 PrettyDescriptor(klass.Get()).c_str(),
5003 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
5004 return false;
5005 }
5006 ifcount += interface->GetIfTableCount();
5007 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005008 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005009 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005010 CHECK(self->IsExceptionPending()); // OOME.
5011 return false;
5012 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005013 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005014 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005015 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005016 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07005017 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005018 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005019 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005020 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005021 // Flatten the interface inheritance hierarchy.
5022 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005023 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07005024 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
5025 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005026 // Check if interface is already in iftable
5027 bool duplicate = false;
5028 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005029 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005030 if (existing_interface == interface) {
5031 duplicate = true;
5032 break;
5033 }
5034 }
5035 if (!duplicate) {
5036 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07005037 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005038 // Add this interface's non-duplicate super-interfaces.
5039 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005040 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005041 bool super_duplicate = false;
5042 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005043 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005044 if (existing_interface == super_interface) {
5045 super_duplicate = true;
5046 break;
5047 }
5048 }
5049 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005050 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005051 }
5052 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005053 }
5054 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005055 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08005056 // Shrink iftable in case duplicates were found
5057 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005058 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005059 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005060 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005061 CHECK(self->IsExceptionPending()); // OOME.
5062 return false;
5063 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08005064 ifcount = idx;
5065 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005066 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005067 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005068 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07005069 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07005070 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005071 return true;
5072 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005073 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005074 size_t max_miranda_methods = 0; // The max size of miranda_list.
5075 for (size_t i = 0; i < ifcount; ++i) {
5076 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
5077 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005078 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005079 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005080 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
5081 hs.NewHandle(klass->GetVTableDuringLinking()));
5082 // Copy the IMT from the super class if possible.
5083 bool extend_super_iftable = false;
5084 if (has_superclass) {
5085 mirror::Class* super_class = klass->GetSuperClass();
5086 extend_super_iftable = true;
5087 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5088 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5089 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
5090 }
5091 } else {
5092 // No imt in the super class, need to reconstruct from the iftable.
5093 mirror::IfTable* if_table = super_class->GetIfTable();
5094 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5095 const size_t length = super_class->GetIfTableCount();
5096 for (size_t i = 0; i < length; ++i) {
5097 mirror::Class* interface = iftable->GetInterface(i);
5098 const size_t num_virtuals = interface->NumVirtualMethods();
5099 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5100 DCHECK_EQ(num_virtuals, method_array_count);
5101 if (method_array_count == 0) {
5102 continue;
5103 }
5104 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5105 for (size_t j = 0; j < num_virtuals; ++j) {
5106 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5107 if (method->IsMiranda()) {
5108 continue;
5109 }
5110 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5111 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5112 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5113 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5114 out_imt->SetReference(imt_index, method);
5115 } else if (imt_ref != conflict_method) {
5116 out_imt->SetReference(imt_index, conflict_method);
5117 }
5118 }
5119 }
5120 }
5121 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005122 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005123 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005124 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005125 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005126 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005127 const bool is_super = i < super_ifcount;
5128 const bool super_interface = is_super && extend_super_iftable;
5129 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5130 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5131 if (super_interface) {
5132 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5133 DCHECK(if_table != nullptr);
5134 DCHECK(if_table->GetMethodArray(i) != nullptr);
5135 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005136 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005137 AsObjectArray<mirror::ArtMethod>());
5138 // We are overwriting a super class interface, try to only virtual methods instead of the
5139 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005140 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005141 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005142 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005143 // A new interface, we need the whole vtable incase a new interface method is implemented
5144 // in the whole superclass.
5145 input_array = vtable;
5146 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005147 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005148 CHECK(self->IsExceptionPending()); // OOME.
5149 return false;
5150 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005151 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005152 if (input_array.Get() == nullptr) {
5153 // If the added virtual methods is empty, do nothing.
5154 DCHECK(super_interface);
5155 continue;
5156 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005157 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005158 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005159 MethodNameAndSignatureComparator interface_name_comparator(
5160 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005161 int32_t k;
5162 // For each method listed in the interface's method list, find the
5163 // matching method in our class's method list. We want to favor the
5164 // subclass over the superclass, which just requires walking
5165 // back from the end of the vtable. (This only matters if the
5166 // superclass defines a private method and this class redefines
5167 // it -- otherwise it would use the same vtable slot. In .dex files
5168 // those don't end up in the virtual method table, so it shouldn't
5169 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005170 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5171 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005172 mirror::ArtMethod* vtable_method_for_name_comparison =
5173 vtable_method->GetInterfaceMethodIfProxy();
5174 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005175 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005176 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005177 ThrowIllegalAccessError(
5178 klass.Get(),
5179 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005180 PrettyMethod(vtable_method).c_str(),
5181 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005182 return false;
5183 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005184 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005185 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005186 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5187 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5188 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5189 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5190 out_imt->SetReference(imt_index, vtable_method);
5191 } else if (imt_ref != conflict_method) {
5192 // If we are not a conflict and we have the same signature and name as the imt entry,
5193 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005194 MethodNameAndSignatureComparator imt_ref_name_comparator(
5195 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005196 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005197 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005198 out_imt->SetReference(imt_index, vtable_method);
5199 } else {
5200 out_imt->SetReference(imt_index, conflict_method);
5201 }
Jeff Hao88474b42013-10-23 16:24:40 -07005202 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005203 break;
5204 }
5205 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005206 if (k < 0 && !super_interface) {
5207 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005208 for (size_t l = 0; l < miranda_list_size; ++l) {
5209 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005210 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005211 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005212 break;
5213 }
5214 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005215 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005216 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005217 miranda_method = interface_method->Clone(self)->AsArtMethod();
5218 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005219 CHECK(self->IsExceptionPending()); // OOME.
5220 return false;
5221 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005222 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005223 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005224 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005225 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005226 }
5227 }
5228 }
5229 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005230 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005231 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005232 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005233 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5234 if (old_method_count == 0) {
5235 virtuals = AllocArtMethodArray(self, new_method_count);
5236 } else {
5237 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5238 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005239 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005240 CHECK(self->IsExceptionPending()); // OOME.
5241 return false;
5242 }
5243 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005244
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005245 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005246 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005247 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005248 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005249 CHECK(self->IsExceptionPending()); // OOME.
5250 return false;
5251 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005252 for (size_t i = 0; i < miranda_list_size; ++i) {
5253 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005254 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005255 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5256 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5257 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005258 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005259 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005260 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005261 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005262 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005263
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005264 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005265 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5266 for (int i = 0; i < check_vtable->GetLength(); ++i) {
5267 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005268 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005269 }
5270
Ian Rogers7b078e82014-09-10 14:44:24 -07005271 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005272 return true;
5273}
5274
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005275bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005276 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005277 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005278}
5279
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005280bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005281 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005282 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005283}
5284
Brian Carlstromdbc05252011-09-09 01:59:59 -07005285struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005286 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5287 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005288 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005289 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005290 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005291 // 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 -07005292 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5293 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005294 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005295 if (type1 == Primitive::kPrimNot) {
5296 // Reference always goes first.
5297 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005298 }
Vladimir Markod5777482014-11-12 17:02:02 +00005299 if (type2 == Primitive::kPrimNot) {
5300 // Reference always goes first.
5301 return false;
5302 }
5303 size_t size1 = Primitive::ComponentSize(type1);
5304 size_t size2 = Primitive::ComponentSize(type2);
5305 if (size1 != size2) {
5306 // Larger primitive types go first.
5307 return size1 > size2;
5308 }
5309 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5310 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005311 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005312 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5313 // by name and for equal names by type id index.
5314 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5315 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005316 }
5317};
5318
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005319bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005320 size_t* class_size) {
5321 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005322 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005323 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005324
Brian Carlstromea46f952013-07-30 01:26:50 -07005325 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005326 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005327
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005328 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005329 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005330 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00005331 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005332 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005333 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005334 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005335 CHECK(super_class->IsResolved())
5336 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005337 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005338 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005339 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005340
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005341 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005342
Brian Carlstromdbc05252011-09-09 01:59:59 -07005343 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005344 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005345 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005346 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005347 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005348 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005349 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005350 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005351 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005352 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005353 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5354 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005355
Fred Shih381e4ca2014-08-25 17:24:27 -07005356 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005357 size_t current_field = 0;
5358 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005359 FieldGaps gaps;
5360
Brian Carlstromdbc05252011-09-09 01:59:59 -07005361 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005362 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005363 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005364 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005365 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005366 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005367 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005368 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5369 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005370 MemberOffset old_offset = field_offset;
5371 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5372 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5373 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005374 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005375 grouped_and_sorted_fields.pop_front();
5376 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005377 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005378 field_offset = MemberOffset(field_offset.Uint32Value() +
5379 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005380 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005381 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5382 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005383 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5384 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5385 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5386 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005387 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5388 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005389 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005390
Elliott Hughesadb460d2011-10-05 17:02:34 -07005391 // 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 -07005392 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005393 // We know there are no non-reference fields in the Reference classes, and we know
5394 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005395 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005396 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005397 --num_reference_fields;
5398 }
5399
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005400 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005401 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005402 if (is_static) {
5403 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005404 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005405 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005406 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005407 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08005408 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
5409 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
5410 } else {
5411 std::string temp;
5412 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5413 size_t previous_size = klass->GetObjectSize();
5414 if (previous_size != 0) {
5415 // Make sure that we didn't originally have an incorrect size.
5416 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5417 }
5418 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005419 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005420 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005421 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005422
5423 if (kIsDebugBuild) {
5424 // Make sure that the fields array is ordered by name but all reference
5425 // offsets are at the beginning as far as alignment allows.
5426 MemberOffset start_ref_offset = is_static
5427 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5428 : klass->GetFirstReferenceInstanceFieldOffset();
5429 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5430 num_reference_fields *
5431 sizeof(mirror::HeapReference<mirror::Object>));
5432 MemberOffset current_ref_offset = start_ref_offset;
5433 for (size_t i = 0; i < num_fields; i++) {
5434 mirror::ArtField* field = fields->Get(i);
5435 if ((false)) { // enable to debug field layout
5436 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5437 << " class=" << PrettyClass(klass.Get())
5438 << " field=" << PrettyField(field)
5439 << " offset="
5440 << field->GetField32(mirror::ArtField::OffsetOffset());
5441 }
5442 if (i != 0) {
5443 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005444 // NOTE: The field names can be the same. This is not possible in the Java language
5445 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5446 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005447 }
5448 Primitive::Type type = field->GetTypeAsPrimitiveType();
5449 bool is_primitive = type != Primitive::kPrimNot;
5450 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5451 strcmp("referent", field->GetName()) == 0) {
5452 is_primitive = true; // We lied above, so we have to expect a lie here.
5453 }
5454 MemberOffset offset = field->GetOffsetDuringLinking();
5455 if (is_primitive) {
5456 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5457 // Shuffled before references.
5458 size_t type_size = Primitive::ComponentSize(type);
5459 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5460 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5461 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5462 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5463 }
5464 } else {
5465 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5466 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5467 sizeof(mirror::HeapReference<mirror::Object>));
5468 }
5469 }
5470 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5471 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005472 return true;
5473}
5474
Vladimir Marko76649e82014-11-10 18:32:59 +00005475// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005476void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005477 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005478 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005479 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005480 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005481 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005482 // Compute reference offsets unless our superclass overflowed.
5483 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5484 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005485 if (num_reference_fields != 0u) {
5486 // All of the fields that contain object references are guaranteed be grouped in memory
5487 // starting at an appropriately aligned address after super class object data.
5488 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5489 sizeof(mirror::HeapReference<mirror::Object>));
5490 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005491 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005492 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005493 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005494 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005495 reference_offsets |= (0xffffffffu << start_bit) &
5496 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005497 }
5498 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005499 }
5500 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005501 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005502}
5503
Mathieu Chartier590fee92013-09-13 13:46:47 -07005504mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005505 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005506 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005507 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005508 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005509 return resolved;
5510 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005511 uint32_t utf16_length;
5512 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005513 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005514 dex_cache->SetResolvedString(string_idx, string);
5515 return string;
5516}
5517
Mathieu Chartier590fee92013-09-13 13:46:47 -07005518mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005519 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005520 StackHandleScope<2> hs(Thread::Current());
5521 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5522 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005523 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5524}
5525
5526mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005527 Handle<mirror::DexCache> dex_cache,
5528 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005529 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005530 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005531 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005532 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005533 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005534 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005535 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005536 // TODO: we used to throw here if resolved's class loader was not the
5537 // boot class loader. This was to permit different classes with the
5538 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005539 dex_cache->SetResolvedType(type_idx, resolved);
5540 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005541 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005542 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005543 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005544 StackHandleScope<1> hs(self);
5545 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005546 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005547 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005548 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005549 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005550 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005551 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005552 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005553 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005554 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005555 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005556 return resolved;
5557}
5558
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005559mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005560 Handle<mirror::DexCache> dex_cache,
5561 Handle<mirror::ClassLoader> class_loader,
5562 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005563 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005564 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005565 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005566 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005567 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005568 return resolved;
5569 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005570 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005571 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005572 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005573 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005574 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005575 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005576 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005577 // Scan using method_idx, this saves string compares but will only hit for matching dex
5578 // caches/files.
5579 switch (type) {
5580 case kDirect: // Fall-through.
5581 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005582 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005583 break;
5584 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005585 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005586 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005587 break;
5588 case kSuper: // Fall-through.
5589 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005590 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005591 break;
5592 default:
5593 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005594 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005595 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005596 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005597 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005598 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005599 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005600 switch (type) {
5601 case kDirect: // Fall-through.
5602 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005603 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005604 break;
5605 case kInterface:
5606 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005607 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005608 break;
5609 case kSuper: // Fall-through.
5610 case kVirtual:
5611 resolved = klass->FindVirtualMethod(name, signature);
5612 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005613 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005614 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005615 // If we found a method, check for incompatible class changes.
5616 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005617 // Be a good citizen and update the dex cache to speed subsequent calls.
5618 dex_cache->SetResolvedMethod(method_idx, resolved);
5619 return resolved;
5620 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005621 // If we had a method, it's an incompatible-class-change error.
5622 if (resolved != nullptr) {
5623 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5624 } else {
5625 // We failed to find the method which means either an access error, an incompatible class
5626 // change, or no such method. First try to find the method among direct and virtual methods.
5627 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5628 const Signature signature = dex_file.GetMethodSignature(method_id);
5629 switch (type) {
5630 case kDirect:
5631 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005632 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005633 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5634 // have had a resolved method before, which triggers the "true" branch above.
5635 break;
5636 case kInterface:
5637 case kVirtual:
5638 case kSuper:
5639 resolved = klass->FindDirectMethod(name, signature);
5640 break;
5641 }
5642
5643 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005644 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005645 if (resolved != nullptr && referrer.Get() != nullptr) {
5646 mirror::Class* methods_class = resolved->GetDeclaringClass();
5647 mirror::Class* referring_class = referrer->GetDeclaringClass();
5648 if (!referring_class->CanAccess(methods_class)) {
5649 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5650 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005651 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005652 } else if (!referring_class->CanAccessMember(methods_class,
5653 resolved->GetAccessFlags())) {
5654 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005655 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005656 }
5657 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005658 if (!exception_generated) {
5659 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5660 // interface methods and throw if we find the method there. If we find nothing, throw a
5661 // NoSuchMethodError.
5662 switch (type) {
5663 case kDirect:
5664 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005665 if (resolved != nullptr) {
5666 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5667 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005668 resolved = klass->FindInterfaceMethod(name, signature);
5669 if (resolved != nullptr) {
5670 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5671 } else {
5672 ThrowNoSuchMethodError(type, klass, name, signature);
5673 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005674 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005675 break;
5676 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005677 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005678 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5679 } else {
5680 resolved = klass->FindVirtualMethod(name, signature);
5681 if (resolved != nullptr) {
5682 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5683 } else {
5684 ThrowNoSuchMethodError(type, klass, name, signature);
5685 }
5686 }
5687 break;
5688 case kSuper:
5689 if (resolved != nullptr) {
5690 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005691 } else {
5692 ThrowNoSuchMethodError(type, klass, name, signature);
5693 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005694 break;
5695 case kVirtual:
5696 if (resolved != nullptr) {
5697 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5698 } else {
5699 resolved = klass->FindInterfaceMethod(name, signature);
5700 if (resolved != nullptr) {
5701 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5702 } else {
5703 ThrowNoSuchMethodError(type, klass, name, signature);
5704 }
5705 }
5706 break;
5707 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005708 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005709 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005710 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005711 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005712 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005713}
5714
Mathieu Chartier590fee92013-09-13 13:46:47 -07005715mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005716 Handle<mirror::DexCache> dex_cache,
5717 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005718 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005719 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005720 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005721 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005722 return resolved;
5723 }
5724 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005725 Thread* const self = Thread::Current();
5726 StackHandleScope<1> hs(self);
5727 Handle<mirror::Class> klass(
5728 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005729 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005730 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005731 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005732 }
5733
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005734 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005735 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005736 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005737 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005738 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005739
Andreas Gampe58a5af82014-07-31 16:23:49 -07005740 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005741 const char* name = dex_file.GetFieldName(field_id);
5742 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5743 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005744 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005745 } else {
5746 resolved = klass->FindInstanceField(name, type);
5747 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005748 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005749 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005750 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005751 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005752 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005753 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005754 return resolved;
5755}
5756
Brian Carlstromea46f952013-07-30 01:26:50 -07005757mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005758 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005759 Handle<mirror::DexCache> dex_cache,
5760 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005761 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005762 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005763 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005764 return resolved;
5765 }
5766 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005767 Thread* self = Thread::Current();
5768 StackHandleScope<1> hs(self);
5769 Handle<mirror::Class> klass(
5770 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005771 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005772 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005773 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005774 }
5775
Ian Rogersdfb325e2013-10-30 01:00:44 -07005776 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5777 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005778 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005779 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005780 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005781 dex_cache->SetResolvedField(field_idx, resolved);
5782 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005783 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005784 }
5785 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005786}
5787
Brian Carlstromea46f952013-07-30 01:26:50 -07005788const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005789 uint32_t* length) {
5790 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5791 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005792 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005793 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005794 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005795}
5796
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005797void ClassLinker::DumpAllClasses(int flags) {
5798 if (dex_cache_image_class_lookup_required_) {
5799 MoveImageClassesToClassTable();
5800 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005801 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5802 // 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 -08005803 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005804 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005805 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005806 for (GcRoot<mirror::Class>& it : class_table_) {
5807 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005808 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005809 }
5810
5811 for (size_t i = 0; i < all_classes.size(); ++i) {
5812 all_classes[i]->DumpClass(std::cerr, flags);
5813 }
5814}
5815
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005816static OatFile::OatMethod CreateOatMethod(const void* code, bool is_portable) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005817 CHECK_EQ(kUsePortableCompiler, is_portable);
5818 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005819 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5820 base -= sizeof(void*); // Move backward so that code_offset != 0.
5821 const uint32_t code_offset = sizeof(void*);
5822 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005823}
5824
5825bool ClassLinker::IsPortableResolutionStub(const void* entry_point) const {
5826 return (entry_point == GetPortableResolutionStub()) ||
5827 (portable_resolution_trampoline_ == entry_point);
5828}
5829
5830bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5831 return (entry_point == GetQuickResolutionStub()) ||
5832 (quick_resolution_trampoline_ == entry_point);
5833}
5834
5835bool ClassLinker::IsPortableToInterpreterBridge(const void* entry_point) const {
5836 return (entry_point == GetPortableToInterpreterBridge());
5837 // TODO: portable_to_interpreter_bridge_trampoline_ == entry_point;
5838}
5839
5840bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5841 return (entry_point == GetQuickToInterpreterBridge()) ||
5842 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5843}
5844
5845bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5846 return (entry_point == GetQuickGenericJniStub()) ||
5847 (quick_generic_jni_trampoline_ == entry_point);
5848}
5849
5850const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5851 return GetQuickGenericJniStub();
5852}
5853
5854void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method, const void* method_code,
5855 bool is_portable) const {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005856 OatFile::OatMethod oat_method = CreateOatMethod(method_code, is_portable);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005857 oat_method.LinkMethod(method);
5858 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5859 // Create bridges to transition between different kinds of compiled bridge.
5860 if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
5861 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5862 } else {
5863 CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
5864 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
5865 method->SetIsPortableCompiled();
5866 }
5867}
5868
5869void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5870 if (!method->IsNative()) {
5871 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
5872 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
5873 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5874 } else {
5875 const void* quick_method_code = GetQuickGenericJniStub();
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005876 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code, false);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005877 oat_method.LinkMethod(method);
5878 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5879 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5880 }
5881}
5882
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005883void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005884 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005885 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005886 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005887 MoveImageClassesToClassTable();
5888 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005889 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005890 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5891 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005892}
5893
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005894size_t ClassLinker::NumLoadedClasses() {
5895 if (dex_cache_image_class_lookup_required_) {
5896 MoveImageClassesToClassTable();
5897 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005898 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005899 // Only return non zygote classes since these are the ones which apps which care about.
5900 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005901}
5902
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005903pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005904 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005905}
5906
5907pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005908 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005909}
5910
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005911void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005912 DCHECK(!init_done_);
5913
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005914 DCHECK(klass != nullptr);
5915 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005916
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005917 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005918 DCHECK(class_roots != nullptr);
5919 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005920 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005921}
5922
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005923const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5924 static const char* class_roots_descriptors[] = {
5925 "Ljava/lang/Class;",
5926 "Ljava/lang/Object;",
5927 "[Ljava/lang/Class;",
5928 "[Ljava/lang/Object;",
5929 "Ljava/lang/String;",
5930 "Ljava/lang/DexCache;",
5931 "Ljava/lang/ref/Reference;",
5932 "Ljava/lang/reflect/ArtField;",
5933 "Ljava/lang/reflect/ArtMethod;",
5934 "Ljava/lang/reflect/Proxy;",
5935 "[Ljava/lang/String;",
5936 "[Ljava/lang/reflect/ArtField;",
5937 "[Ljava/lang/reflect/ArtMethod;",
5938 "Ljava/lang/ClassLoader;",
5939 "Ljava/lang/Throwable;",
5940 "Ljava/lang/ClassNotFoundException;",
5941 "Ljava/lang/StackTraceElement;",
5942 "Z",
5943 "B",
5944 "C",
5945 "D",
5946 "F",
5947 "I",
5948 "J",
5949 "S",
5950 "V",
5951 "[Z",
5952 "[B",
5953 "[C",
5954 "[D",
5955 "[F",
5956 "[I",
5957 "[J",
5958 "[S",
5959 "[Ljava/lang/StackTraceElement;",
5960 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005961 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5962 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005963
5964 const char* descriptor = class_roots_descriptors[class_root];
5965 CHECK(descriptor != nullptr);
5966 return descriptor;
5967}
5968
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005969std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5970 const {
5971 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005972 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005973}
5974
5975bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5976 const GcRoot<mirror::Class>& b) {
5977 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5978 return false;
5979 }
5980 std::string temp;
5981 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5982}
5983
5984std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5985 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005986 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005987}
5988
5989bool ClassLinker::ClassDescriptorHashEquals::operator()(
5990 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
5991 if (a.Read()->GetClassLoader() != b.second) {
5992 return false;
5993 }
5994 return a.Read()->DescriptorEquals(b.first);
5995}
5996
5997bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5998 const char* descriptor) {
5999 return a.Read()->DescriptorEquals(descriptor);
6000}
6001
6002std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006003 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006004}
6005
Sebastien Hertz6963e442014-11-26 22:11:27 +01006006bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
6007 // Non-image methods don't use direct code pointer.
6008 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
6009 return false;
6010 }
6011 if (m->IsPrivate()) {
6012 // The method can only be called inside its own oat file. Therefore it won't be called using
6013 // its direct code if the oat file has been compiled in PIC mode.
6014 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
6015 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
6016 const OatFile::OatDexFile* oat_dex_file = class_linker->FindOpenedOatDexFileForDexFile(dex_file);
6017 if (oat_dex_file == nullptr) {
6018 // No oat file: the method has not been compiled.
6019 return false;
6020 }
6021 const OatFile* oat_file = oat_dex_file->GetOatFile();
6022 return oat_file != nullptr && !oat_file->IsPic();
6023 } else {
6024 // The method can be called outside its own oat file. Therefore it won't be called using its
6025 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
6026 ReaderMutexLock mu(Thread::Current(), dex_lock_);
6027 for (const OatFile* oat_file : oat_files_) {
6028 if (!oat_file->IsPic()) {
6029 return true;
6030 }
6031 }
6032 return false;
6033 }
6034}
6035
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006036} // namespace art