blob: d119a56da32ce0fd644ccdb8cde3ae5297b56e38 [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 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800242 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100243 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800244 quick_to_interpreter_bridge_trampoline_(nullptr),
245 image_pointer_size_(sizeof(void*)) {
Ian Rogers98379392014-02-24 16:53:16 -0800246 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700247}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700248
Alex Light64ad14d2014-08-19 14:23:13 -0700249void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800250 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700251 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700252
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700253 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700254
Elliott Hughes30646832011-10-13 16:59:46 -0700255 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700256 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700257 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700258 // 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 -0800259 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700260 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
261 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700262 heap->AllocNonMovableObject<true>(self, nullptr,
263 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700264 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700265 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700266 mirror::Class::SetClassClass(java_lang_Class.Get());
267 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700268 if (kUseBakerOrBrooksReadBarrier) {
269 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800270 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700271 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700272 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800273 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800274 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700275
Elliott Hughes418d20f2011-09-22 14:00:39 -0700276 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700277 Handle<mirror::Class> class_array_class(hs.NewHandle(
278 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700279 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700280
Ian Rogers23435d02012-09-24 11:23:12 -0700281 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700282 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
283 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700284 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700285 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700286 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700287 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700288
Ian Rogers23435d02012-09-24 11:23:12 -0700289 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700290 Handle<mirror::Class> object_array_class(hs.NewHandle(
291 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700292 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700293
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700294 // Setup the char (primitive) class to be used for char[].
295 Handle<mirror::Class> char_class(hs.NewHandle(
296 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700297 // The primitive char class won't be initialized by
298 // InitializePrimitiveClass until line 459, but strings (and
299 // internal char arrays) will be allocated before that and the
300 // component size, which is computed from the primitive type, needs
301 // to be set here.
302 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700303
Ian Rogers23435d02012-09-24 11:23:12 -0700304 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700305 Handle<mirror::Class> char_array_class(hs.NewHandle(
306 AllocClass(self, java_lang_Class.Get(),
307 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700308 char_array_class->SetComponentType(char_class.Get());
309 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700310
Ian Rogers23435d02012-09-24 11:23:12 -0700311 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700312 Handle<mirror::Class> java_lang_String(hs.NewHandle(
313 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700314 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700315 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700316 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400317
Fred Shih4ee7a662014-07-11 09:59:27 -0700318 // Setup Reference.
319 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
320 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
321 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
322 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
323 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
324
Ian Rogers23435d02012-09-24 11:23:12 -0700325 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700326 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
327 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
328 kClassRootsMax));
329 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700330 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
331 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
332 SetClassRoot(kClassArrayClass, class_array_class.Get());
333 SetClassRoot(kObjectArrayClass, object_array_class.Get());
334 SetClassRoot(kCharArrayClass, char_array_class.Get());
335 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700336 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700337
338 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700339 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
340 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
341 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
342 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
343 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
344 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
345 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
346 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700347
Ian Rogers23435d02012-09-24 11:23:12 -0700348 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700349 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700350
Ian Rogers23435d02012-09-24 11:23:12 -0700351 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700352 Handle<mirror::Class> int_array_class(hs.NewHandle(
353 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700354 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700355 mirror::IntArray::SetArrayClass(int_array_class.Get());
356 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700357
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700358 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700359
Ian Rogers52813c92012-10-11 11:50:38 -0700360 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700361 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
362 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700363 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700364 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700365 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700366
Brian Carlstromf3632832014-05-20 15:36:53 -0700367 // Constructor, Field, Method, and AbstractMethod are necessary so
368 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700369 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
370 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700371 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700372 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700373 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700374 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700375 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700376
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700377 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
378 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700379 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800380 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700381 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700382 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700383 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700384
385 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700386 Handle<mirror::Class> object_array_string(hs.NewHandle(
387 AllocClass(self, java_lang_Class.Get(),
388 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700389 object_array_string->SetComponentType(java_lang_String.Get());
390 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700391
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700392 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
393 AllocClass(self, java_lang_Class.Get(),
394 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700395 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
396 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700397
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700398 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
399 AllocClass(self, java_lang_Class.Get(),
400 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700401 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
402 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700403
Ian Rogers23435d02012-09-24 11:23:12 -0700404 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
405 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
406 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700407 CHECK_NE(0U, boot_class_path.size());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800408 for (const DexFile* dex_file : boot_class_path) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700409 CHECK(dex_file != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700410 AppendToBootClassPath(self, *dex_file);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700411 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700412
413 // now we can use FindSystemClass
414
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700415 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700416 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
417 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700418
Jeff Hao88474b42013-10-23 16:24:40 -0700419 // Create runtime resolution and imt conflict methods. Also setup the default imt.
420 Runtime* runtime = Runtime::Current();
421 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
422 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700423 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700424 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
425
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700426 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
427 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700428 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Alex Light64ad14d2014-08-19 14:23:13 -0700429 if (!runtime->IsCompiler()) {
430 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700431 quick_resolution_trampoline_ = GetQuickResolutionStub();
432 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
433 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700434 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700435
Mathieu Chartier66f19252012-09-18 08:57:04 -0700436 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700437 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800438 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700439 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700440 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700441 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800442 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700443 std::ostringstream os1, os2;
444 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
445 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
446 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
447 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700448 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800449 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700450 CHECK_EQ(java_lang_String.Get(), String_class);
451 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700452 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700453
Ian Rogers23435d02012-09-24 11:23:12 -0700454 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800455 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800456 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700457
Ian Rogers98379392014-02-24 16:53:16 -0800458 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800459 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700460
Ian Rogers98379392014-02-24 16:53:16 -0800461 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700462 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700463
Ian Rogers98379392014-02-24 16:53:16 -0800464 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800465 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700466
Ian Rogers98379392014-02-24 16:53:16 -0800467 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700468 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700469
Ian Rogers98379392014-02-24 16:53:16 -0800470 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800471 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700472
Ian Rogers98379392014-02-24 16:53:16 -0800473 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800474 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700475
Ian Rogers98379392014-02-24 16:53:16 -0800476 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800477 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700478
Ian Rogers98379392014-02-24 16:53:16 -0800479 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700480 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700481
Ian Rogers98379392014-02-24 16:53:16 -0800482 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700483 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700484
Ian Rogers23435d02012-09-24 11:23:12 -0700485 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800486 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700487 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800488 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700489 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700490 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
491 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700492 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700493 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700494 array_iftable->SetInterface(0, java_lang_Cloneable);
495 array_iftable->SetInterface(1, java_io_Serializable);
496 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700497
Ian Rogers23435d02012-09-24 11:23:12 -0700498 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700499 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
500 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
501 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
502 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700503 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700504 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800505 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700506 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700507
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700508 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800509 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700510 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700511
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700512 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800513 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700514 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700515
Brian Carlstromf3632832014-05-20 15:36:53 -0700516 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700517 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700518 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700519
Brian Carlstromea46f952013-07-30 01:26:50 -0700520 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700521 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700522 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700523
Brian Carlstromea46f952013-07-30 01:26:50 -0700524 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700525 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700526 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700527
Ian Rogers23435d02012-09-24 11:23:12 -0700528 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700529
Ian Rogers23435d02012-09-24 11:23:12 -0700530 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800531 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700532 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
533
Brian Carlstrom1f870082011-08-23 16:02:11 -0700534 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700535 // finish initializing Reference class
536 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
537 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
538 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
539 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
540 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700541 mirror::Class* java_lang_ref_FinalizerReference =
542 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700543 java_lang_ref_FinalizerReference->SetAccessFlags(
544 java_lang_ref_FinalizerReference->GetAccessFlags() |
545 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700546 mirror::Class* java_lang_ref_PhantomReference =
547 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700548 java_lang_ref_PhantomReference->SetAccessFlags(
549 java_lang_ref_PhantomReference->GetAccessFlags() |
550 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700551 mirror::Class* java_lang_ref_SoftReference =
552 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700553 java_lang_ref_SoftReference->SetAccessFlags(
554 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700555 mirror::Class* java_lang_ref_WeakReference =
556 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700557 java_lang_ref_WeakReference->SetAccessFlags(
558 java_lang_ref_WeakReference->GetAccessFlags() |
559 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700560
Ian Rogers23435d02012-09-24 11:23:12 -0700561 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800562 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700563 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700564 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
565
jeffhao8cd6dda2012-02-22 10:15:34 -0800566 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700567 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800568 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800569 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700570 SetClassRoot(kJavaLangClassNotFoundException,
571 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800572 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700573 SetClassRoot(kJavaLangStackTraceElementArrayClass,
574 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800575 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700576
Andreas Gampe76bd8802014-12-10 16:43:58 -0800577 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
578 // initialized.
579 {
580 const DexFile& dex_file = java_lang_Object->GetDexFile();
581 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
582 CHECK(void_string_id != nullptr);
583 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
584 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
585 CHECK(void_type_id != nullptr);
586 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
587 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
588 // as referrer so the used dex cache is core's one.
589 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
590 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
591 self->AssertNoPendingException();
592 }
593
Ian Rogers98379392014-02-24 16:53:16 -0800594 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700595
Brian Carlstroma004aa92012-02-08 18:05:09 -0800596 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700597}
598
Ian Rogers98379392014-02-24 16:53:16 -0800599void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800600 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700601
602 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700603 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700604 // as the types of the field can't be resolved prior to the runtime being
605 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800606 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700607 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800608 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800609
Brian Carlstromea46f952013-07-30 01:26:50 -0700610 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700611 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
612 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700613
Brian Carlstromea46f952013-07-30 01:26:50 -0700614 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700615 CHECK_STREQ(queue->GetName(), "queue");
616 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700617
Brian Carlstromea46f952013-07-30 01:26:50 -0700618 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700619 CHECK_STREQ(queueNext->GetName(), "queueNext");
620 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700621
Brian Carlstromea46f952013-07-30 01:26:50 -0700622 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700623 CHECK_STREQ(referent->GetName(), "referent");
624 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700625
Brian Carlstromea46f952013-07-30 01:26:50 -0700626 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700627 CHECK_STREQ(zombie->GetName(), "zombie");
628 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700629
Brian Carlstroma663ea52011-08-19 23:33:41 -0700630 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700631 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700632 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800633 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700634 CHECK(klass != nullptr);
635 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700636 // note SetClassRoot does additional validation.
637 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700638 }
639
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700640 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700641
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700642 // disable the slow paths in FindClass and CreatePrimitiveClass now
643 // that Object, Class, and Object[] are setup
644 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700645
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800646 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700647}
648
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700649void ClassLinker::RunRootClinits() {
650 Thread* self = Thread::Current();
651 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800652 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700653 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700654 StackHandleScope<1> hs(self);
655 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700656 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700657 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700658 }
659 }
660}
661
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700662bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800663 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000664 const char* oat_cache_filename,
665 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700666 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700667 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800668
Ian Rogers1d54e732013-05-02 21:10:01 -0700669 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800670 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700671 if (heap->GetImageSpace() == nullptr) {
672 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
673 // out of space anyway it might not matter.
674 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
675 "without an image.", dex_filename);
676 return false;
677 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700678 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800679
Brian Carlstrom6449c622014-02-10 23:48:36 -0800680 std::string dex_file_option("--dex-file=");
681 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800682
Brian Carlstrom6449c622014-02-10 23:48:36 -0800683 std::string oat_fd_option("--oat-fd=");
684 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800685
Brian Carlstrom6449c622014-02-10 23:48:36 -0800686 std::string oat_location_option("--oat-location=");
687 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800688
Brian Carlstrom6449c622014-02-10 23:48:36 -0800689 std::vector<std::string> argv;
690 argv.push_back(dex2oat);
691 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800692 argv.push_back("-classpath");
693 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800694 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800695
Ian Rogers8afeb852014-04-02 14:55:49 -0700696 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800697
Jeff Hao4a200f52014-04-01 14:58:49 -0700698 if (!Runtime::Current()->IsVerificationEnabled()) {
699 argv.push_back("--compiler-filter=verify-none");
700 }
701
Alex Light6e183f22014-07-18 14:57:04 -0700702 if (Runtime::Current()->MustRelocateIfPossible()) {
703 argv.push_back("--runtime-arg");
704 argv.push_back("-Xrelocate");
705 } else {
706 argv.push_back("--runtime-arg");
707 argv.push_back("-Xnorelocate");
708 }
709
Brian Carlstrom6449c622014-02-10 23:48:36 -0800710 if (!kIsTargetBuild) {
711 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700712 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700713
Brian Carlstrom6449c622014-02-10 23:48:36 -0800714 argv.push_back(boot_image_option);
715 argv.push_back(dex_file_option);
716 argv.push_back(oat_fd_option);
717 argv.push_back(oat_location_option);
718 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800719 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800720 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700721 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800722
Andreas Gampea696c0a2014-12-10 20:51:45 -0800723 if (!Exec(argv, error_msg)) {
724 // Manually delete the file. Ensures there is no garbage left over if the process unexpectedly
725 // died. Ignore unlink failure, propagate the original error.
726 TEMP_FAILURE_RETRY(unlink(oat_cache_filename));
727 return false;
728 }
729
730 return true;
jeffhao262bf462011-10-20 18:36:32 -0700731}
732
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700733const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700734 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800735 if (kIsDebugBuild) {
736 for (size_t i = 0; i < oat_files_.size(); ++i) {
737 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700738 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800739 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700740 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
741 oat_files_.push_back(oat_file);
742 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800743}
744
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700745OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
746 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700747 OatFile* oat_file = space->ReleaseOatFile();
748 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700749 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700750 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700751}
752
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100753const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800754 const char* dex_location = dex_file.GetLocation().c_str();
755 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100756 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800757}
758
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100759const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
760 const char* dex_location,
761 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700762 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100763 for (const OatFile* oat_file : oat_files_) {
764 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700765
766 if (oat_location != nullptr) {
767 if (oat_file->GetLocation() != oat_location) {
768 continue;
769 }
770 }
771
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700772 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800773 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700774 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100775 if (oat_dex_file != nullptr) {
776 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800777 }
778 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100779 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800780}
781
Calin Juravle621962a2014-09-02 15:53:55 +0100782
783// Loads all multi dex files from the given oat file returning true on success.
784//
785// Parameters:
786// oat_file - the oat file to load from
787// dex_location - the dex location used to generate the oat file
788// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
789// generated - whether or not the oat_file existed before or was just (re)generated
790// error_msgs - any error messages will be appended here
791// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
792static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
793 const char* dex_location,
794 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700795 bool generated,
796 std::vector<std::string>* error_msgs,
797 std::vector<const DexFile*>* dex_files) {
798 if (oat_file == nullptr) {
799 return false;
800 }
801
802 size_t old_size = dex_files->size(); // To rollback on error.
803
804 bool success = true;
805 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100806 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700807 const char* next_name = next_name_str.c_str();
808
Calin Juravle621962a2014-09-02 15:53:55 +0100809 uint32_t next_location_checksum;
810 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700811 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100812 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
813 // When i=0 the multidex name should be the same as the location name. We already have the
814 // checksum it so we don't need to recompute it.
815 if (dex_location_checksum == nullptr) {
816 next_location_checksum_pointer = nullptr;
817 } else {
818 next_location_checksum = *dex_location_checksum;
819 }
820 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700821 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100822 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700823 }
824
825 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
826
827 if (oat_dex_file == nullptr) {
828 if (i == 0 && generated) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700829 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100830 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700831 oat_file->GetLocation().c_str());
832 error_msgs->push_back(error_msg);
833 }
834 break; // Not found, done.
835 }
836
837 // Checksum test. Test must succeed when generated.
838 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100839 if (next_location_checksum_pointer != nullptr) {
840 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700841 }
842
843 if (success) {
844 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
845 if (dex_file == nullptr) {
846 success = false;
847 error_msgs->push_back(error_msg);
848 } else {
849 dex_files->push_back(dex_file);
850 }
851 }
852
853 // When we generated the file, we expect success, or something is terribly wrong.
854 CHECK_EQ(false, generated && !success)
855 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100856 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700857 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
858 }
859
860 if (dex_files->size() == old_size) {
861 success = false; // We did not even find classes.dex
862 }
863
864 if (success) {
865 return true;
866 } else {
867 // Free all the dex files we have loaded.
868 auto it = dex_files->begin() + old_size;
869 auto it_end = dex_files->end();
870 for (; it != it_end; it++) {
871 delete *it;
872 }
873 dex_files->erase(dex_files->begin() + old_size, it_end);
874
875 return false;
876 }
877}
878
879// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
880// complicates the loading process, as we should not use an iterative loading process, because that
881// would register the oat file and dex files that come before the broken one. Instead, check all
882// multidex ahead of time.
883bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
884 std::vector<std::string>* error_msgs,
885 std::vector<const DexFile*>* dex_files) {
886 // 1) Check whether we have an open oat file.
887 // This requires a dex checksum, use the "primary" one.
888 uint32_t dex_location_checksum;
889 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
890 bool have_checksum = true;
891 std::string checksum_error_msg;
892 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100893 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700894 dex_location_checksum_pointer = nullptr;
895 have_checksum = false;
896 }
897
898 bool needs_registering = false;
899
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100900 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
901 dex_location_checksum_pointer);
902 std::unique_ptr<const OatFile> open_oat_file(
903 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700904
905 // 2) If we do not have an open one, maybe there's one on disk already.
906
907 // In case the oat file is not open, we play a locking game here so
908 // that if two different processes race to load and register or generate
909 // (or worse, one tries to open a partial generated file) we will be okay.
910 // This is actually common with apps that use DexClassLoader to work
911 // around the dex method reference limit and that have a background
912 // service running in a separate process.
913 ScopedFlock scoped_flock;
914
915 if (open_oat_file.get() == nullptr) {
916 if (oat_location != nullptr) {
917 // Can only do this if we have a checksum, else error.
918 if (!have_checksum) {
919 error_msgs->push_back(checksum_error_msg);
920 return false;
921 }
922
923 std::string error_msg;
924
925 // We are loading or creating one in the future. Time to set up the file lock.
926 if (!scoped_flock.Init(oat_location, &error_msg)) {
927 error_msgs->push_back(error_msg);
928 return false;
929 }
930
Alex Lighta59dd802014-07-02 16:28:08 -0700931 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700932 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
933 oat_location, &error_msg));
934
935 if (open_oat_file.get() == nullptr) {
936 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
937 dex_location, oat_location, error_msg.c_str());
938 VLOG(class_linker) << compound_msg;
939 error_msgs->push_back(compound_msg);
940 }
941 } else {
942 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100943 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700944 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
945 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100946 kRuntimeISA, error_msgs,
947 &obsolete_file_cleanup_failed));
948 // There's no point in going forward and eventually try to regenerate the
949 // file if we couldn't remove the obsolete one. Mostly likely we will fail
950 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100951 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
952 if (obsolete_file_cleanup_failed) {
953 return false;
954 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700955 }
956 needs_registering = true;
957 }
958
959 // 3) If we have an oat file, check all contained multidex files for our dex_location.
960 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100961 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
962 dex_location_checksum_pointer,
963 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700964 if (success) {
965 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
966 if (needs_registering) {
967 // We opened the oat file, so we must register it.
968 RegisterOatFile(oat_file);
969 }
Alex Light9dcc4572014-08-14 14:16:26 -0700970 // If the file isn't executable we failed patchoat but did manage to get the dex files.
971 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700972 } else {
973 if (needs_registering) {
974 // We opened it, delete it.
975 open_oat_file.reset();
976 } else {
977 open_oat_file.release(); // Do not delete open oat files.
978 }
979 }
980
981 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
982
983 // Need a checksum, fail else.
984 if (!have_checksum) {
985 error_msgs->push_back(checksum_error_msg);
986 return false;
987 }
988
989 // Look in cache location if no oat_location is given.
990 std::string cache_location;
991 if (oat_location == nullptr) {
992 // Use the dalvik cache.
993 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
994 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
995 oat_location = cache_location.c_str();
996 }
997
Alex Light64ad14d2014-08-19 14:23:13 -0700998 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700999 // Definitely need to lock now.
1000 if (!scoped_flock.HasFile()) {
1001 std::string error_msg;
1002 if (!scoped_flock.Init(oat_location, &error_msg)) {
1003 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -07001004 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -07001005 }
1006 }
1007
Alex Light64ad14d2014-08-19 14:23:13 -07001008 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001009 // Create the oat file.
1010 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1011 oat_location, error_msgs));
1012 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001013
1014 // Failed, bail.
1015 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001016 std::string error_msg;
1017 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1018 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1019 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001020 return false;
1021 }
1022
1023 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001024 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1025 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001026 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001027 if (success) {
1028 RegisterOatFile(open_oat_file.release());
1029 return true;
1030 } else {
1031 return false;
1032 }
1033}
1034
1035const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1036 uint32_t dex_location_checksum,
1037 const char* oat_location,
1038 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001039 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001040 !Runtime::Current()->IsCompiler(),
1041 error_msg));
1042 if (oat_file.get() == nullptr) {
1043 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1044 error_msg->c_str());
1045 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001046 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001047 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001048 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1049 if (image_space != nullptr) {
1050 const ImageHeader& image_header = image_space->GetImageHeader();
1051 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1052 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1053 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1054 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1055 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1056 actual_image_oat_checksum);
1057 return nullptr;
1058 }
1059
1060 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1061 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1062 if (expected_image_oat_offset != actual_image_oat_offset) {
1063 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1064 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1065 actual_image_oat_offset);
1066 return nullptr;
1067 }
1068 int32_t expected_patch_delta = image_header.GetPatchDelta();
1069 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1070 if (expected_patch_delta != actual_patch_delta) {
1071 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1072 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1073 return nullptr;
1074 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001075 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001076
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001077 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1078 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001079 if (oat_dex_file == nullptr) {
1080 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1081 dex_location);
1082 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001083 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001084 uint32_t expected_dex_checksum = dex_location_checksum;
1085 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1086 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001087 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1088 "found 0x%x", oat_location, expected_dex_checksum,
1089 actual_dex_checksum);
1090 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001091 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001092 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1093 if (dex_file.get() != nullptr) {
1094 return oat_file.release();
1095 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001096 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001097 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001098}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001099
Andreas Gampe833a4852014-05-21 18:46:59 -07001100const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1101 int fd, const char* oat_location,
1102 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001103 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001104 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001105 std::string error_msg;
1106 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001107 CHECK(!error_msg.empty());
1108 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001109 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001110 }
Igor Murashkin46774762014-10-22 11:37:02 -07001111 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001112 !Runtime::Current()->IsCompiler(),
1113 &error_msg));
1114 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001115 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1116 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001117 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001118 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001119 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001120
1121 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001122}
1123
Alex Light6e183f22014-07-18 14:57:04 -07001124bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1125 const InstructionSet instruction_set) {
1126 Runtime* runtime = Runtime::Current();
1127 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001128 if (image_space == nullptr) {
1129 return false;
1130 }
Alex Light6e183f22014-07-18 14:57:04 -07001131 uint32_t image_oat_checksum = 0;
1132 if (instruction_set == kRuntimeISA) {
1133 const ImageHeader& image_header = image_space->GetImageHeader();
1134 image_oat_checksum = image_header.GetOatChecksum();
1135 } else {
1136 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1137 image_space->GetImageLocation().c_str(), instruction_set));
1138 image_oat_checksum = image_header->GetOatChecksum();
1139 }
1140 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1141}
1142
1143bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1144 const InstructionSet instruction_set,
1145 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001146 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001147 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001148 if (image_space == nullptr) {
1149 *error_msg = "No image space for verification against";
1150 return false;
1151 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001152
1153 // If the requested instruction set is the same as the current runtime,
1154 // we can use the checksums directly. If it isn't, we'll have to read the
1155 // image header from the image for the right instruction set.
1156 uint32_t image_oat_checksum = 0;
1157 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001158 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001159 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001160 const ImageHeader& image_header = image_space->GetImageHeader();
1161 image_oat_checksum = image_header.GetOatChecksum();
1162 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001163 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001164 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001165 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001166 image_space->GetImageLocation().c_str(), instruction_set));
1167 image_oat_checksum = image_header->GetOatChecksum();
1168 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001169 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001170 }
1171 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin96e83932014-10-29 19:45:42 -07001172 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1173
1174 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1175 if (!oat_file->IsPic()) {
1176 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1177 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1178 }
Alex Light6e183f22014-07-18 14:57:04 -07001179 if (!ret) {
1180 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1181 oat_file->GetLocation().c_str(),
1182 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1183 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1184 oat_file->GetOatHeader().GetImagePatchDelta(),
1185 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1186 }
1187 return ret;
1188}
1189
1190bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1191 const char* dex_location,
1192 uint32_t dex_location_checksum,
1193 const InstructionSet instruction_set,
1194 std::string* error_msg) {
1195 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1196 return false;
1197 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001198
Brian Carlstromf3632832014-05-20 15:36:53 -07001199 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1200 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001201 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001202 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1203 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001204 for (const OatFile::OatDexFile* oat_dex_file_in : oat_file->GetOatDexFiles()) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001205 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001206 oat_file->GetLocation().c_str(),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001207 oat_dex_file_in->GetDexFileLocation().c_str(),
1208 oat_dex_file_in->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001209 }
1210 return false;
1211 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001212
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001213 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001214 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001215}
1216
Alex Lighta59dd802014-07-02 16:28:08 -07001217bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1218 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001219 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001220 std::string* error_msg) {
1221 CHECK(oat_file != nullptr);
1222 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001223 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001224 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001225 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1226 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1227 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001228 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001229 if (oat_dex_file == nullptr) {
1230 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001231 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001232 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001233 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001234 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001235 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001236 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001237 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001238 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001239 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001240 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001241 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001242 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001243 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001244 }
Alex Lighta59dd802014-07-02 16:28:08 -07001245 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001246}
1247
Andreas Gampe833a4852014-05-21 18:46:59 -07001248const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001249 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001250 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001251 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001252 std::vector<std::string>* error_msgs,
1253 bool* obsolete_file_cleanup_failed) {
1254 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001255 bool already_opened = false;
1256 std::string dex_location_str(dex_location);
1257 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1258 &already_opened,
1259 obsolete_file_cleanup_failed,
1260 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001261 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001262 if (oat_file.get() == nullptr) {
1263 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1264 dex_location));
1265 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001266 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001267 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1268 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001269 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1270 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001271 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001272 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001273 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001274 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001275 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1276 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1277 "dex location '%s'. Image checksum incorrect.",
1278 oat_file->GetLocation().c_str(), dex_location));
1279 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001280 } else {
1281 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001282 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001283}
1284
Brian Carlstromae826982011-11-09 01:33:42 -08001285const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001286 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001287 for (size_t i = 0; i < oat_files_.size(); i++) {
1288 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001289 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001290 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001291 return oat_file;
1292 }
1293 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001294 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001295}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001296
Alex Lighta59dd802014-07-02 16:28:08 -07001297const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1298 InstructionSet isa,
1299 bool *already_opened,
1300 bool *obsolete_file_cleanup_failed,
1301 std::vector<std::string>* error_msgs) {
1302 // Find out if we've already opened the file
1303 const OatFile* ret = nullptr;
1304 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1305 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1306 if (ret != nullptr) {
1307 *already_opened = true;
1308 return ret;
1309 }
1310
1311 std::string dalvik_cache;
1312 bool have_android_data = false;
1313 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001314 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001315 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001316 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001317 std::string cache_filename;
1318 if (have_dalvik_cache) {
1319 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1320 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1321 if (ret != nullptr) {
1322 *already_opened = true;
1323 return ret;
1324 }
1325 } else {
1326 // If we need to relocate we should just place odex back where it started.
1327 cache_filename = odex_filename;
1328 }
1329
1330 ret = nullptr;
1331
1332 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1333 //
1334 // Now we do the following:
1335 // 1) Try and open the odex version
1336 // 2) If present, checksum-verified & relocated correctly return it
1337 // 3) Close the odex version to free up its address space.
1338 // 4) Try and open the cache version
1339 // 5) If present, checksum-verified & relocated correctly return it
1340 // 6) Close the cache version to free up its address space.
1341 // 7) If we should relocate:
1342 // a) If we have opened and checksum-verified the odex version relocate it to
1343 // 'cache_filename' and return it
1344 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1345 // it. This should not happen often (I think only the run-test's will hit this case).
1346 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1347 // this point.
1348 // 9) Return nullptr
1349
1350 *already_opened = false;
1351 const Runtime* runtime = Runtime::Current();
1352 CHECK(runtime != nullptr);
1353 bool executable = !runtime->IsCompiler();
1354
1355 std::string odex_error_msg;
1356 bool should_patch_system = false;
1357 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001358 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001359 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001360 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001361 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001362 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001363 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001364 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001365 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001366 &odex_checksum_verified,
1367 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001368 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001369 } else {
1370 if (odex_checksum_verified) {
1371 // We can just relocate
1372 should_patch_system = true;
1373 odex_error_msg = "Image Patches are incorrect";
1374 }
1375 if (odex_oat_file.get() != nullptr) {
1376 have_system_odex = true;
1377 }
Alex Lighta59dd802014-07-02 16:28:08 -07001378 }
1379 }
1380
Alex Lighta59dd802014-07-02 16:28:08 -07001381 std::string cache_error_msg;
1382 bool should_patch_cache = false;
1383 bool cache_checksum_verified = false;
1384 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001385 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001386 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001387 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001388 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001389 &cache_checksum_verified,
1390 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001391 return cache_oat_file.release();
1392 } else if (cache_checksum_verified) {
1393 // We can just relocate
1394 should_patch_cache = true;
1395 cache_error_msg = "Image Patches are incorrect";
1396 }
1397 } else if (have_android_data) {
1398 // dalvik_cache does not exist but android data does. This means we should be able to create
1399 // it, so we should try.
1400 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1401 }
1402
1403 ret = nullptr;
1404 std::string error_msg;
1405 if (runtime->CanRelocate()) {
1406 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001407 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1408 if (space != nullptr) {
1409 const std::string& image_location = space->GetImageLocation();
1410 if (odex_checksum_verified && should_patch_system) {
1411 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1412 } else if (cache_checksum_verified && should_patch_cache) {
1413 CHECK(have_dalvik_cache);
1414 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1415 }
Alex Light84d76052014-08-22 17:49:35 -07001416 } else if (have_system_odex) {
1417 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001418 }
1419 }
1420 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1421 // implicitly: were able to fine where the cached version is but we were unable to use it,
1422 // either as a destination for relocation or to open a file. We should delete it if it is
1423 // there.
1424 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1425 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1426 "searching for dex file %s: %s",
1427 cache_filename.c_str(), dex_location.c_str(),
1428 strerror(errno));
1429 error_msgs->push_back(rm_error_msg);
1430 VLOG(class_linker) << rm_error_msg;
1431 // Let the caller know that we couldn't remove the obsolete file.
1432 // This is a good indication that further writes may fail as well.
1433 *obsolete_file_cleanup_failed = true;
1434 }
1435 }
1436 if (ret == nullptr) {
1437 VLOG(class_linker) << error_msg;
1438 error_msgs->push_back(error_msg);
1439 std::string relocation_msg;
1440 if (runtime->CanRelocate()) {
1441 relocation_msg = StringPrintf(" and relocation failed");
1442 }
1443 if (have_dalvik_cache && cache_checksum_verified) {
1444 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1445 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1446 cache_filename.c_str(), cache_error_msg.c_str(),
1447 relocation_msg.c_str());
1448 } else {
1449 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1450 "dalvik_cache availible)%s.", odex_filename.c_str(),
1451 odex_error_msg.c_str(), relocation_msg.c_str());
1452 }
1453 VLOG(class_linker) << error_msg;
1454 error_msgs->push_back(error_msg);
1455 }
1456 return ret;
1457}
1458
Alex Light9dcc4572014-08-14 14:16:26 -07001459const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1460 InstructionSet isa,
1461 std::string* error_msg) {
1462 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001463 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001464 if (output.get() == nullptr) {
1465 return nullptr;
1466 }
Alex Light84d76052014-08-22 17:49:35 -07001467 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1468 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001469 return output.release();
1470 } else {
1471 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1472 oat_path.c_str());
1473 return nullptr;
1474 }
1475}
1476
Alex Lighta59dd802014-07-02 16:28:08 -07001477const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1478 const std::string& output_oat,
1479 const std::string& image_location,
1480 InstructionSet isa,
1481 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001482 Runtime* runtime = Runtime::Current();
1483 DCHECK(runtime != nullptr);
1484 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001485 // We don't have an image space so there is no point in trying to patchoat.
1486 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1487 << "running without an image. Attempting to use oat file for interpretation.";
1488 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1489 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001490 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001491 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1492 // input_oat but make sure we only do interpretation on it's dex files.
1493 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1494 << "disabled. Attempting to use oat file for interpretation";
1495 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1496 }
Alex Lighta59dd802014-07-02 16:28:08 -07001497 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001498 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001499
1500 std::string isa_arg("--instruction-set=");
1501 isa_arg += GetInstructionSetString(isa);
1502 std::string input_oat_filename_arg("--input-oat-file=");
1503 input_oat_filename_arg += input_oat;
1504 std::string output_oat_filename_arg("--output-oat-file=");
1505 output_oat_filename_arg += output_oat;
1506 std::string patched_image_arg("--patched-image-location=");
1507 patched_image_arg += image_location;
1508
1509 std::vector<std::string> argv;
1510 argv.push_back(patchoat);
1511 argv.push_back(isa_arg);
1512 argv.push_back(input_oat_filename_arg);
1513 argv.push_back(output_oat_filename_arg);
1514 argv.push_back(patched_image_arg);
1515
1516 std::string command_line(Join(argv, ' '));
1517 LOG(INFO) << "Relocate Oat File: " << command_line;
1518 bool success = Exec(argv, error_msg);
1519 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001520 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gampe7ba64962014-10-23 11:37:40 -07001521 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001522 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001523 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1524 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001525 return output.release();
1526 } else if (output.get() != nullptr) {
1527 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1528 "but output file '%s' failed verifcation: %s",
1529 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1530 } else {
1531 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1532 "but was unable to open output file '%s': %s",
1533 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1534 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001535 } else if (!runtime->IsCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001536 // patchoat failed which means we probably don't have enough room to place the output oat file,
1537 // instead of failing we should just run the interpreter from the dex files in the input oat.
1538 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1539 << "for interpretation. patchoat failure was: " << *error_msg;
1540 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001541 } else {
1542 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1543 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1544 error_msg->c_str());
1545 }
1546 return nullptr;
1547}
1548
Andreas Gampe7ba64962014-10-23 11:37:40 -07001549bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001550 bool* checksum_verified,
1551 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001552 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001553 if (image_space == nullptr) {
1554 *error_msg = "No image space present";
1555 return false;
1556 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001557 uint32_t real_image_checksum;
1558 void* real_image_oat_offset;
1559 int32_t real_patch_delta;
1560 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001561 const ImageHeader& image_header = image_space->GetImageHeader();
1562 real_image_checksum = image_header.GetOatChecksum();
1563 real_image_oat_offset = image_header.GetOatDataBegin();
1564 real_patch_delta = image_header.GetPatchDelta();
1565 } else {
1566 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1567 image_space->GetImageLocation().c_str(), isa));
1568 real_image_checksum = image_header->GetOatChecksum();
1569 real_image_oat_offset = image_header->GetOatDataBegin();
1570 real_patch_delta = image_header->GetPatchDelta();
1571 }
1572
1573 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001574 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001575
1576 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1577 *checksum_verified = oat_image_checksum == real_image_checksum;
1578 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001579 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1580 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001581 }
1582
Andreas Gampe7ba64962014-10-23 11:37:40 -07001583 bool offset_verified;
1584 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001585
Andreas Gampe7ba64962014-10-23 11:37:40 -07001586 if (!oat_file->IsPic()) {
1587 // If an oat file is not PIC, we need to check that the image is at the expected location and
1588 // patched in the same way.
1589 void* oat_image_oat_offset =
1590 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1591 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1592 if (!offset_verified) {
1593 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1594 real_image_oat_offset, oat_image_oat_offset);
1595 }
1596
1597 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1598 patch_delta_verified = oat_patch_delta == real_patch_delta;
1599 if (!patch_delta_verified) {
1600 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1601 "received 0x%x)", real_patch_delta, oat_patch_delta);
1602 }
1603 } else {
1604 // If an oat file is PIC, we ignore offset and patching delta.
1605 offset_verified = true;
1606 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001607 }
1608
1609 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001610 if (!ret) {
1611 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001612 }
1613 return ret;
1614}
1615
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001616const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1617 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001618 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001619 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001620 return oat_file;
1621 }
1622
Igor Murashkin46774762014-10-22 11:37:02 -07001623 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001624 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001625}
1626
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001627void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001628 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001629 DCHECK(obj != nullptr);
1630 DCHECK(class_linker != nullptr);
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001631 size_t pointer_size = class_linker->image_pointer_size_;
Ian Rogers848871b2013-08-05 10:56:33 -07001632
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001633 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001634 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001635 if (!method->IsNative()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001636 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001637 if (method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001638 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1639 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001640 }
1641 }
1642 }
1643}
1644
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001645void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001646 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001647 CHECK(!init_done_);
1648
Mathieu Chartier590fee92013-09-13 13:46:47 -07001649 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001650 gc::Heap* heap = Runtime::Current()->GetHeap();
1651 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001652 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001653 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001654 OatFile& oat_file = GetImageOatFile(space);
1655 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1656 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001657 const char* image_file_location = oat_file.GetOatHeader().
1658 GetStoreValueByKey(OatHeader::kImageLocationKey);
1659 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001660 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001661 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001662 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001663 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001664 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1665 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1666 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001667
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001668 StackHandleScope<1> hs(self);
1669 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1670 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1671 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001672 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001673
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001674 // Special case of setting up the String class early so that we can test arbitrary objects
1675 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001676 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001677
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001678 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001679 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001680 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001681 StackHandleScope<1> hs2(self);
1682 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001683 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001684 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1685 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001686 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001687 std::string error_msg;
1688 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001689 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001690 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001691 << " from within oat file " << oat_file.GetLocation()
1692 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -08001693 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001694 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001695
1696 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1697
1698 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001699 }
1700
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001701 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1702 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001703 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001704 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
1705 if (!Runtime::Current()->IsCompiler()) {
1706 // Compiler supports having an image with a different pointer size than the runtime. This
1707 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
1708 // also use 32 bit dex2oat on a system with 64 bit apps.
1709 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
1710 << sizeof(void*);
1711 }
1712 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
1713 image_pointer_size_ = 4;
1714 } else {
1715 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
1716 image_pointer_size_ = 8;
1717 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001718
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001719 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001720 Runtime* runtime = Runtime::Current();
1721 if (!runtime->IsCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001722 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001723 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001724 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001725
1726 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001727 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001728 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001729
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001730 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001731 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001732 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001733 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001734 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001735 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001736 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1737 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1738 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1739 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1740 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1741 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1742 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1743 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1744 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1745 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001746
Ian Rogers98379392014-02-24 16:53:16 -08001747 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001748
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001749 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001750}
1751
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001752void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1753 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1754 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001755 for (GcRoot<mirror::Class>& root : class_table_) {
1756 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1757 }
1758 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1759 root.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001760 }
1761 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001762 for (auto& root : new_class_roots_) {
1763 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
1764 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1765 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001766 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001767 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1768 // corresponding object. This is slow, but luckily for us, this may only happen with a
1769 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001770 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
1771 class_table_.Erase(it);
1772 class_table_.Insert(GcRoot<mirror::Class>(new_ref));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001773 }
1774 }
1775 }
1776 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1777 new_class_roots_.clear();
1778 }
1779 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1780 log_new_class_table_roots_ = true;
1781 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1782 log_new_class_table_roots_ = false;
1783 }
1784 // We deliberately ignore the class roots in the image since we
1785 // handle image roots by using the MS/CMS rescanning of dirty cards.
1786}
1787
Brian Carlstroma663ea52011-08-19 23:33:41 -07001788// Keep in sync with InitCallback. Anything we visit, we need to
1789// reinit references to when reinitializing a ClassLinker from a
1790// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001791void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001792 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001793 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001794 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001795 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001796 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001797 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1798 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001799 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001800 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1801 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001802 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001803 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001804 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001805 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1806 new_dex_cache_roots_.clear();
1807 }
1808 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1809 log_new_dex_caches_roots_ = true;
1810 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1811 log_new_dex_caches_roots_ = false;
1812 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001813 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001814 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001815 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1816 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001817 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001818 if (!find_array_class_cache_[i].IsNull()) {
1819 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001820 }
1821 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001822}
1823
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001824void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1825 if (dex_cache_image_class_lookup_required_) {
1826 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001827 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001828 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001829 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001830 for (GcRoot<mirror::Class>& root : class_table_) {
1831 if (!visitor(root.Read(), arg)) {
1832 return;
1833 }
1834 }
1835 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1836 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001837 return;
1838 }
1839 }
1840}
1841
Ian Rogersdbf3be02014-08-29 15:40:08 -07001842static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001843 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001844 classes->insert(c);
1845 return true;
1846}
1847
Ian Rogersdbf3be02014-08-29 15:40:08 -07001848struct GetClassesVisitorArrayArg {
1849 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1850 int32_t index;
1851 bool success;
1852};
1853
1854static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1855 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1856 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1857 if (arg->index < (*arg->classes)->GetLength()) {
1858 (*arg->classes)->Set(arg->index, c);
1859 arg->index++;
1860 return true;
1861 } else {
1862 arg->success = false;
1863 return false;
1864 }
1865}
1866
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001867void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001868 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1869 // is avoiding duplicates.
1870 if (!kMovingClasses) {
1871 std::set<mirror::Class*> classes;
1872 VisitClasses(GetClassesVisitorSet, &classes);
1873 for (mirror::Class* klass : classes) {
1874 if (!visitor(klass, arg)) {
1875 return;
1876 }
1877 }
1878 } else {
1879 Thread* self = Thread::Current();
1880 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001881 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001882 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1883 GetClassesVisitorArrayArg local_arg;
1884 local_arg.classes = &classes;
1885 local_arg.success = false;
1886 // We size the array assuming classes won't be added to the class table during the visit.
1887 // If this assumption fails we iterate again.
1888 while (!local_arg.success) {
1889 size_t class_table_size;
1890 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001891 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001892 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001893 }
1894 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1895 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1896 classes.Assign(
1897 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1898 CHECK(classes.Get() != nullptr); // OOME.
1899 local_arg.index = 0;
1900 local_arg.success = true;
1901 VisitClasses(GetClassesVisitorArray, &local_arg);
1902 }
1903 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1904 // If the class table shrank during creation of the clases array we expect null elements. If
1905 // the class table grew then the loop repeats. If classes are created after the loop has
1906 // finished then we don't visit.
1907 mirror::Class* klass = classes->Get(i);
1908 if (klass != nullptr && !visitor(klass, arg)) {
1909 return;
1910 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001911 }
1912 }
1913}
1914
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001915ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001916 mirror::Class::ResetClass();
1917 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001918 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001919 mirror::ArtField::ResetClass();
1920 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001921 mirror::BooleanArray::ResetArrayClass();
1922 mirror::ByteArray::ResetArrayClass();
1923 mirror::CharArray::ResetArrayClass();
1924 mirror::DoubleArray::ResetArrayClass();
1925 mirror::FloatArray::ResetArrayClass();
1926 mirror::IntArray::ResetArrayClass();
1927 mirror::LongArray::ResetArrayClass();
1928 mirror::ShortArray::ResetArrayClass();
1929 mirror::Throwable::ResetClass();
1930 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001931 STLDeleteElements(&boot_class_path_);
1932 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001933}
1934
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001935mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001936 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001937 StackHandleScope<16> hs(self);
1938 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1939 Handle<mirror::DexCache> dex_cache(
1940 hs.NewHandle(down_cast<mirror::DexCache*>(
1941 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1942 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001943 if (dex_cache.Get() == nullptr) {
1944 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001945 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001946 Handle<mirror::String>
1947 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001948 if (location.Get() == nullptr) {
1949 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001950 }
Ian Rogers700a4022014-05-19 16:49:03 -07001951 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001952 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001953 if (strings.Get() == nullptr) {
1954 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001955 }
Ian Rogers700a4022014-05-19 16:49:03 -07001956 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001957 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001958 if (types.Get() == nullptr) {
1959 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001960 }
Ian Rogers700a4022014-05-19 16:49:03 -07001961 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001962 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001963 if (methods.Get() == nullptr) {
1964 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001965 }
Ian Rogers700a4022014-05-19 16:49:03 -07001966 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001967 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001968 if (fields.Get() == nullptr) {
1969 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001970 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001971 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1972 fields.Get());
1973 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001974}
1975
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001976mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001977 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001978 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001979 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001980 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001981 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001982 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1983 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001984 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001985 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001986 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001987 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001988 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001989}
1990
Ian Rogers6fac4472014-02-25 17:01:10 -08001991mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001992 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001993}
1994
Brian Carlstromea46f952013-07-30 01:26:50 -07001995mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001996 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001997 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001998}
1999
Brian Carlstromea46f952013-07-30 01:26:50 -07002000mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002001 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002002 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002003}
2004
Mathieu Chartier590fee92013-09-13 13:46:47 -07002005mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
2006 Thread* self, size_t length) {
2007 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2008 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002009}
2010
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002011mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
2012 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002013 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002014
2015 // For temporary classes we must wait for them to be retired.
2016 if (init_done_ && klass->IsTemp()) {
2017 CHECK(!klass->IsResolved());
2018 if (klass->IsErroneous()) {
2019 ThrowEarlierClassFailure(klass);
2020 return nullptr;
2021 }
2022 StackHandleScope<1> hs(self);
2023 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2024 ObjectLock<mirror::Class> lock(self, h_class);
2025 // Loop and wait for the resolving thread to retire this class.
2026 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2027 lock.WaitIgnoringInterrupts();
2028 }
2029 if (h_class->IsErroneous()) {
2030 ThrowEarlierClassFailure(h_class.Get());
2031 return nullptr;
2032 }
2033 CHECK(h_class->IsRetired());
2034 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002035 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2036 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002037 }
2038
Brian Carlstromaded5f72011-10-07 17:15:04 -07002039 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002040 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002041 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002042 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2043 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002044 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002045 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2046 ThrowClassCircularityError(h_class.Get());
2047 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002048 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002049 }
2050 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002051 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002052 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002053 }
2054 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002055
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002056 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002057 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002058 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002059 }
2060 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002061 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002062 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002063 return klass;
2064}
2065
Ian Rogers68b56852014-08-29 20:19:11 -07002066typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2067
2068// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002069ClassPathEntry FindInClassPath(const char* descriptor,
2070 size_t hash, const std::vector<const DexFile*>& class_path) {
2071 for (const DexFile* dex_file : class_path) {
2072 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002073 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002074 return ClassPathEntry(dex_file, dex_class_def);
2075 }
2076 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002077 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002078}
2079
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002080mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2081 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002082 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002083 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08002084 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002085 if (class_loader->GetClass() !=
2086 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2087 class_loader->GetParent()->GetClass() !=
2088 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2089 return nullptr;
2090 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002091 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002092 // Check if this would be found in the parent boot class loader.
2093 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002094 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002095 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08002096 // May return null if resolution on another thread fails.
2097 klass = EnsureResolved(self, descriptor, klass);
2098 } else {
2099 // May OOME.
2100 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2101 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002102 }
Ian Rogers32427292014-11-19 14:05:21 -08002103 if (klass == nullptr) {
2104 CHECK(self->IsExceptionPending()) << descriptor;
2105 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002106 }
Ian Rogers32427292014-11-19 14:05:21 -08002107 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002108 } else {
Ian Rogers32427292014-11-19 14:05:21 -08002109 // Handle as if this is the child PathClassLoader.
2110 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002111 StackHandleScope<3> hs(self);
2112 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2113 // We need to get the DexPathList and loop through it.
2114 Handle<mirror::ArtField> cookie_field =
2115 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2116 Handle<mirror::ArtField> dex_file_field =
2117 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002118 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002119 mirror::Object* dex_path_list =
2120 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2121 GetObject(class_loader.Get());
2122 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2123 cookie_field.Get() != nullptr) {
2124 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2125 mirror::Object* dex_elements_obj =
2126 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2127 GetObject(dex_path_list);
2128 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2129 // at the mCookie which is a DexFile vector.
2130 if (dex_elements_obj != nullptr) {
2131 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2132 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2133 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2134 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2135 if (element == nullptr) {
2136 // Should never happen, fall back to java code to throw a NPE.
2137 break;
2138 }
2139 mirror::Object* dex_file = dex_file_field->GetObject(element);
2140 if (dex_file != nullptr) {
2141 const uint64_t cookie = cookie_field->GetLong(dex_file);
2142 auto* dex_files =
2143 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2144 if (dex_files == nullptr) {
2145 // This should never happen so log a warning.
2146 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2147 break;
2148 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002149 for (const DexFile* cp_dex_file : *dex_files) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002150 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002151 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002152 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002153 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2154 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002155 if (klass == nullptr) {
2156 CHECK(self->IsExceptionPending()) << descriptor;
2157 self->ClearException();
2158 return nullptr;
2159 }
2160 return klass;
2161 }
2162 }
2163 }
2164 }
2165 }
2166 }
Ian Rogers32427292014-11-19 14:05:21 -08002167 self->AssertNoPendingException();
2168 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002169 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002170}
2171
Ian Rogers98379392014-02-24 16:53:16 -08002172mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002173 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002174 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002175 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002176 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002177 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002178 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2179 // for primitive classes that aren't backed by dex files.
2180 return FindPrimitiveClass(descriptor[0]);
2181 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002182 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002183 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002184 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002185 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002186 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002187 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002188 // Class is not yet loaded.
2189 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002190 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002191 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002192 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002193 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002194 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002195 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002196 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002197 } else {
2198 // The boot class loader is searched ahead of the application class loader, failures are
2199 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2200 // trigger the chaining with a proper stack trace.
2201 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2202 self->SetException(ThrowLocation(), pre_allocated);
2203 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002204 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002205 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002206 // First try with the bootstrap class loader.
2207 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002208 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002209 if (klass != nullptr) {
2210 return EnsureResolved(self, descriptor, klass);
2211 }
2212 }
Ian Rogers63557452014-06-04 16:57:15 -07002213 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2214 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002215 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002216 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002217 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002218 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002219 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002220 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002221 const std::vector<const DexFile*>* class_path;
2222 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002223 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002224 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002225 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002226 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2227 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002228 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07002229 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002230 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07002231 } else {
2232 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2233 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2234 self->SetException(ThrowLocation(), pre_allocated);
2235 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002236 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002237 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002238 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002239 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2240 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002241 if (cp_klass != nullptr) {
2242 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002243 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002244 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002245 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002246 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002247 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002248 {
2249 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002250 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2251 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002252 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002253 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002254 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002255 }
Ian Rogers68b56852014-08-29 20:19:11 -07002256 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002257 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2258 WellKnownClasses::java_lang_ClassLoader_loadClass,
2259 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002260 }
Ian Rogers98379392014-02-24 16:53:16 -08002261 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002262 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002263 return nullptr;
2264 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002265 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002266 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002267 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002268 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002269 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002270 // success, return mirror::Class*
2271 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002272 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002273 }
Ian Rogers07140832014-09-30 15:43:59 -07002274 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002275}
2276
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002277mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002278 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002279 const DexFile& dex_file,
2280 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002281 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002282 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002283
Brian Carlstromaded5f72011-10-07 17:15:04 -07002284 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002285 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002286 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002287 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002288 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002289 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002290 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002291 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002292 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002293 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2294 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002295 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002296 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002297 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002298 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002299 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002300 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002301 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002302 }
2303
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002304 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002305 // Allocate a class with the status of not ready.
2306 // Interface object should get the right size here. Regular class will
2307 // figure out the right size later and be replaced with one of the right
2308 // size when the class becomes resolved.
2309 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002310 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002311 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002312 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002313 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002314 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002315 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002316 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002317 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002318 if (self->IsExceptionPending()) {
2319 // An exception occured during load, set status to erroneous while holding klass' lock in case
2320 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002321 if (!klass->IsErroneous()) {
2322 klass->SetStatus(mirror::Class::kStatusError, self);
2323 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002324 return nullptr;
2325 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002326 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002327
Mathieu Chartier590fee92013-09-13 13:46:47 -07002328 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002329 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002330 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002331 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2332 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002333 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002334 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002335
Brian Carlstromaded5f72011-10-07 17:15:04 -07002336 // Finish loading (if necessary) by finding parents
2337 CHECK(!klass->IsLoaded());
2338 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2339 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002340 if (!klass->IsErroneous()) {
2341 klass->SetStatus(mirror::Class::kStatusError, self);
2342 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002343 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002344 }
2345 CHECK(klass->IsLoaded());
2346 // Link the class (if necessary)
2347 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002348 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002349 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002350
2351 mirror::Class* new_class = nullptr;
2352 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002353 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002354 if (!klass->IsErroneous()) {
2355 klass->SetStatus(mirror::Class::kStatusError, self);
2356 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002357 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002358 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002359 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002360 CHECK(new_class != nullptr) << descriptor;
2361 CHECK(new_class->IsResolved()) << descriptor;
2362
2363 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002364
2365 /*
2366 * We send CLASS_PREPARE events to the debugger from here. The
2367 * definition of "preparation" is creating the static fields for a
2368 * class and initializing them to the standard default values, but not
2369 * executing any code (that comes later, during "initialization").
2370 *
2371 * We did the static preparation in LinkClass.
2372 *
2373 * The class has been prepared and resolved but possibly not yet verified
2374 * at this point.
2375 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002376 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002377
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002378 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002379}
2380
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002381uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2382 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002383 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002384 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002385 size_t num_8 = 0;
2386 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002387 size_t num_32 = 0;
2388 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002389 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002390 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2391 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002392 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002393 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002394 switch (c) {
2395 case 'L':
2396 case '[':
2397 num_ref++;
2398 break;
2399 case 'J':
2400 case 'D':
2401 num_64++;
2402 break;
2403 case 'I':
2404 case 'F':
2405 num_32++;
2406 break;
2407 case 'S':
2408 case 'C':
2409 num_16++;
2410 break;
2411 case 'B':
2412 case 'Z':
2413 num_8++;
2414 break;
2415 default:
2416 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002417 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002418 }
2419 }
2420 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002421 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002422}
2423
Ian Rogers97b52f82014-08-14 11:34:07 -07002424OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2425 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002426 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002427 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2428 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002429 *found = false;
2430 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002431 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002432 *found = true;
2433 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002434}
2435
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002436static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2437 uint32_t method_idx) {
2438 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002439 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002440 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002441 ClassDataItemIterator it(dex_file, class_data);
2442 // Skip fields
2443 while (it.HasNextStaticField()) {
2444 it.Next();
2445 }
2446 while (it.HasNextInstanceField()) {
2447 it.Next();
2448 }
2449 // Process methods
2450 size_t class_def_method_index = 0;
2451 while (it.HasNextDirectMethod()) {
2452 if (it.GetMemberIndex() == method_idx) {
2453 return class_def_method_index;
2454 }
2455 class_def_method_index++;
2456 it.Next();
2457 }
2458 while (it.HasNextVirtualMethod()) {
2459 if (it.GetMemberIndex() == method_idx) {
2460 return class_def_method_index;
2461 }
2462 class_def_method_index++;
2463 it.Next();
2464 }
2465 DCHECK(!it.HasNext());
2466 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08002467 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002468}
2469
Ian Rogers97b52f82014-08-14 11:34:07 -07002470const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002471 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002472 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002473 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002474 size_t oat_method_index;
2475 if (method->IsStatic() || method->IsDirect()) {
2476 // Simple case where the oat method index was stashed at load time.
2477 oat_method_index = method->GetMethodIndex();
2478 } else {
2479 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2480 // by search for its position in the declared virtual methods.
2481 oat_method_index = declaring_class->NumDirectMethods();
2482 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002483 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002484 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002485 // Check method index instead of identity in case of duplicate method definitions.
2486 if (method->GetDexMethodIndex() ==
2487 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002488 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002489 break;
2490 }
Ian Rogersf320b632012-03-13 18:47:47 -07002491 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002492 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002493 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2494 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002495 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002496 DCHECK_EQ(oat_method_index,
2497 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002498 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002499 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002500 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2501 declaring_class->GetDexClassDefIndex(),
2502 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002503 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002504 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002505 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002506 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002507}
2508
2509// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002510const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002511 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002512 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002513 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002514 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002515 bool found;
2516 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002517 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002518 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002519 result = oat_method.GetQuickCode();
2520 }
2521
Ian Rogersef7d42f2014-01-06 12:55:46 -08002522 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002523 if (method->IsNative()) {
2524 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002525 result = GetQuickGenericJniStub();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002526 } else {
2527 // No code? You must mean to go into the interpreter.
2528 result = GetQuickToInterpreterBridge();
2529 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002530 }
2531 return result;
TDYa12785321912012-04-01 15:24:56 -07002532}
2533
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002534const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2535 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2536 return nullptr;
2537 }
2538 bool found;
2539 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2540 return found ? oat_method.GetQuickCode() : nullptr;
2541}
2542
Ian Rogersef7d42f2014-01-06 12:55:46 -08002543const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2544 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002545 bool found;
2546 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2547 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002548 return nullptr;
2549 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002550 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002551 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002552}
2553
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002554// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08002555static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07002556 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08002557 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002558 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002559 // May return true for native code, in the case of generic JNI
2560 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002561 return true;
2562 }
2563 // If interpreter mode is enabled, every method (except native and proxy) must
2564 // be run with interpreter.
2565 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2566 !method->IsNative() && !method->IsProxyMethod();
2567}
2568
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002569void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002570 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002571 if (klass->NumDirectMethods() == 0) {
2572 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002573 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002574 Runtime* runtime = Runtime::Current();
2575 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002576 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2577 return; // OAT file unavailable.
2578 }
Ian Rogers19846512012-02-24 11:42:47 -08002579 }
Alex Light64ad14d2014-08-19 14:23:13 -07002580
Mathieu Chartierf8322842014-05-16 10:59:25 -07002581 const DexFile& dex_file = klass->GetDexFile();
2582 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002583 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002584 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002585 // There should always be class data if there were direct methods.
2586 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002587 ClassDataItemIterator it(dex_file, class_data);
2588 // Skip fields
2589 while (it.HasNextStaticField()) {
2590 it.Next();
2591 }
2592 while (it.HasNextInstanceField()) {
2593 it.Next();
2594 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002595 bool has_oat_class;
2596 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2597 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002598 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002599 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002600 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002601 if (!method->IsStatic()) {
2602 // Only update static methods.
2603 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002604 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002605 const void* quick_code = nullptr;
2606 if (has_oat_class) {
2607 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002608 quick_code = oat_method.GetQuickCode();
2609 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002610 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002611 if (enter_interpreter) {
2612 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002613 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08002614 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002615 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08002616 } else {
2617 quick_code = GetQuickToInterpreterBridge();
2618 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002619 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002620 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08002621 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002622 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002623}
2624
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002625void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002626 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002627 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002628 Runtime* runtime = Runtime::Current();
2629 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002630 // The following code only applies to a non-compiler runtime.
2631 return;
2632 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002633 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002634 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002635 if (oat_class != nullptr) {
2636 // Every kind of method should at least get an invoke stub from the oat_method.
2637 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002638 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002639 oat_method.LinkMethod(method.Get());
2640 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002641
Jeff Hao16743632013-05-08 10:59:04 -07002642 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002643 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08002644 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002645 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002646 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002647 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002648 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002649 }
2650
Brian Carlstrom92827a52011-10-10 15:50:01 -07002651 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002652 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002653 return;
2654 }
Ian Rogers19846512012-02-24 11:42:47 -08002655
2656 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002657 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002658 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2659 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002660 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002661 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002662 if (!method->IsNative()) {
2663 // Set entry point from compiled code if there's no code or in interpreter only mode.
2664 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002665 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002666 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002667 }
Ian Rogers0d6de042012-02-29 08:50:26 -08002668 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002669
Ian Rogers62d6c772013-02-27 08:32:07 -08002670 if (method->IsNative()) {
2671 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002672 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002673
2674 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002675 // We have a native method here without code. Then it should have either the generic JNI
2676 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2677 // TODO: this doesn't handle all the cases where trampolines may be installed.
2678 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2679 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002680 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002681 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002682
Ian Rogers62d6c772013-02-27 08:32:07 -08002683 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002684 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08002685 method->GetEntryPointFromQuickCompiledCode());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002686}
2687
Fred Shih37f05ef2014-07-16 18:38:08 -07002688
Fred Shih37f05ef2014-07-16 18:38:08 -07002689
Ian Rogers7b078e82014-09-10 14:44:24 -07002690void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002691 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002692 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002693 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002694 CHECK(klass.Get() != nullptr);
2695 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002696 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002697 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002698 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002699
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002700 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002701 if (kUseBakerOrBrooksReadBarrier) {
2702 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002703 }
Andreas Gampe51829322014-08-25 15:05:04 -07002704 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002705 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002706 klass->SetAccessFlags(access_flags);
2707 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002708 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002709 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002710
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002711 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002712 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002713 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002714
Ian Rogers13735952014-10-08 12:43:28 -07002715 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002716 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002717 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002718 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002719
Ian Rogers97b52f82014-08-14 11:34:07 -07002720
2721 bool has_oat_class = false;
2722 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2723 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2724 &has_oat_class);
2725 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002726 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002727 }
2728 }
2729 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002730 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002731 }
2732}
2733
Ian Rogers7b078e82014-09-10 14:44:24 -07002734void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002735 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002736 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002737 const OatFile::OatClass* oat_class) {
2738 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002739 ClassDataItemIterator it(dex_file, class_data);
2740 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002741 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002742 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002743 CHECK(self->IsExceptionPending()); // OOME.
2744 return;
2745 }
2746 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002747 }
2748 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002749 mirror::ObjectArray<mirror::ArtField>* fields =
2750 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002751 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002752 CHECK(self->IsExceptionPending()); // OOME.
2753 return;
2754 }
2755 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002756 }
2757 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002758 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002759 StackHandleScope<1> hs(self);
2760 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002761 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002762 CHECK(self->IsExceptionPending()); // OOME.
2763 return;
2764 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002765 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002766 LoadField(dex_file, it, klass, sfield);
2767 }
2768 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002769 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002770 StackHandleScope<1> hs(self);
2771 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002772 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002773 CHECK(self->IsExceptionPending()); // OOME.
2774 return;
2775 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002776 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002777 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002778 }
2779
Ian Rogers0571d352011-11-03 19:51:38 -07002780 // Load methods.
2781 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002782 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002783 mirror::ObjectArray<mirror::ArtMethod>* directs =
2784 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002785 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002786 CHECK(self->IsExceptionPending()); // OOME.
2787 return;
2788 }
2789 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002790 }
Ian Rogers0571d352011-11-03 19:51:38 -07002791 if (it.NumVirtualMethods() != 0) {
2792 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002793 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2794 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002795 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002796 CHECK(self->IsExceptionPending()); // OOME.
2797 return;
2798 }
2799 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002800 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002801 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002802 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2803 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002804 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002805 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002806 StackHandleScope<1> hs(self);
2807 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002808 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002809 CHECK(self->IsExceptionPending()); // OOME.
2810 return;
2811 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002812 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002813 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002814 uint32_t it_method_index = it.GetMemberIndex();
2815 if (last_dex_method_index == it_method_index) {
2816 // duplicate case
2817 method->SetMethodIndex(last_class_def_method_index);
2818 } else {
2819 method->SetMethodIndex(class_def_method_index);
2820 last_dex_method_index = it_method_index;
2821 last_class_def_method_index = class_def_method_index;
2822 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002823 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002824 }
2825 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002826 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002827 StackHandleScope<1> hs(self);
2828 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002829 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002830 CHECK(self->IsExceptionPending()); // OOME.
2831 return;
2832 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002833 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002834 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002835 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002836 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002837 }
2838 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002839}
2840
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002841void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002842 Handle<mirror::Class> klass,
2843 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002844 uint32_t field_idx = it.GetMemberIndex();
2845 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002846 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002847 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002848}
2849
Brian Carlstromea46f952013-07-30 01:26:50 -07002850mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002851 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002852 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002853 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002854 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002855 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002856
Brian Carlstromea46f952013-07-30 01:26:50 -07002857 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002858 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002859 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002860 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002861 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002862 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002863
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002864 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002865 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002866 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002867 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002868
Ian Rogers19846512012-02-24 11:42:47 -08002869 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002870 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002871
Andreas Gampe51829322014-08-25 15:05:04 -07002872 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002873
Ian Rogersdfb325e2013-10-30 01:00:44 -07002874 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002875 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002876 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2877 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002878 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002879 klass->SetFinalizable();
2880 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002881 std::string temp;
2882 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002883 // The Enum class declares a "final" finalize() method to prevent subclasses from
2884 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2885 // subclasses, so we exclude it here.
2886 // We also want to avoid setting the flag on Object, where we know that finalize() is
2887 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002888 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2889 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002890 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002891 }
2892 }
2893 }
2894 } else if (method_name[0] == '<') {
2895 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002896 bool is_init = (strcmp("<init>", method_name) == 0);
2897 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002898 if (UNLIKELY(!is_init && !is_clinit)) {
2899 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2900 } else {
2901 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2902 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002903 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002904 access_flags |= kAccConstructor;
2905 }
2906 }
2907 }
2908 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002909
Mathieu Chartier66f19252012-09-18 08:57:04 -07002910 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002911}
2912
Ian Rogers7b078e82014-09-10 14:44:24 -07002913void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002914 StackHandleScope<1> hs(self);
2915 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002916 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2917 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002918 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002919}
2920
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002921void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002922 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002923 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002924 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002925 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002926}
2927
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002928bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002929 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002930 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002931 mirror::DexCache* dex_cache = GetDexCache(i);
2932 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002933 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002934 }
2935 }
2936 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002937}
2938
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002939bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002940 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002941 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002942}
2943
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002944void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002945 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002946 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002947 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002948 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2949 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002950 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002951 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002952 if (log_new_dex_caches_roots_) {
2953 // TODO: This is not safe if we can remove dex caches.
2954 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2955 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002956}
2957
Brian Carlstromaded5f72011-10-07 17:15:04 -07002958void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002959 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002960 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002961 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002962 if (IsDexFileRegisteredLocked(dex_file)) {
2963 return;
2964 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002965 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002966 // Don't alloc while holding the lock, since allocation may need to
2967 // suspend all threads and another thread may need the dex_lock_ to
2968 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002969 StackHandleScope<1> hs(self);
2970 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002971 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2972 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002973 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002974 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002975 if (IsDexFileRegisteredLocked(dex_file)) {
2976 return;
2977 }
2978 RegisterDexFileLocked(dex_file, dex_cache);
2979 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002980}
2981
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002982void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002983 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002984 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002985 RegisterDexFileLocked(dex_file, dex_cache);
2986}
2987
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002988mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002989 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002990 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002991 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002992 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002993 if (dex_cache->GetDexFile() == &dex_file) {
2994 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002995 }
2996 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002997 // Search matching by location name.
2998 std::string location(dex_file.GetLocation());
2999 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003000 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003001 if (dex_cache->GetDexFile()->GetLocation() == location) {
3002 return dex_cache;
3003 }
3004 }
3005 // Failure, dump diagnostic and abort.
3006 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003007 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003008 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3009 }
3010 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003011 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003012}
3013
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003014void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003015 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003016 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003017 mirror::DexCache* dex_cache = GetDexCache(i);
3018 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003019 }
3020}
3021
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003022mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003023 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003024 if (UNLIKELY(klass == nullptr)) {
3025 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003026 }
3027 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003028}
3029
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003030mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3031 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003032 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003033 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003034 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003035 StackHandleScope<1> hs(self);
3036 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003037 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003038 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003039 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003040 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3041 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003042 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3043 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003044 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003045 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003046}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003047
Brian Carlstrombe977852011-07-19 14:54:54 -07003048// Create an array class (i.e. the class object for the array, not the
3049// array itself). "descriptor" looks like "[C" or "[[[[B" or
3050// "[Ljava/lang/String;".
3051//
3052// If "descriptor" refers to an array of primitives, look up the
3053// primitive type's internally-generated class object.
3054//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003055// "class_loader" is the class loader of the class that's referring to
3056// us. It's used to ensure that we're looking for the element type in
3057// the right context. It does NOT become the class loader for the
3058// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003059//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003060// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003061mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003062 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003063 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003064 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003065 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003066 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3067 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003068 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003069 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003070 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003071 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3072 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003073 if (component_type.Get() == nullptr) {
3074 DCHECK(self->IsExceptionPending());
3075 return nullptr;
3076 } else {
3077 self->ClearException();
3078 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003079 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003080 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3081 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3082 return nullptr;
3083 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003084 // See if the component type is already loaded. Array classes are
3085 // always associated with the class loader of their underlying
3086 // element type -- an array of Strings goes with the loader for
3087 // java/lang/String -- so we need to look for it there. (The
3088 // caller should have checked for the existence of the class
3089 // before calling here, but they did so with *their* class loader,
3090 // not the component type's loader.)
3091 //
3092 // If we find it, the caller adds "loader" to the class' initiating
3093 // loader list, which should prevent us from going through this again.
3094 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003095 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003096 // are the same, because our caller (FindClass) just did the
3097 // lookup. (Even if we get this wrong we still have correct behavior,
3098 // because we effectively do this lookup again when we add the new
3099 // class to the hash table --- necessary because of possible races with
3100 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003101 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003102 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003103 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003104 return new_class;
3105 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003106 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003107
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003108 // Fill out the fields in the Class.
3109 //
3110 // It is possible to execute some methods against arrays, because
3111 // all arrays are subclasses of java_lang_Object_, so we need to set
3112 // up a vtable. We can just point at the one in java_lang_Object_.
3113 //
3114 // Array classes are simple enough that we don't need to do a full
3115 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003116 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003117 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003118 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003119 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003120 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003121 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003122 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003123 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003124 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003125 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003126 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003127 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003128 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003129 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003130 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003131 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003132 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003133 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003134 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003135 }
3136 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003137 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003138 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003139 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003140 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003141 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003142 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003143 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003144 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003145 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003146 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003147 new_class->SetSuperClass(java_lang_Object);
3148 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003149 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003150 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003151 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003152 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003153 StackHandleScope<mirror::Class::kImtSize> hs2(self,
3154 Runtime::Current()->GetImtUnimplementedMethod());
3155 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003156 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003157 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003158 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003159 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003160
3161
3162 // All arrays have java/lang/Cloneable and java/io/Serializable as
3163 // interfaces. We need to set that up here, so that stuff like
3164 // "instanceof" works right.
3165 //
3166 // Note: The GC could run during the call to FindSystemClass,
3167 // so we need to make sure the class object is GC-valid while we're in
3168 // there. Do this by clearing the interface list so the GC will just
3169 // think that the entries are null.
3170
3171
3172 // Use the single, global copies of "interfaces" and "iftable"
3173 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003174 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003175 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003176 CHECK(array_iftable != nullptr);
3177 new_class->SetIfTable(array_iftable);
3178 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003179
Elliott Hughes00626c22013-06-14 15:04:14 -07003180 // Inherit access flags from the component type.
3181 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3182 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3183 access_flags &= kAccJavaFlagsMask;
3184 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003185 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003186 access_flags |= kAccAbstract | kAccFinal;
3187 access_flags &= ~kAccInterface;
3188
3189 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003190
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003191 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003192 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003193 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003194 }
3195 // Another thread must have loaded the class after we
3196 // started but before we finished. Abandon what we've
3197 // done.
3198 //
3199 // (Yes, this happens.)
3200
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003201 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003202}
3203
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003204mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003205 switch (type) {
3206 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003207 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003208 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003209 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003210 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003211 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003212 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003213 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003214 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003215 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003216 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003217 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003218 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003219 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003220 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003221 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003222 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003223 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003224 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003225 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003226 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003227 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003228 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003229 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003230}
3231
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003232mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3233 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003234 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003235 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003236 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003237 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003238 source += " from ";
3239 source += dex_cache->GetLocation()->ToModifiedUtf8();
3240 }
3241 LOG(INFO) << "Loaded class " << descriptor << source;
3242 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003243 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003244 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003245 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003246 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003247 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003248 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003249 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003250 // Check a class loaded with the system class loader matches one in the image if the class
3251 // is in the image.
3252 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003253 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003254 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003255 }
3256 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003257 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003258 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003259 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003260 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003261 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003262 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003263}
3264
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003265mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3266 size_t hash) {
3267 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003268 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3269 hash);
3270 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003271 CHECK(klass->IsProxyClass());
3272 return nullptr;
3273 }
3274
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003275 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003276 CHECK_NE(existing, klass) << descriptor;
3277 CHECK(!existing->IsResolved()) << descriptor;
3278 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3279
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003280 CHECK(!klass->IsTemp()) << descriptor;
3281 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3282 dex_cache_image_class_lookup_required_) {
3283 // Check a class loaded with the system class loader matches one in the image if the class
3284 // is in the image.
3285 existing = LookupClassFromImage(descriptor);
3286 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003287 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003288 }
3289 }
3290 VerifyObject(klass);
3291
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003292 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003293 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003294 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003295 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003296 }
3297
3298 return existing;
3299}
3300
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003301bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003302 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003303 auto pair = std::make_pair(descriptor, class_loader);
3304 auto it = class_table_.Find(pair);
3305 if (it != class_table_.end()) {
3306 class_table_.Erase(it);
3307 return true;
3308 }
3309 it = pre_zygote_class_table_.Find(pair);
3310 if (it != pre_zygote_class_table_.end()) {
3311 pre_zygote_class_table_.Erase(it);
3312 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003313 }
3314 return false;
3315}
3316
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003317mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003318 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003319 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003320 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003321 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003322 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003323 return result;
3324 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003325 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003326 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3327 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003328 } else {
3329 // Lookup failed but need to search dex_caches_.
3330 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003331 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003332 InsertClass(descriptor, result, hash);
3333 } else {
3334 // Searching the image dex files/caches failed, we don't want to get into this situation
3335 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3336 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003337 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003338 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3339 MoveImageClassesToClassTable();
3340 }
3341 }
3342 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003343 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003344}
3345
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003346mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003347 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003348 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003349 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3350 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3351 if (it == pre_zygote_class_table_.end()) {
3352 it = class_table_.FindWithHash(descriptor_pair, hash);
3353 if (it == class_table_.end()) {
3354 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003355 }
3356 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003357 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003358}
3359
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003360static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3361 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3362 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003363 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003364 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3365 return root->AsObjectArray<mirror::DexCache>();
3366}
3367
3368void ClassLinker::MoveImageClassesToClassTable() {
3369 Thread* self = Thread::Current();
3370 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3371 if (!dex_cache_image_class_lookup_required_) {
3372 return; // All dex cache classes are already in the class table.
3373 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003374 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003375 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003376 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003377 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3378 mirror::DexCache* dex_cache = dex_caches->Get(i);
3379 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3380 for (int32_t j = 0; j < types->GetLength(); j++) {
3381 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003382 if (klass != nullptr) {
3383 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003384 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003385 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003386 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3387 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003388 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003389 << PrettyClassAndClassLoader(klass);
3390 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003391 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003392 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003393 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003394 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003395 }
3396 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003397 }
3398 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003399 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003400}
3401
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003402void ClassLinker::MoveClassTableToPreZygote() {
3403 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3404 DCHECK(pre_zygote_class_table_.Empty());
3405 pre_zygote_class_table_ = std::move(class_table_);
3406 class_table_.Clear();
3407}
3408
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003409mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003410 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003411 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3412 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3413 mirror::DexCache* dex_cache = dex_caches->Get(i);
3414 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003415 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003416 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003417 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003418 const DexFile::TypeId* type_id =
3419 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003420 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003421 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3422 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003423 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003424 return klass;
3425 }
3426 }
3427 }
3428 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003429 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003430}
3431
3432void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3433 result.clear();
3434 if (dex_cache_image_class_lookup_required_) {
3435 MoveImageClassesToClassTable();
3436 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003437 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3438 while (true) {
3439 auto it = class_table_.Find(descriptor);
3440 if (it == class_table_.end()) {
3441 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003442 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003443 result.push_back(it->Read());
3444 class_table_.Erase(it);
3445 }
3446 for (mirror::Class* k : result) {
3447 class_table_.Insert(GcRoot<mirror::Class>(k));
3448 }
3449 size_t pre_zygote_start = result.size();
3450 // Now handle the pre zygote table.
3451 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3452 // called from the debugger.
3453 while (true) {
3454 auto it = pre_zygote_class_table_.Find(descriptor);
3455 if (it == pre_zygote_class_table_.end()) {
3456 break;
3457 }
3458 result.push_back(it->Read());
3459 pre_zygote_class_table_.Erase(it);
3460 }
3461 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3462 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003463 }
3464}
3465
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003466void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003467 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003468 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003469
Ian Rogers9ffb0392012-09-10 11:56:50 -07003470 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003471 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003472 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003473 return;
3474 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003475 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3476 return;
3477 }
jeffhao98eacac2011-09-14 16:11:53 -07003478
Ian Rogers9ffb0392012-09-10 11:56:50 -07003479 // The class might already be erroneous, for example at compile time if we attempted to verify
3480 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003481 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003482 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003483 return;
3484 }
3485
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003486 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003487 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003488 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003489 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003490 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003491 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003492 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003493 }
jeffhao98eacac2011-09-14 16:11:53 -07003494
Jeff Hao4a200f52014-04-01 14:58:49 -07003495 // Skip verification if disabled.
3496 if (!Runtime::Current()->IsVerificationEnabled()) {
3497 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003498 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003499 return;
3500 }
3501
Ian Rogers9ffb0392012-09-10 11:56:50 -07003502 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003503 StackHandleScope<2> hs(self);
3504 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003505 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003506 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003507 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003508
3509 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003510 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003511 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003512 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003513 std::string error_msg(
3514 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3515 PrettyDescriptor(klass.Get()).c_str(),
3516 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003517 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003518 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3519 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003520 self->ClearException();
3521 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003522 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3523 if (cause.Get() != nullptr) {
3524 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003525 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003526 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003527 if (Runtime::Current()->IsCompiler()) {
3528 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3529 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003530 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003531 return;
3532 }
3533 }
3534
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003535 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003536 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003537 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003538 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003539 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003540 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003541 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003542 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003543 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3544 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003545 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003546 return;
3547 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003548 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003549 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003550 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003551 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003552 Runtime::Current()->IsCompiler(),
3553 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003554 }
3555 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003556 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003557 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003558 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3559 << " because: " << error_msg;
3560 }
Ian Rogers1f539342012-10-03 21:09:42 -07003561 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003562 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003563 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003564 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003565 // Even though there were no verifier failures we need to respect whether the super-class
3566 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003567 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003568 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003569 } else {
3570 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003571 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003572 // Pretend a soft failure occured so that we don't consider the class verified below.
3573 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003574 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003575 } else {
3576 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3577 // Soft failures at compile time should be retried at runtime. Soft
3578 // failures at runtime will be handled by slow paths in the generated
3579 // code. Set status accordingly.
3580 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003581 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003582 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003583 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003584 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3585 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003586 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003587 }
3588 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003589 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003590 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003591 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3592 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003593 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003594 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003595 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003596 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003597 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003598 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003599 // Let the interpreter know it by setting the kAccPreverified flag onto each
3600 // method.
3601 // Note: we're going here during compilation and at runtime. When we set the
3602 // kAccPreverified flag when compiling image classes, the flag is recorded
3603 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003604 EnsurePreverifiedMethods(klass);
3605 }
3606}
3607
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003608void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003609 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003610 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003611 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003612 }
jeffhao98eacac2011-09-14 16:11:53 -07003613}
3614
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003615bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3616 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003617 // If we're compiling, we can only verify the class using the oat file if
3618 // we are not compiling the image or if the class we're verifying is not part of
3619 // the app. In other words, we will only check for preverification of bootclasspath
3620 // classes.
3621 if (Runtime::Current()->IsCompiler()) {
3622 // Are we compiling the bootclasspath?
3623 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3624 return false;
3625 }
3626 // We are compiling an app (not the image).
3627
3628 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003629 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003630 return false;
3631 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003632 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003633
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003634 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003635 // In case we run without an image there won't be a backing oat file.
3636 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003637 return false;
3638 }
3639
Andreas Gampe76bd8802014-12-10 16:43:58 -08003640 // We may be running with a preopted oat file but without image. In this case,
3641 // we don't skip verification of preverified classes to ensure we initialize
3642 // dex caches with all types resolved during verification.
3643 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
3644 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
3645 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
3646 // already pre-opted, as then the runtime is started.
3647 if (!Runtime::Current()->IsCompiler() &&
3648 !Runtime::Current()->GetHeap()->HasImageSpace() &&
3649 klass->GetClassLoader() != nullptr) {
3650 return false;
3651 }
3652
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003653 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003654 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003655 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3656 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003657 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003658 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003659 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003660 // Compile time verification failed with a soft error. Compile time verification can fail
3661 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003662 // class ... {
3663 // Foo x;
3664 // .... () {
3665 // if (...) {
3666 // v1 gets assigned a type of resolved class Foo
3667 // } else {
3668 // v1 gets assigned a type of unresolved class Bar
3669 // }
3670 // iput x = v1
3671 // } }
3672 // when we merge v1 following the if-the-else it results in Conflict
3673 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3674 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3675 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3676 // at compile time).
3677 return false;
3678 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003679 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003680 // Compile time verification failed with a hard error. This is caused by invalid instructions
3681 // in the class. These errors are unrecoverable.
3682 return false;
3683 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003684 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003685 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3686 // not loading the class.
3687 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3688 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003689 return false;
3690 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003691 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003692 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003693 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003694 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003695 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003696}
3697
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003698void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003699 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003700 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3701 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3702 }
3703 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3704 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3705 }
3706}
3707
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003708void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003709 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003710 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3711 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003712 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003713 return; // native or abstract method
3714 }
3715 if (code_item->tries_size_ == 0) {
3716 return; // nothing to process
3717 }
Ian Rogers13735952014-10-08 12:43:28 -07003718 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003719 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3720 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3721 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3722 CatchHandlerIterator iterator(handlers_ptr);
3723 for (; iterator.HasNext(); iterator.Next()) {
3724 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3725 // unresolved exception types will be ignored by exception delivery
3726 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003727 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003728 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003729 DCHECK(Thread::Current()->IsExceptionPending());
3730 Thread::Current()->ClearException();
3731 }
3732 }
3733 }
3734 handlers_ptr = iterator.EndDataPointer();
3735 }
3736}
3737
Brian Carlstromea46f952013-07-30 01:26:50 -07003738static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003739static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3740 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003741
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003742mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003743 jobjectArray interfaces, jobject loader,
3744 jobjectArray methods, jobjectArray throws) {
3745 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003746 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003747 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003748 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003749 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003750 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003751 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003752 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003753 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003754 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003755 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3756 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003757 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003758 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003759 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003760 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003761 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003762 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003763
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003764 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003765 {
3766 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003767 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003768 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003769 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003770 }
3771 klass->SetSFields(sfields);
3772 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003773 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3774 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003775 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3776 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003777 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003778 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003779 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003780 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003781 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003782 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003783 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3784 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003785 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3786 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003787 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003788 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003789 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003790 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003791 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003792 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003793 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003794
Ian Rogers466bb252011-10-14 03:29:56 -07003795 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003796 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003797 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003798 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003799 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003800 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003801 }
3802 klass->SetDirectMethods(directs);
3803 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003804 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003805 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003806 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003807 }
3808 klass->SetDirectMethod(0, constructor);
3809 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003810
Mathieu Chartier590fee92013-09-13 13:46:47 -07003811 // Create virtual method using specified prototypes.
3812 size_t num_virtual_methods =
3813 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003814 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003815 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3816 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003817 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003818 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003819 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003820 }
3821 klass->SetVirtualMethods(virtuals);
3822 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003823 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003824 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003825 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3826 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003827 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003828 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003829 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003830 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003831 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003832 }
3833 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003834 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003835
3836 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003837 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003838 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003839
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003840 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3841 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003842 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003843 // Must hold lock on object when resolved.
3844 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003845 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003846 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003847 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003848 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003849 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003850 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003851 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003852 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003853
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003854 CHECK(klass->IsRetired());
3855 CHECK_NE(klass.Get(), new_class);
3856 klass.Assign(new_class);
3857
3858 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003859 interfaces_sfield->SetObject<false>(klass.Get(),
3860 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003861 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003862 throws_sfield->SetObject<false>(klass.Get(),
3863 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003864
3865 {
3866 // Lock on klass is released. Lock new class object.
3867 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003868 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003869 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003870
3871 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003872 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003873 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003874 CheckProxyConstructor(klass->GetDirectMethod(0));
3875 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003876 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003877 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3878 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003879 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3880 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003881 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003882 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003883
Mathieu Chartier590fee92013-09-13 13:46:47 -07003884 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003885 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003886 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003887 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3888
3889 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003890 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003891 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003892
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003893 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003894 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003895 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003896 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003897 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003898 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3899 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003900 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003901 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003902}
3903
Ian Rogersef7d42f2014-01-06 12:55:46 -08003904std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003905 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003906 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003907 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003908 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3909}
3910
Ian Rogersef7d42f2014-01-06 12:55:46 -08003911mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3912 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003913 DCHECK(proxy_class->IsProxyClass());
3914 DCHECK(proxy_method->IsProxyMethod());
3915 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003916 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003917 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003918 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003919 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003920 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003921 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003922 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003923 break;
3924 }
3925 }
3926 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003927 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003928 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003929 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003930 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003931 return resolved_method;
3932}
3933
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003934
Brian Carlstromea46f952013-07-30 01:26:50 -07003935mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003936 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003937 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003938 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003939 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003940 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003941 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3942 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003943 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3944 // constructor method.
3945 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3946 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003947 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3948 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003949 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3950 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003951 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003952 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003953 }
Ian Rogers466bb252011-10-14 03:29:56 -07003954 // Make this constructor public and fix the class to be our Proxy version
3955 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003956 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003957 return constructor;
3958}
3959
Brian Carlstromea46f952013-07-30 01:26:50 -07003960static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003961 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003962 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003963 CHECK_STREQ(constructor->GetName(), "<init>");
3964 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3965 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003966 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003967}
3968
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003969mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003970 Handle<mirror::Class> klass,
3971 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003972 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3973 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003974 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003975 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003976 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003977 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003978 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003979 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003980 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003981 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003982 }
Ian Rogers466bb252011-10-14 03:29:56 -07003983
3984 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3985 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003986 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003987 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003988
Ian Rogers466bb252011-10-14 03:29:56 -07003989 // At runtime the method looks like a reference and argument saving method, clone the code
3990 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003991 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003992 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003993
Ian Rogersc2b44472011-12-14 21:17:17 -08003994 return method;
3995}
Jesse Wilson95caa792011-10-12 18:14:17 -04003996
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003997static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3998 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003999 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004000 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004001 CHECK(!prototype->IsFinal());
4002 CHECK(method->IsFinal());
4003 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004004
4005 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4006 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07004007 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4008 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004009 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4010
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004011 CHECK_STREQ(method->GetName(), prototype->GetName());
4012 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004013 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004014 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004015}
4016
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004017static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4018 bool can_init_parents)
4019 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004020 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004021 return true;
4022 }
4023 if (!can_init_statics) {
4024 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004025 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004026 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004027 return false;
4028 }
4029 // Check if there are encoded static values needing initialization.
4030 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004031 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004032 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004033 if (dex_class_def->static_values_off_ != 0) {
4034 return false;
4035 }
4036 }
4037 }
4038 if (!klass->IsInterface() && klass->HasSuperClass()) {
4039 mirror::Class* super_class = klass->GetSuperClass();
4040 if (!can_init_parents && !super_class->IsInitialized()) {
4041 return false;
4042 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004043 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004044 return false;
4045 }
4046 }
4047 }
4048 return true;
4049}
4050
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004051bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004052 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004053 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4054
4055 // Are we already initialized and therefore done?
4056 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4057 // an initialized class will never change its state.
4058 if (klass->IsInitialized()) {
4059 return true;
4060 }
4061
4062 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004063 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004064 return false;
4065 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004066
Ian Rogers7b078e82014-09-10 14:44:24 -07004067 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004068 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004069 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004070 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004071
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004072 // Re-check under the lock in case another thread initialized ahead of us.
4073 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004074 return true;
4075 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004076
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004077 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004078 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004079 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004080 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004081 return false;
4082 }
4083
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004084 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004085
4086 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004087 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004088 if (!klass->IsVerified()) {
4089 // We failed to verify, expect either the klass to be erroneous or verification failed at
4090 // compile time.
4091 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004092 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004093 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004094 } else {
4095 CHECK(Runtime::Current()->IsCompiler());
4096 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004097 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004098 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004099 } else {
4100 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004101 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004102 }
4103
Brian Carlstromd1422f82011-09-28 11:37:09 -07004104 // If the class is kStatusInitializing, either this thread is
4105 // initializing higher up the stack or another thread has beat us
4106 // to initializing and we need to wait. Either way, this
4107 // invocation of InitializeClass will not be responsible for
4108 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004109 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004110 // Could have got an exception during verification.
4111 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004112 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004113 return false;
4114 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004115 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004116 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004117 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004118 return true;
4119 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004120 // No. That's fine. Wait for another thread to finish initializing.
4121 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004122 }
4123
4124 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004125 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004126 return false;
4127 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004128 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004129
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004130 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004131
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004132 // From here out other threads may observe that we're initializing and so changes of state
4133 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004134 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004135 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004136
4137 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004138 }
4139
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004140 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004141 if (!klass->IsInterface() && klass->HasSuperClass()) {
4142 mirror::Class* super_class = klass->GetSuperClass();
4143 if (!super_class->IsInitialized()) {
4144 CHECK(!super_class->IsInterface());
4145 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004146 StackHandleScope<1> hs(self);
4147 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004148 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004149 if (!super_initialized) {
4150 // The super class was verified ahead of entering initializing, we should only be here if
4151 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004152 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004153 << "Super class initialization failed for "
4154 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004155 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004156 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004157 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004158 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004159 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004160 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004161 return false;
4162 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004163 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004164 }
4165
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004166 const size_t num_static_fields = klass->NumStaticFields();
4167 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004168 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004169 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004170 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004171 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004172 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004173 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004174
4175 // Eagerly fill in static fields so that the we don't have to do as many expensive
4176 // Class::FindStaticField in ResolveField.
4177 for (size_t i = 0; i < num_static_fields; ++i) {
4178 mirror::ArtField* field = klass->GetStaticField(i);
4179 const uint32_t field_idx = field->GetDexFieldIndex();
4180 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4181 if (resolved_field == nullptr) {
4182 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004183 } else {
4184 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004185 }
4186 }
4187
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004188 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4189 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004190 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004191 ClassDataItemIterator field_it(dex_file, class_data);
4192 if (value_it.HasNext()) {
4193 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004194 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004195 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004196 StackHandleScope<1> hs2(self);
4197 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004198 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004199 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004200 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004201 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004202 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004203 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004204 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004205 }
4206 }
4207 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004208
Ian Rogersd91d6d62013-09-25 20:26:14 -07004209 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004210 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004211 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004212 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004213 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004214 }
4215
Ian Rogers7b078e82014-09-10 14:44:24 -07004216 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004217 uint64_t t1 = NanoTime();
4218
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004219 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004220 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004221 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004222
4223 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004224 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004225 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004226 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004227 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004228 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4229 RuntimeStats* thread_stats = self->GetStats();
4230 ++global_stats->class_init_count;
4231 ++thread_stats->class_init_count;
4232 global_stats->class_init_time_ns += (t1 - t0);
4233 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004234 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004235 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004236 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004237 std::string temp;
4238 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004239 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004240 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004241 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004242 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004243 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004244 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004245 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004246}
4247
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004248bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004249 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004250 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004251 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004252 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004253 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004254 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004255
4256 // When we wake up, repeat the test for init-in-progress. If
4257 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004258 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004259 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004260 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004261 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004262 return false;
4263 }
4264 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004265 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004266 continue;
4267 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004268 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004269 // Compile time initialization failed.
4270 return false;
4271 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004272 if (klass->IsErroneous()) {
4273 // The caller wants an exception, but it was thrown in a
4274 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004275 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004276 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004277 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004278 return false;
4279 }
4280 if (klass->IsInitialized()) {
4281 return true;
4282 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004283 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004284 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004285 }
Ian Rogers07140832014-09-30 15:43:59 -07004286 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004287}
4288
Ian Rogersb5fb2072014-12-02 17:22:02 -08004289static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
4290 Handle<mirror::ArtMethod> method1,
4291 Handle<mirror::ArtMethod> method2)
4292 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4293 {
4294 StackHandleScope<1> hs(self);
4295 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
4296 if (UNLIKELY(method2->GetReturnType() != return_type.Get())) {
4297 return false;
4298 }
4299 }
4300 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4301 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4302 if (types1 == nullptr) {
4303 return (types2 == nullptr) || (types2->Size() == 0);
4304 } else if (UNLIKELY(types2 == nullptr)) {
4305 return types1->Size() == 0;
4306 }
4307 uint32_t num_types = types1->Size();
4308 if (UNLIKELY(num_types != types2->Size())) {
4309 return false;
4310 }
4311 for (uint32_t i = 0; i < num_types; ++i) {
4312 mirror::Class* param_type =
4313 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true);
4314 mirror::Class* other_param_type =
4315 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
4316 if (UNLIKELY(param_type != other_param_type)) {
4317 return false;
4318 }
4319 }
4320 return true;
4321}
4322
4323
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004324bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004325 if (klass->IsInterface()) {
4326 return true;
4327 }
Ian Rogers151f2212014-05-06 11:27:27 -07004328 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004329 Thread* self = Thread::Current();
4330 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004331 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
4332 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004333 if (klass->HasSuperClass() &&
4334 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004335 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004336 h_m.Assign(klass->GetVTableEntry(i));
4337 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
4338 if (h_m.Get() != super_h_m.Get() &&
4339 !HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004340 ThrowLinkageError(klass.Get(),
4341 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004342 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogersb5fb2072014-12-02 17:22:02 -08004343 PrettyMethod(h_m.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004344 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004345 return false;
4346 }
4347 }
4348 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004349 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004350 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4351 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4352 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004353 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4354 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
4355 if (h_m.Get() != super_h_m.Get() &&
4356 !HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004357 ThrowLinkageError(klass.Get(),
4358 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004359 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogersb5fb2072014-12-02 17:22:02 -08004360 PrettyMethod(h_m.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004361 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004362 return false;
4363 }
4364 }
4365 }
4366 }
4367 return true;
4368}
4369
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004370bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4371 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004372 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004373 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004374 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004375 return true;
4376 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004377 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004378 if (!success) {
4379 if (can_init_fields && can_init_parents) {
4380 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4381 }
4382 } else {
4383 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004384 }
4385 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004386}
4387
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004388void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4389 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4390 if (fields != nullptr) {
4391 for (int index = 0; index < fields->GetLength(); index ++) {
4392 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4393 fields->Get(index)->SetDeclaringClass(new_class);
4394 }
4395 }
4396 }
4397
4398 fields = new_class->GetSFields();
4399 if (fields != nullptr) {
4400 for (int index = 0; index < fields->GetLength(); index ++) {
4401 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4402 fields->Get(index)->SetDeclaringClass(new_class);
4403 }
4404 }
4405 }
4406
4407 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4408 if (methods != nullptr) {
4409 for (int index = 0; index < methods->GetLength(); index ++) {
4410 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4411 methods->Get(index)->SetDeclaringClass(new_class);
4412 }
4413 }
4414 }
4415
4416 methods = new_class->GetVirtualMethods();
4417 if (methods != nullptr) {
4418 for (int index = 0; index < methods->GetLength(); index ++) {
4419 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4420 methods->Get(index)->SetDeclaringClass(new_class);
4421 }
4422 }
4423 }
4424}
4425
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004426bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4427 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004428 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004429 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004430
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004431 if (!LinkSuperClass(klass)) {
4432 return false;
4433 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004434 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4435 self, Runtime::Current()->GetImtUnimplementedMethod());
4436 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004437 return false;
4438 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004439 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004440 return false;
4441 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004442 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004443 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004444 return false;
4445 }
4446 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004447 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004448
4449 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4450 // We don't need to retire this class as it has no embedded tables or it was created the
4451 // correct size during class linker initialization.
4452 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4453
4454 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004455 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004456 }
4457
4458 // This will notify waiters on klass that saw the not yet resolved
4459 // class in the class_table_ during EnsureResolved.
4460 klass->SetStatus(mirror::Class::kStatusResolved, self);
4461 *new_class = klass.Get();
4462 } else {
4463 CHECK(!klass->IsResolved());
4464 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004465 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004466 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004467 CHECK(self->IsExceptionPending()); // Expect an OOME.
4468 klass->SetStatus(mirror::Class::kStatusError, self);
4469 return false;
4470 }
4471
4472 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4473 StackHandleScope<1> hs(self);
4474 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4475 ObjectLock<mirror::Class> lock(self, new_class_h);
4476
4477 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4478
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004479 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4480 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004481 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004482
4483 // This will notify waiters on temp class that saw the not yet resolved class in the
4484 // class_table_ during EnsureResolved.
4485 klass->SetStatus(mirror::Class::kStatusRetired, self);
4486
4487 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4488 // This will notify waiters on new_class that saw the not yet resolved
4489 // class in the class_table_ during EnsureResolved.
4490 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004491 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004492 return true;
4493}
4494
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004495bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004496 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004497 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4498 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004499 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004500 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004501 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004502 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004503 return false;
4504 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004505 // Verify
4506 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004507 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004508 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004509 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004510 return false;
4511 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004512 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004513 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004514 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004515 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004516 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004517 for (size_t i = 0; i < interfaces->Size(); i++) {
4518 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004519 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004520 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004521 DCHECK(Thread::Current()->IsExceptionPending());
4522 return false;
4523 }
4524 // Verify
4525 if (!klass->CanAccess(interface)) {
4526 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004527 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004528 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004529 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004530 return false;
4531 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004532 }
4533 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004534 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004535 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004536 return true;
4537}
4538
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004539bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004540 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004541 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004542 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004543 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004544 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004545 return false;
4546 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004547 return true;
4548 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004549 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004550 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4551 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004552 return false;
4553 }
4554 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004555 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004556 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004557 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004558 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004559 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004560 return false;
4561 }
4562 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004563 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004564 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004565 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004566 return false;
4567 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004568
Brian Carlstromf3632832014-05-20 15:36:53 -07004569 // Inherit kAccClassIsFinalizable from the superclass in case this
4570 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004571 if (super->IsFinalizable()) {
4572 klass->SetFinalizable();
4573 }
4574
Elliott Hughes2da50362011-10-10 16:57:08 -07004575 // Inherit reference flags (if any) from the superclass.
4576 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4577 if (reference_flags != 0) {
4578 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4579 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004580 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004581 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004582 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004583 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004584 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004585 return false;
4586 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004587
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004588 if (kIsDebugBuild) {
4589 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004590 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004591 CHECK(super->IsResolved());
4592 super = super->GetSuperClass();
4593 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004594 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004595 return true;
4596}
4597
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004598// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004599bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004600 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4601 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004602 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004603 if (klass->IsInterface()) {
4604 // No vtable.
4605 size_t count = klass->NumVirtualMethods();
4606 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004607 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004608 return false;
4609 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004610 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004611 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004612 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004613 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4614 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004615 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004616 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004617}
4618
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004619// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4620// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4621// caches in the implementation below.
4622class MethodNameAndSignatureComparator FINAL : public ValueObject {
4623 public:
4624 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4625 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4626 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4627 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004628 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4629 }
4630
4631 const char* GetName() {
4632 if (name_ == nullptr) {
4633 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4634 }
4635 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004636 }
4637
4638 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4639 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4640 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4641 const DexFile* other_dex_file = other->GetDexFile();
4642 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4643 if (dex_file_ == other_dex_file) {
4644 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4645 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004646 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004647 uint32_t other_name_len;
4648 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4649 &other_name_len);
4650 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4651 return false;
4652 }
4653 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4654 }
4655
4656 private:
4657 // Dex file for the method to compare against.
4658 const DexFile* const dex_file_;
4659 // MethodId for the method to compare against.
4660 const DexFile::MethodId* const mid_;
4661 // Lazily computed name from the dex file's strings.
4662 const char* name_;
4663 // Lazily computed name length.
4664 uint32_t name_len_;
4665};
4666
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004667class LinkVirtualHashTable {
4668 public:
4669 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4670 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4671 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4672 }
4673 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4674 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4675 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004676 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004677 uint32_t index = hash % hash_size_;
4678 // Linear probe until we have an empty slot.
4679 while (hash_table_[index] != invalid_index_) {
4680 if (++index == hash_size_) {
4681 index = 0;
4682 }
4683 }
4684 hash_table_[index] = virtual_method_index;
4685 }
4686 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4687 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4688 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004689 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004690 size_t index = hash % hash_size_;
4691 while (true) {
4692 const uint32_t value = hash_table_[index];
4693 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4694 // the block and can safely assume not found.
4695 if (value == invalid_index_) {
4696 break;
4697 }
4698 if (value != removed_index_) { // This signifies not already overriden.
4699 mirror::ArtMethod* virtual_method =
4700 klass_->GetVirtualMethodDuringLinking(value);
4701 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4702 hash_table_[index] = removed_index_;
4703 return value;
4704 }
4705 }
4706 if (++index == hash_size_) {
4707 index = 0;
4708 }
4709 }
4710 return GetNotFoundIndex();
4711 }
4712 static uint32_t GetNotFoundIndex() {
4713 return invalid_index_;
4714 }
4715
4716 private:
4717 static const uint32_t invalid_index_;
4718 static const uint32_t removed_index_;
4719
4720 Handle<mirror::Class> klass_;
4721 const size_t hash_size_;
4722 uint32_t* const hash_table_;
4723};
4724
4725const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4726const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4727
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004728bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004729 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004730 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004731 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4732 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004733 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004734 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004735 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004736 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4737 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4738 if (UNLIKELY(vtable.Get() == nullptr)) {
4739 CHECK(self->IsExceptionPending()); // OOME.
4740 return false;
4741 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004742 for (size_t i = 0; i < super_vtable_length; i++) {
4743 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004744 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004745 if (num_virtual_methods == 0) {
4746 klass->SetVTable(vtable.Get());
4747 return true;
4748 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004749 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004750 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4751 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4752 if (num_virtual_methods == 0) {
4753 klass->SetVTable(super_vtable);
4754 return true;
4755 }
4756 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004757 if (UNLIKELY(vtable.Get() == nullptr)) {
4758 CHECK(self->IsExceptionPending()); // OOME.
4759 return false;
4760 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004761 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004762 // How the algorithm works:
4763 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4764 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4765 // method which has not been matched to a vtable method, and j if the virtual method at the
4766 // index overrode the super virtual method at index j.
4767 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4768 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4769 // the need for the initial vtable which we later shrink back down).
4770 // 3. Add non overridden methods to the end of the vtable.
4771 static constexpr size_t kMaxStackHash = 250;
4772 const size_t hash_table_size = num_virtual_methods * 3;
4773 uint32_t* hash_table_ptr;
4774 std::unique_ptr<uint32_t[]> hash_heap_storage;
4775 if (hash_table_size <= kMaxStackHash) {
4776 hash_table_ptr = reinterpret_cast<uint32_t*>(
4777 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4778 } else {
4779 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4780 hash_table_ptr = hash_heap_storage.get();
4781 }
4782 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4783 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004784 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004785 hash_table.Add(i);
4786 }
4787 // Loop through each super vtable method and see if they are overriden by a method we added to
4788 // the hash table.
4789 for (size_t j = 0; j < super_vtable_length; ++j) {
4790 // Search the hash table to see if we are overidden by any method.
4791 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4792 MethodNameAndSignatureComparator super_method_name_comparator(
4793 super_method->GetInterfaceMethodIfProxy());
4794 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4795 if (hash_index != hash_table.GetNotFoundIndex()) {
4796 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4797 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4798 super_method->GetAccessFlags())) {
4799 if (super_method->IsFinal()) {
4800 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4801 PrettyMethod(virtual_method).c_str(),
4802 super_method->GetDeclaringClassDescriptor());
4803 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004804 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004805 vtable->SetWithoutChecks<false>(j, virtual_method);
4806 virtual_method->SetMethodIndex(j);
4807 } else {
4808 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004809 << " would have incorrectly overridden the package-private method in "
4810 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004811 }
4812 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004813 }
4814 // Add the non overridden methods at the end.
4815 size_t actual_count = super_vtable_length;
4816 for (size_t i = 0; i < num_virtual_methods; ++i) {
4817 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4818 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4819 if (method_idx < super_vtable_length &&
4820 local_method == vtable->GetWithoutChecks(method_idx)) {
4821 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004822 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004823 vtable->SetWithoutChecks<false>(actual_count, local_method);
4824 local_method->SetMethodIndex(actual_count);
4825 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004826 }
4827 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004828 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004829 return false;
4830 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004831 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004832 CHECK_LE(actual_count, max_count);
4833 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004834 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004835 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004836 CHECK(self->IsExceptionPending()); // OOME.
4837 return false;
4838 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004839 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004840 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004841 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004842 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004843 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004844 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4845 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004846 return false;
4847 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004848 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4849 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004850 CHECK(self->IsExceptionPending()); // OOME.
4851 return false;
4852 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004853 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004854 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004855 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004856 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004857 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004858 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004859 }
4860 return true;
4861}
4862
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004863bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4864 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4865 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004866 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004867 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004868 const bool has_superclass = klass->HasSuperClass();
4869 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4870 const bool have_interfaces = interfaces.Get() != nullptr;
4871 const size_t num_interfaces =
4872 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4873 if (num_interfaces == 0) {
4874 if (super_ifcount == 0) {
4875 // Class implements no interfaces.
4876 DCHECK_EQ(klass->GetIfTableCount(), 0);
4877 DCHECK(klass->GetIfTable() == nullptr);
4878 return true;
4879 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004880 // Class implements same interfaces as parent, are any of these not marker interfaces?
4881 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004882 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004883 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004884 if (super_iftable->GetMethodArrayCount(i) > 0) {
4885 has_non_marker_interface = true;
4886 break;
4887 }
4888 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004889 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004890 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004891 klass->SetIfTable(super_iftable);
4892 return true;
4893 }
4894 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004895 size_t ifcount = super_ifcount + num_interfaces;
4896 for (size_t i = 0; i < num_interfaces; i++) {
4897 mirror::Class* interface = have_interfaces ?
4898 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4899 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004900 if (UNLIKELY(!interface->IsInterface())) {
4901 std::string temp;
4902 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4903 PrettyDescriptor(klass.Get()).c_str(),
4904 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4905 return false;
4906 }
4907 ifcount += interface->GetIfTableCount();
4908 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004909 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004910 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004911 CHECK(self->IsExceptionPending()); // OOME.
4912 return false;
4913 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004914 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004915 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004916 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004917 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004918 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004919 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004920 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004921 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004922 // Flatten the interface inheritance hierarchy.
4923 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004924 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004925 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4926 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004927 // Check if interface is already in iftable
4928 bool duplicate = false;
4929 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004930 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004931 if (existing_interface == interface) {
4932 duplicate = true;
4933 break;
4934 }
4935 }
4936 if (!duplicate) {
4937 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004938 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004939 // Add this interface's non-duplicate super-interfaces.
4940 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004941 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004942 bool super_duplicate = false;
4943 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004944 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004945 if (existing_interface == super_interface) {
4946 super_duplicate = true;
4947 break;
4948 }
4949 }
4950 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004951 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004952 }
4953 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004954 }
4955 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004956 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004957 // Shrink iftable in case duplicates were found
4958 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004959 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004960 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004961 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004962 CHECK(self->IsExceptionPending()); // OOME.
4963 return false;
4964 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004965 ifcount = idx;
4966 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004967 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004968 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004969 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004970 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004971 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004972 return true;
4973 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004974 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004975 size_t max_miranda_methods = 0; // The max size of miranda_list.
4976 for (size_t i = 0; i < ifcount; ++i) {
4977 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4978 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004979 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004980 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004981 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4982 hs.NewHandle(klass->GetVTableDuringLinking()));
4983 // Copy the IMT from the super class if possible.
4984 bool extend_super_iftable = false;
4985 if (has_superclass) {
4986 mirror::Class* super_class = klass->GetSuperClass();
4987 extend_super_iftable = true;
4988 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4989 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4990 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
4991 }
4992 } else {
4993 // No imt in the super class, need to reconstruct from the iftable.
4994 mirror::IfTable* if_table = super_class->GetIfTable();
4995 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4996 const size_t length = super_class->GetIfTableCount();
4997 for (size_t i = 0; i < length; ++i) {
4998 mirror::Class* interface = iftable->GetInterface(i);
4999 const size_t num_virtuals = interface->NumVirtualMethods();
5000 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5001 DCHECK_EQ(num_virtuals, method_array_count);
5002 if (method_array_count == 0) {
5003 continue;
5004 }
5005 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5006 for (size_t j = 0; j < num_virtuals; ++j) {
5007 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5008 if (method->IsMiranda()) {
5009 continue;
5010 }
5011 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5012 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5013 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5014 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5015 out_imt->SetReference(imt_index, method);
5016 } else if (imt_ref != conflict_method) {
5017 out_imt->SetReference(imt_index, conflict_method);
5018 }
5019 }
5020 }
5021 }
5022 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005023 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005024 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005025 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005026 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005027 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005028 const bool is_super = i < super_ifcount;
5029 const bool super_interface = is_super && extend_super_iftable;
5030 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5031 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5032 if (super_interface) {
5033 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5034 DCHECK(if_table != nullptr);
5035 DCHECK(if_table->GetMethodArray(i) != nullptr);
5036 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005037 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005038 AsObjectArray<mirror::ArtMethod>());
5039 // We are overwriting a super class interface, try to only virtual methods instead of the
5040 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005041 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005042 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005043 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005044 // A new interface, we need the whole vtable incase a new interface method is implemented
5045 // in the whole superclass.
5046 input_array = vtable;
5047 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005048 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005049 CHECK(self->IsExceptionPending()); // OOME.
5050 return false;
5051 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005052 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005053 if (input_array.Get() == nullptr) {
5054 // If the added virtual methods is empty, do nothing.
5055 DCHECK(super_interface);
5056 continue;
5057 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005058 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005059 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005060 MethodNameAndSignatureComparator interface_name_comparator(
5061 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005062 int32_t k;
5063 // For each method listed in the interface's method list, find the
5064 // matching method in our class's method list. We want to favor the
5065 // subclass over the superclass, which just requires walking
5066 // back from the end of the vtable. (This only matters if the
5067 // superclass defines a private method and this class redefines
5068 // it -- otherwise it would use the same vtable slot. In .dex files
5069 // those don't end up in the virtual method table, so it shouldn't
5070 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005071 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5072 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005073 mirror::ArtMethod* vtable_method_for_name_comparison =
5074 vtable_method->GetInterfaceMethodIfProxy();
5075 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005076 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005077 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005078 ThrowIllegalAccessError(
5079 klass.Get(),
5080 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005081 PrettyMethod(vtable_method).c_str(),
5082 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005083 return false;
5084 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005085 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005086 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005087 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5088 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5089 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5090 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5091 out_imt->SetReference(imt_index, vtable_method);
5092 } else if (imt_ref != conflict_method) {
5093 // If we are not a conflict and we have the same signature and name as the imt entry,
5094 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005095 MethodNameAndSignatureComparator imt_ref_name_comparator(
5096 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005097 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005098 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005099 out_imt->SetReference(imt_index, vtable_method);
5100 } else {
5101 out_imt->SetReference(imt_index, conflict_method);
5102 }
Jeff Hao88474b42013-10-23 16:24:40 -07005103 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005104 break;
5105 }
5106 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005107 if (k < 0 && !super_interface) {
5108 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005109 for (size_t l = 0; l < miranda_list_size; ++l) {
5110 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005111 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005112 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005113 break;
5114 }
5115 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005116 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005117 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005118 miranda_method = interface_method->Clone(self)->AsArtMethod();
5119 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005120 CHECK(self->IsExceptionPending()); // OOME.
5121 return false;
5122 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005123 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005124 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005125 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005126 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005127 }
5128 }
5129 }
5130 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005131 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005132 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005133 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005134 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5135 if (old_method_count == 0) {
5136 virtuals = AllocArtMethodArray(self, new_method_count);
5137 } else {
5138 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5139 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005140 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005141 CHECK(self->IsExceptionPending()); // OOME.
5142 return false;
5143 }
5144 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005145
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005146 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005147 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005148 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005149 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005150 CHECK(self->IsExceptionPending()); // OOME.
5151 return false;
5152 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005153 for (size_t i = 0; i < miranda_list_size; ++i) {
5154 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005155 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005156 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5157 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5158 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005159 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005160 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005161 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005162 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005163 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005164
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005165 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005166 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5167 for (int i = 0; i < check_vtable->GetLength(); ++i) {
5168 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005169 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005170 }
5171
Ian Rogers7b078e82014-09-10 14:44:24 -07005172 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005173 return true;
5174}
5175
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005176bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005177 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005178 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005179}
5180
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005181bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005182 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005183 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005184}
5185
Brian Carlstromdbc05252011-09-09 01:59:59 -07005186struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005187 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5188 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005189 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005190 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005191 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005192 // 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 -07005193 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5194 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005195 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005196 if (type1 == Primitive::kPrimNot) {
5197 // Reference always goes first.
5198 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005199 }
Vladimir Markod5777482014-11-12 17:02:02 +00005200 if (type2 == Primitive::kPrimNot) {
5201 // Reference always goes first.
5202 return false;
5203 }
5204 size_t size1 = Primitive::ComponentSize(type1);
5205 size_t size2 = Primitive::ComponentSize(type2);
5206 if (size1 != size2) {
5207 // Larger primitive types go first.
5208 return size1 > size2;
5209 }
5210 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5211 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005212 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005213 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5214 // by name and for equal names by type id index.
5215 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5216 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005217 }
5218};
5219
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005220bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005221 size_t* class_size) {
5222 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005223 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005224 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005225
Brian Carlstromea46f952013-07-30 01:26:50 -07005226 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005227 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005228
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005229 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005230 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005231 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00005232 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005233 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005234 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005235 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005236 CHECK(super_class->IsResolved())
5237 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005238 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005239 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005240 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005241
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005242 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005243
Brian Carlstromdbc05252011-09-09 01:59:59 -07005244 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005245 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005246 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005247 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005248 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005249 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005250 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005251 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005252 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005253 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005254 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5255 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005256
Fred Shih381e4ca2014-08-25 17:24:27 -07005257 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005258 size_t current_field = 0;
5259 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005260 FieldGaps gaps;
5261
Brian Carlstromdbc05252011-09-09 01:59:59 -07005262 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005263 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005264 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005265 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005266 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005267 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005268 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005269 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5270 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005271 MemberOffset old_offset = field_offset;
5272 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5273 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5274 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005275 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005276 grouped_and_sorted_fields.pop_front();
5277 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005278 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005279 field_offset = MemberOffset(field_offset.Uint32Value() +
5280 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005281 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005282 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5283 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005284 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5285 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5286 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5287 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005288 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5289 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005290 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005291
Elliott Hughesadb460d2011-10-05 17:02:34 -07005292 // 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 -07005293 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005294 // We know there are no non-reference fields in the Reference classes, and we know
5295 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005296 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005297 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005298 --num_reference_fields;
5299 }
5300
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005301 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005302 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005303 if (is_static) {
5304 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005305 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005306 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005307 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005308 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08005309 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
5310 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
5311 } else {
5312 std::string temp;
5313 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5314 size_t previous_size = klass->GetObjectSize();
5315 if (previous_size != 0) {
5316 // Make sure that we didn't originally have an incorrect size.
5317 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5318 }
5319 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005320 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005321 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005322 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005323
5324 if (kIsDebugBuild) {
5325 // Make sure that the fields array is ordered by name but all reference
5326 // offsets are at the beginning as far as alignment allows.
5327 MemberOffset start_ref_offset = is_static
5328 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5329 : klass->GetFirstReferenceInstanceFieldOffset();
5330 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5331 num_reference_fields *
5332 sizeof(mirror::HeapReference<mirror::Object>));
5333 MemberOffset current_ref_offset = start_ref_offset;
5334 for (size_t i = 0; i < num_fields; i++) {
5335 mirror::ArtField* field = fields->Get(i);
5336 if ((false)) { // enable to debug field layout
5337 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5338 << " class=" << PrettyClass(klass.Get())
5339 << " field=" << PrettyField(field)
5340 << " offset="
5341 << field->GetField32(mirror::ArtField::OffsetOffset());
5342 }
5343 if (i != 0) {
5344 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005345 // NOTE: The field names can be the same. This is not possible in the Java language
5346 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5347 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005348 }
5349 Primitive::Type type = field->GetTypeAsPrimitiveType();
5350 bool is_primitive = type != Primitive::kPrimNot;
5351 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5352 strcmp("referent", field->GetName()) == 0) {
5353 is_primitive = true; // We lied above, so we have to expect a lie here.
5354 }
5355 MemberOffset offset = field->GetOffsetDuringLinking();
5356 if (is_primitive) {
5357 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5358 // Shuffled before references.
5359 size_t type_size = Primitive::ComponentSize(type);
5360 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5361 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5362 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5363 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5364 }
5365 } else {
5366 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5367 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5368 sizeof(mirror::HeapReference<mirror::Object>));
5369 }
5370 }
5371 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5372 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005373 return true;
5374}
5375
Vladimir Marko76649e82014-11-10 18:32:59 +00005376// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005377void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005378 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005379 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005380 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005381 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005382 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005383 // Compute reference offsets unless our superclass overflowed.
5384 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5385 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005386 if (num_reference_fields != 0u) {
5387 // All of the fields that contain object references are guaranteed be grouped in memory
5388 // starting at an appropriately aligned address after super class object data.
5389 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5390 sizeof(mirror::HeapReference<mirror::Object>));
5391 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005392 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005393 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005394 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005395 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005396 reference_offsets |= (0xffffffffu << start_bit) &
5397 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005398 }
5399 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005400 }
5401 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005402 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005403}
5404
Mathieu Chartier590fee92013-09-13 13:46:47 -07005405mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005406 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005407 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005408 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005409 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005410 return resolved;
5411 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005412 uint32_t utf16_length;
5413 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005414 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005415 dex_cache->SetResolvedString(string_idx, string);
5416 return string;
5417}
5418
Mathieu Chartier590fee92013-09-13 13:46:47 -07005419mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005420 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005421 StackHandleScope<2> hs(Thread::Current());
5422 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5423 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005424 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5425}
5426
5427mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005428 Handle<mirror::DexCache> dex_cache,
5429 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005430 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005431 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005432 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005433 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005434 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005435 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005436 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005437 // TODO: we used to throw here if resolved's class loader was not the
5438 // boot class loader. This was to permit different classes with the
5439 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005440 dex_cache->SetResolvedType(type_idx, resolved);
5441 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005442 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005443 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005444 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005445 StackHandleScope<1> hs(self);
5446 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005447 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005448 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005449 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005450 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005451 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005452 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005453 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005454 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005455 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005456 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005457 return resolved;
5458}
5459
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005460mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005461 Handle<mirror::DexCache> dex_cache,
5462 Handle<mirror::ClassLoader> class_loader,
5463 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005464 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005465 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005466 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005467 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005468 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005469 return resolved;
5470 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005471 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005472 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005473 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005474 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005475 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005476 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005477 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005478 // Scan using method_idx, this saves string compares but will only hit for matching dex
5479 // caches/files.
5480 switch (type) {
5481 case kDirect: // Fall-through.
5482 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005483 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005484 break;
5485 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005486 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005487 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005488 break;
5489 case kSuper: // Fall-through.
5490 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005491 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005492 break;
5493 default:
5494 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005495 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005496 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005497 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005498 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005499 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005500 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005501 switch (type) {
5502 case kDirect: // Fall-through.
5503 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005504 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005505 break;
5506 case kInterface:
5507 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005508 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005509 break;
5510 case kSuper: // Fall-through.
5511 case kVirtual:
5512 resolved = klass->FindVirtualMethod(name, signature);
5513 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005514 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005515 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005516 // If we found a method, check for incompatible class changes.
5517 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005518 // Be a good citizen and update the dex cache to speed subsequent calls.
5519 dex_cache->SetResolvedMethod(method_idx, resolved);
5520 return resolved;
5521 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005522 // If we had a method, it's an incompatible-class-change error.
5523 if (resolved != nullptr) {
5524 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5525 } else {
5526 // We failed to find the method which means either an access error, an incompatible class
5527 // change, or no such method. First try to find the method among direct and virtual methods.
5528 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5529 const Signature signature = dex_file.GetMethodSignature(method_id);
5530 switch (type) {
5531 case kDirect:
5532 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005533 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005534 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5535 // have had a resolved method before, which triggers the "true" branch above.
5536 break;
5537 case kInterface:
5538 case kVirtual:
5539 case kSuper:
5540 resolved = klass->FindDirectMethod(name, signature);
5541 break;
5542 }
5543
5544 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005545 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005546 if (resolved != nullptr && referrer.Get() != nullptr) {
5547 mirror::Class* methods_class = resolved->GetDeclaringClass();
5548 mirror::Class* referring_class = referrer->GetDeclaringClass();
5549 if (!referring_class->CanAccess(methods_class)) {
5550 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5551 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005552 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005553 } else if (!referring_class->CanAccessMember(methods_class,
5554 resolved->GetAccessFlags())) {
5555 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005556 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005557 }
5558 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005559 if (!exception_generated) {
5560 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5561 // interface methods and throw if we find the method there. If we find nothing, throw a
5562 // NoSuchMethodError.
5563 switch (type) {
5564 case kDirect:
5565 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005566 if (resolved != nullptr) {
5567 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5568 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005569 resolved = klass->FindInterfaceMethod(name, signature);
5570 if (resolved != nullptr) {
5571 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5572 } else {
5573 ThrowNoSuchMethodError(type, klass, name, signature);
5574 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005575 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005576 break;
5577 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005578 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005579 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5580 } else {
5581 resolved = klass->FindVirtualMethod(name, signature);
5582 if (resolved != nullptr) {
5583 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5584 } else {
5585 ThrowNoSuchMethodError(type, klass, name, signature);
5586 }
5587 }
5588 break;
5589 case kSuper:
5590 if (resolved != nullptr) {
5591 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005592 } else {
5593 ThrowNoSuchMethodError(type, klass, name, signature);
5594 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005595 break;
5596 case kVirtual:
5597 if (resolved != nullptr) {
5598 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5599 } else {
5600 resolved = klass->FindInterfaceMethod(name, signature);
5601 if (resolved != nullptr) {
5602 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5603 } else {
5604 ThrowNoSuchMethodError(type, klass, name, signature);
5605 }
5606 }
5607 break;
5608 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005609 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005610 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005611 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005612 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005613 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005614}
5615
Mathieu Chartier590fee92013-09-13 13:46:47 -07005616mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005617 Handle<mirror::DexCache> dex_cache,
5618 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005619 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005620 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005621 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005622 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005623 return resolved;
5624 }
5625 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005626 Thread* const self = Thread::Current();
5627 StackHandleScope<1> hs(self);
5628 Handle<mirror::Class> klass(
5629 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005630 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005631 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005632 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005633 }
5634
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005635 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005636 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005637 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005638 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005639 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005640
Andreas Gampe58a5af82014-07-31 16:23:49 -07005641 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005642 const char* name = dex_file.GetFieldName(field_id);
5643 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5644 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005645 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005646 } else {
5647 resolved = klass->FindInstanceField(name, type);
5648 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005649 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005650 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005651 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005652 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005653 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005654 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005655 return resolved;
5656}
5657
Brian Carlstromea46f952013-07-30 01:26:50 -07005658mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005659 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005660 Handle<mirror::DexCache> dex_cache,
5661 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005662 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005663 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005664 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005665 return resolved;
5666 }
5667 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005668 Thread* self = Thread::Current();
5669 StackHandleScope<1> hs(self);
5670 Handle<mirror::Class> klass(
5671 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005672 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005673 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005674 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005675 }
5676
Ian Rogersdfb325e2013-10-30 01:00:44 -07005677 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5678 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005679 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005680 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005681 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005682 dex_cache->SetResolvedField(field_idx, resolved);
5683 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005684 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005685 }
5686 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005687}
5688
Brian Carlstromea46f952013-07-30 01:26:50 -07005689const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005690 uint32_t* length) {
5691 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5692 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005693 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005694 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005695 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005696}
5697
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005698void ClassLinker::DumpAllClasses(int flags) {
5699 if (dex_cache_image_class_lookup_required_) {
5700 MoveImageClassesToClassTable();
5701 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005702 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5703 // 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 -08005704 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005705 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005706 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005707 for (GcRoot<mirror::Class>& it : class_table_) {
5708 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005709 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005710 }
5711
5712 for (size_t i = 0; i < all_classes.size(); ++i) {
5713 all_classes[i]->DumpClass(std::cerr, flags);
5714 }
5715}
5716
Elliott Hughes956af0f2014-12-11 14:34:28 -08005717static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005718 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005719 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5720 base -= sizeof(void*); // Move backward so that code_offset != 0.
5721 const uint32_t code_offset = sizeof(void*);
5722 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005723}
5724
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005725bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5726 return (entry_point == GetQuickResolutionStub()) ||
5727 (quick_resolution_trampoline_ == entry_point);
5728}
5729
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005730bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5731 return (entry_point == GetQuickToInterpreterBridge()) ||
5732 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5733}
5734
5735bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5736 return (entry_point == GetQuickGenericJniStub()) ||
5737 (quick_generic_jni_trampoline_ == entry_point);
5738}
5739
5740const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5741 return GetQuickGenericJniStub();
5742}
5743
Elliott Hughes956af0f2014-12-11 14:34:28 -08005744void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5745 const void* method_code) const {
5746 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005747 oat_method.LinkMethod(method);
5748 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005749}
5750
5751void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5752 if (!method->IsNative()) {
5753 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005754 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5755 } else {
5756 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005757 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005758 oat_method.LinkMethod(method);
5759 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005760 }
5761}
5762
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005763void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005764 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005765 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005766 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005767 MoveImageClassesToClassTable();
5768 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005769 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005770 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5771 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005772}
5773
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005774size_t ClassLinker::NumLoadedClasses() {
5775 if (dex_cache_image_class_lookup_required_) {
5776 MoveImageClassesToClassTable();
5777 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005778 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005779 // Only return non zygote classes since these are the ones which apps which care about.
5780 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005781}
5782
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005783pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005784 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005785}
5786
5787pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005788 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005789}
5790
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005791void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005792 DCHECK(!init_done_);
5793
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005794 DCHECK(klass != nullptr);
5795 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005796
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005797 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005798 DCHECK(class_roots != nullptr);
5799 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005800 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005801}
5802
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005803const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5804 static const char* class_roots_descriptors[] = {
5805 "Ljava/lang/Class;",
5806 "Ljava/lang/Object;",
5807 "[Ljava/lang/Class;",
5808 "[Ljava/lang/Object;",
5809 "Ljava/lang/String;",
5810 "Ljava/lang/DexCache;",
5811 "Ljava/lang/ref/Reference;",
5812 "Ljava/lang/reflect/ArtField;",
5813 "Ljava/lang/reflect/ArtMethod;",
5814 "Ljava/lang/reflect/Proxy;",
5815 "[Ljava/lang/String;",
5816 "[Ljava/lang/reflect/ArtField;",
5817 "[Ljava/lang/reflect/ArtMethod;",
5818 "Ljava/lang/ClassLoader;",
5819 "Ljava/lang/Throwable;",
5820 "Ljava/lang/ClassNotFoundException;",
5821 "Ljava/lang/StackTraceElement;",
5822 "Z",
5823 "B",
5824 "C",
5825 "D",
5826 "F",
5827 "I",
5828 "J",
5829 "S",
5830 "V",
5831 "[Z",
5832 "[B",
5833 "[C",
5834 "[D",
5835 "[F",
5836 "[I",
5837 "[J",
5838 "[S",
5839 "[Ljava/lang/StackTraceElement;",
5840 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005841 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5842 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005843
5844 const char* descriptor = class_roots_descriptors[class_root];
5845 CHECK(descriptor != nullptr);
5846 return descriptor;
5847}
5848
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005849std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5850 const {
5851 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005852 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005853}
5854
5855bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5856 const GcRoot<mirror::Class>& b) {
5857 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5858 return false;
5859 }
5860 std::string temp;
5861 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5862}
5863
5864std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5865 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005866 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005867}
5868
5869bool ClassLinker::ClassDescriptorHashEquals::operator()(
5870 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
5871 if (a.Read()->GetClassLoader() != b.second) {
5872 return false;
5873 }
5874 return a.Read()->DescriptorEquals(b.first);
5875}
5876
5877bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5878 const char* descriptor) {
5879 return a.Read()->DescriptorEquals(descriptor);
5880}
5881
5882std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005883 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005884}
5885
Sebastien Hertz6963e442014-11-26 22:11:27 +01005886bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
5887 // Non-image methods don't use direct code pointer.
5888 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
5889 return false;
5890 }
5891 if (m->IsPrivate()) {
5892 // The method can only be called inside its own oat file. Therefore it won't be called using
5893 // its direct code if the oat file has been compiled in PIC mode.
5894 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
5895 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
5896 const OatFile::OatDexFile* oat_dex_file = class_linker->FindOpenedOatDexFileForDexFile(dex_file);
5897 if (oat_dex_file == nullptr) {
5898 // No oat file: the method has not been compiled.
5899 return false;
5900 }
5901 const OatFile* oat_file = oat_dex_file->GetOatFile();
5902 return oat_file != nullptr && !oat_file->IsPic();
5903 } else {
5904 // The method can be called outside its own oat file. Therefore it won't be called using its
5905 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
5906 ReaderMutexLock mu(Thread::Current(), dex_lock_);
5907 for (const OatFile* oat_file : oat_files_) {
5908 if (!oat_file->IsPic()) {
5909 return true;
5910 }
5911 }
5912 return false;
5913 }
5914}
5915
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005916} // namespace art