blob: 05b6b1dba5f6a84fd5e12717eb4b5a5dbd1355a3 [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
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800249void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<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());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800408 for (auto& dex_file : boot_class_path) {
409 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700410 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800411 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700412 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
414 // now we can use FindSystemClass
415
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700416 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700417 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
418 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700419
Jeff Hao88474b42013-10-23 16:24:40 -0700420 // Create runtime resolution and imt conflict methods. Also setup the default imt.
421 Runtime* runtime = Runtime::Current();
422 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
423 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700424 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700425 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
426
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700427 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
428 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700429 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Alex Light64ad14d2014-08-19 14:23:13 -0700430 if (!runtime->IsCompiler()) {
431 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700432 quick_resolution_trampoline_ = GetQuickResolutionStub();
433 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
434 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700435 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700436
Mathieu Chartier66f19252012-09-18 08:57:04 -0700437 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700438 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800439 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700440 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700441 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700442 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800443 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700444 std::ostringstream os1, os2;
445 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
446 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
447 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
448 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700449 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800450 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700451 CHECK_EQ(java_lang_String.Get(), String_class);
452 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700453 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454
Ian Rogers23435d02012-09-24 11:23:12 -0700455 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800456 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800457 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700458
Ian Rogers98379392014-02-24 16:53:16 -0800459 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800460 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700461
Ian Rogers98379392014-02-24 16:53:16 -0800462 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700463 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700464
Ian Rogers98379392014-02-24 16:53:16 -0800465 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800466 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700467
Ian Rogers98379392014-02-24 16:53:16 -0800468 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700469 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470
Ian Rogers98379392014-02-24 16:53:16 -0800471 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800472 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700473
Ian Rogers98379392014-02-24 16:53:16 -0800474 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800475 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700476
Ian Rogers98379392014-02-24 16:53:16 -0800477 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800478 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700479
Ian Rogers98379392014-02-24 16:53:16 -0800480 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700481 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700482
Ian Rogers98379392014-02-24 16:53:16 -0800483 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700484 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700485
Ian Rogers23435d02012-09-24 11:23:12 -0700486 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800487 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700488 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800489 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700490 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700491 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
492 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700493 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700494 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700495 array_iftable->SetInterface(0, java_lang_Cloneable);
496 array_iftable->SetInterface(1, java_io_Serializable);
497 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700498
Ian Rogers23435d02012-09-24 11:23:12 -0700499 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700500 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
501 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
502 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
503 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700504 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700505 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800506 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700507 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700508
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700509 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800510 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700511 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700512
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700513 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800514 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700515 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700516
Brian Carlstromf3632832014-05-20 15:36:53 -0700517 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700518 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700519 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700520
Brian Carlstromea46f952013-07-30 01:26:50 -0700521 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700522 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700523 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700524
Brian Carlstromea46f952013-07-30 01:26:50 -0700525 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700526 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700527 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700528
Ian Rogers23435d02012-09-24 11:23:12 -0700529 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700530
Ian Rogers23435d02012-09-24 11:23:12 -0700531 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800532 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700533 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
534
Brian Carlstrom1f870082011-08-23 16:02:11 -0700535 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700536 // finish initializing Reference class
537 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
538 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
539 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
540 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
541 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700542 mirror::Class* java_lang_ref_FinalizerReference =
543 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700544 java_lang_ref_FinalizerReference->SetAccessFlags(
545 java_lang_ref_FinalizerReference->GetAccessFlags() |
546 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700547 mirror::Class* java_lang_ref_PhantomReference =
548 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700549 java_lang_ref_PhantomReference->SetAccessFlags(
550 java_lang_ref_PhantomReference->GetAccessFlags() |
551 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700552 mirror::Class* java_lang_ref_SoftReference =
553 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700554 java_lang_ref_SoftReference->SetAccessFlags(
555 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700556 mirror::Class* java_lang_ref_WeakReference =
557 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700558 java_lang_ref_WeakReference->SetAccessFlags(
559 java_lang_ref_WeakReference->GetAccessFlags() |
560 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700561
Ian Rogers23435d02012-09-24 11:23:12 -0700562 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800563 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700564 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700565 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
566
jeffhao8cd6dda2012-02-22 10:15:34 -0800567 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700568 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800569 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800570 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700571 SetClassRoot(kJavaLangClassNotFoundException,
572 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800573 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700574 SetClassRoot(kJavaLangStackTraceElementArrayClass,
575 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800576 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700577
Andreas Gampe76bd8802014-12-10 16:43:58 -0800578 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
579 // initialized.
580 {
581 const DexFile& dex_file = java_lang_Object->GetDexFile();
582 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
583 CHECK(void_string_id != nullptr);
584 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
585 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
586 CHECK(void_type_id != nullptr);
587 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
588 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
589 // as referrer so the used dex cache is core's one.
590 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
591 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
592 self->AssertNoPendingException();
593 }
594
Ian Rogers98379392014-02-24 16:53:16 -0800595 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700596
Brian Carlstroma004aa92012-02-08 18:05:09 -0800597 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700598}
599
Ian Rogers98379392014-02-24 16:53:16 -0800600void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800601 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700602
603 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700604 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700605 // as the types of the field can't be resolved prior to the runtime being
606 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800607 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700608 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800609 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800610
Brian Carlstromea46f952013-07-30 01:26:50 -0700611 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700612 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
613 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700614
Brian Carlstromea46f952013-07-30 01:26:50 -0700615 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700616 CHECK_STREQ(queue->GetName(), "queue");
617 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700618
Brian Carlstromea46f952013-07-30 01:26:50 -0700619 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700620 CHECK_STREQ(queueNext->GetName(), "queueNext");
621 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700622
Brian Carlstromea46f952013-07-30 01:26:50 -0700623 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700624 CHECK_STREQ(referent->GetName(), "referent");
625 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700626
Brian Carlstromea46f952013-07-30 01:26:50 -0700627 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700628 CHECK_STREQ(zombie->GetName(), "zombie");
629 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700630
Brian Carlstroma663ea52011-08-19 23:33:41 -0700631 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700632 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700633 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800634 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700635 CHECK(klass != nullptr);
636 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700637 // note SetClassRoot does additional validation.
638 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700639 }
640
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700641 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700642
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700643 // disable the slow paths in FindClass and CreatePrimitiveClass now
644 // that Object, Class, and Object[] are setup
645 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700646
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800647 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700648}
649
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700650void ClassLinker::RunRootClinits() {
651 Thread* self = Thread::Current();
652 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800653 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700654 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700655 StackHandleScope<1> hs(self);
656 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700657 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700658 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700659 }
660 }
661}
662
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700663bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800664 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000665 const char* oat_cache_filename,
666 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700667 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700668 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800669
Ian Rogers1d54e732013-05-02 21:10:01 -0700670 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800671 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700672 if (heap->GetImageSpace() == nullptr) {
673 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
674 // out of space anyway it might not matter.
675 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
676 "without an image.", dex_filename);
677 return false;
678 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700679 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800680
Brian Carlstrom6449c622014-02-10 23:48:36 -0800681 std::string dex_file_option("--dex-file=");
682 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800683
Brian Carlstrom6449c622014-02-10 23:48:36 -0800684 std::string oat_fd_option("--oat-fd=");
685 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800686
Brian Carlstrom6449c622014-02-10 23:48:36 -0800687 std::string oat_location_option("--oat-location=");
688 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800689
Brian Carlstrom6449c622014-02-10 23:48:36 -0800690 std::vector<std::string> argv;
691 argv.push_back(dex2oat);
692 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800693 argv.push_back("-classpath");
694 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800695 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800696
Ian Rogers8afeb852014-04-02 14:55:49 -0700697 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800698
Jeff Hao4a200f52014-04-01 14:58:49 -0700699 if (!Runtime::Current()->IsVerificationEnabled()) {
700 argv.push_back("--compiler-filter=verify-none");
701 }
702
Alex Light6e183f22014-07-18 14:57:04 -0700703 if (Runtime::Current()->MustRelocateIfPossible()) {
704 argv.push_back("--runtime-arg");
705 argv.push_back("-Xrelocate");
706 } else {
707 argv.push_back("--runtime-arg");
708 argv.push_back("-Xnorelocate");
709 }
710
Brian Carlstrom6449c622014-02-10 23:48:36 -0800711 if (!kIsTargetBuild) {
712 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700713 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700714
Brian Carlstrom6449c622014-02-10 23:48:36 -0800715 argv.push_back(boot_image_option);
716 argv.push_back(dex_file_option);
717 argv.push_back(oat_fd_option);
718 argv.push_back(oat_location_option);
719 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800720 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800721 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700722 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800723
Andreas Gampea696c0a2014-12-10 20:51:45 -0800724 if (!Exec(argv, error_msg)) {
725 // Manually delete the file. Ensures there is no garbage left over if the process unexpectedly
726 // died. Ignore unlink failure, propagate the original error.
727 TEMP_FAILURE_RETRY(unlink(oat_cache_filename));
728 return false;
729 }
730
731 return true;
jeffhao262bf462011-10-20 18:36:32 -0700732}
733
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700734const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700735 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800736 if (kIsDebugBuild) {
737 for (size_t i = 0; i < oat_files_.size(); ++i) {
738 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700739 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800740 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700741 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
742 oat_files_.push_back(oat_file);
743 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800744}
745
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700746OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
747 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700748 OatFile* oat_file = space->ReleaseOatFile();
749 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700750 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700751 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700752}
753
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100754const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800755 const char* dex_location = dex_file.GetLocation().c_str();
756 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100757 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800758}
759
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100760const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
761 const char* dex_location,
762 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700763 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100764 for (const OatFile* oat_file : oat_files_) {
765 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700766
767 if (oat_location != nullptr) {
768 if (oat_file->GetLocation() != oat_location) {
769 continue;
770 }
771 }
772
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700773 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800774 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700775 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100776 if (oat_dex_file != nullptr) {
777 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800778 }
779 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100780 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800781}
782
Calin Juravle621962a2014-09-02 15:53:55 +0100783
784// Loads all multi dex files from the given oat file returning true on success.
785//
786// Parameters:
787// oat_file - the oat file to load from
788// dex_location - the dex location used to generate the oat file
789// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
790// generated - whether or not the oat_file existed before or was just (re)generated
791// error_msgs - any error messages will be appended here
792// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
793static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
794 const char* dex_location,
795 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700796 bool generated,
797 std::vector<std::string>* error_msgs,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800798 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700799 if (oat_file == nullptr) {
800 return false;
801 }
802
803 size_t old_size = dex_files->size(); // To rollback on error.
804
805 bool success = true;
806 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100807 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700808 const char* next_name = next_name_str.c_str();
809
Calin Juravle621962a2014-09-02 15:53:55 +0100810 uint32_t next_location_checksum;
811 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700812 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100813 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
814 // When i=0 the multidex name should be the same as the location name. We already have the
815 // checksum it so we don't need to recompute it.
816 if (dex_location_checksum == nullptr) {
817 next_location_checksum_pointer = nullptr;
818 } else {
819 next_location_checksum = *dex_location_checksum;
820 }
821 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700822 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100823 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700824 }
825
826 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
827
828 if (oat_dex_file == nullptr) {
829 if (i == 0 && generated) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700830 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100831 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700832 oat_file->GetLocation().c_str());
833 error_msgs->push_back(error_msg);
834 }
835 break; // Not found, done.
836 }
837
838 // Checksum test. Test must succeed when generated.
839 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100840 if (next_location_checksum_pointer != nullptr) {
841 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700842 }
843
844 if (success) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800845 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
846 if (dex_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700847 success = false;
848 error_msgs->push_back(error_msg);
849 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800850 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700851 }
852 }
853
854 // When we generated the file, we expect success, or something is terribly wrong.
855 CHECK_EQ(false, generated && !success)
856 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100857 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700858 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
859 }
860
861 if (dex_files->size() == old_size) {
862 success = false; // We did not even find classes.dex
863 }
864
865 if (success) {
866 return true;
867 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800868 dex_files->erase(dex_files->begin() + old_size, dex_files->end());
Andreas Gampe833a4852014-05-21 18:46:59 -0700869 return false;
870 }
871}
872
873// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
874// complicates the loading process, as we should not use an iterative loading process, because that
875// would register the oat file and dex files that come before the broken one. Instead, check all
876// multidex ahead of time.
877bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
878 std::vector<std::string>* error_msgs,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800879 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700880 // 1) Check whether we have an open oat file.
881 // This requires a dex checksum, use the "primary" one.
882 uint32_t dex_location_checksum;
883 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
884 bool have_checksum = true;
885 std::string checksum_error_msg;
886 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100887 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700888 dex_location_checksum_pointer = nullptr;
889 have_checksum = false;
890 }
891
892 bool needs_registering = false;
893
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100894 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
895 dex_location_checksum_pointer);
896 std::unique_ptr<const OatFile> open_oat_file(
897 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700898
899 // 2) If we do not have an open one, maybe there's one on disk already.
900
901 // In case the oat file is not open, we play a locking game here so
902 // that if two different processes race to load and register or generate
903 // (or worse, one tries to open a partial generated file) we will be okay.
904 // This is actually common with apps that use DexClassLoader to work
905 // around the dex method reference limit and that have a background
906 // service running in a separate process.
907 ScopedFlock scoped_flock;
908
909 if (open_oat_file.get() == nullptr) {
910 if (oat_location != nullptr) {
911 // Can only do this if we have a checksum, else error.
912 if (!have_checksum) {
913 error_msgs->push_back(checksum_error_msg);
914 return false;
915 }
916
917 std::string error_msg;
918
919 // We are loading or creating one in the future. Time to set up the file lock.
920 if (!scoped_flock.Init(oat_location, &error_msg)) {
921 error_msgs->push_back(error_msg);
922 return false;
923 }
924
Alex Lighta59dd802014-07-02 16:28:08 -0700925 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700926 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
927 oat_location, &error_msg));
928
929 if (open_oat_file.get() == nullptr) {
930 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
931 dex_location, oat_location, error_msg.c_str());
932 VLOG(class_linker) << compound_msg;
933 error_msgs->push_back(compound_msg);
934 }
935 } else {
936 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100937 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700938 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
939 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100940 kRuntimeISA, error_msgs,
941 &obsolete_file_cleanup_failed));
942 // There's no point in going forward and eventually try to regenerate the
943 // file if we couldn't remove the obsolete one. Mostly likely we will fail
944 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100945 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
946 if (obsolete_file_cleanup_failed) {
947 return false;
948 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700949 }
950 needs_registering = true;
951 }
952
953 // 3) If we have an oat file, check all contained multidex files for our dex_location.
954 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100955 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
956 dex_location_checksum_pointer,
957 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700958 if (success) {
959 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
960 if (needs_registering) {
961 // We opened the oat file, so we must register it.
962 RegisterOatFile(oat_file);
963 }
Alex Light9dcc4572014-08-14 14:16:26 -0700964 // If the file isn't executable we failed patchoat but did manage to get the dex files.
965 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700966 } else {
967 if (needs_registering) {
968 // We opened it, delete it.
969 open_oat_file.reset();
970 } else {
971 open_oat_file.release(); // Do not delete open oat files.
972 }
973 }
974
975 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
976
977 // Need a checksum, fail else.
978 if (!have_checksum) {
979 error_msgs->push_back(checksum_error_msg);
980 return false;
981 }
982
983 // Look in cache location if no oat_location is given.
984 std::string cache_location;
985 if (oat_location == nullptr) {
986 // Use the dalvik cache.
987 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
988 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
989 oat_location = cache_location.c_str();
990 }
991
Alex Light64ad14d2014-08-19 14:23:13 -0700992 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700993 // Definitely need to lock now.
994 if (!scoped_flock.HasFile()) {
995 std::string error_msg;
996 if (!scoped_flock.Init(oat_location, &error_msg)) {
997 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700998 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -0700999 }
1000 }
1001
Alex Light64ad14d2014-08-19 14:23:13 -07001002 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001003 // Create the oat file.
1004 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1005 oat_location, error_msgs));
1006 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001007
1008 // Failed, bail.
1009 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001010 std::string error_msg;
1011 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1012 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1013 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001014 return false;
1015 }
1016
1017 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001018 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1019 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001020 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001021 if (success) {
1022 RegisterOatFile(open_oat_file.release());
1023 return true;
1024 } else {
1025 return false;
1026 }
1027}
1028
1029const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1030 uint32_t dex_location_checksum,
1031 const char* oat_location,
1032 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001033 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001034 !Runtime::Current()->IsCompiler(),
1035 error_msg));
1036 if (oat_file.get() == nullptr) {
1037 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1038 error_msg->c_str());
1039 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001040 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001041 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001042 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1043 if (image_space != nullptr) {
1044 const ImageHeader& image_header = image_space->GetImageHeader();
1045 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1046 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1047 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1048 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1049 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1050 actual_image_oat_checksum);
1051 return nullptr;
1052 }
1053
1054 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1055 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1056 if (expected_image_oat_offset != actual_image_oat_offset) {
1057 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1058 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1059 actual_image_oat_offset);
1060 return nullptr;
1061 }
1062 int32_t expected_patch_delta = image_header.GetPatchDelta();
1063 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1064 if (expected_patch_delta != actual_patch_delta) {
1065 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1066 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1067 return nullptr;
1068 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001069 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001070
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001071 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1072 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001073 if (oat_dex_file == nullptr) {
1074 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1075 dex_location);
1076 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001077 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001078 uint32_t expected_dex_checksum = dex_location_checksum;
1079 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1080 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001081 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1082 "found 0x%x", oat_location, expected_dex_checksum,
1083 actual_dex_checksum);
1084 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001085 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001086 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1087 if (dex_file.get() != nullptr) {
1088 return oat_file.release();
1089 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001090 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001091 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001092}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001093
Andreas Gampe833a4852014-05-21 18:46:59 -07001094const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1095 int fd, const char* oat_location,
1096 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001097 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001098 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001099 std::string error_msg;
1100 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001101 CHECK(!error_msg.empty());
1102 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001103 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001104 }
Igor Murashkin46774762014-10-22 11:37:02 -07001105 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001106 !Runtime::Current()->IsCompiler(),
1107 &error_msg));
1108 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001109 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1110 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001111 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001112 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001113 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001114
1115 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001116}
1117
Alex Light6e183f22014-07-18 14:57:04 -07001118bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1119 const InstructionSet instruction_set) {
1120 Runtime* runtime = Runtime::Current();
1121 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001122 if (image_space == nullptr) {
1123 return false;
1124 }
Alex Light6e183f22014-07-18 14:57:04 -07001125 uint32_t image_oat_checksum = 0;
1126 if (instruction_set == kRuntimeISA) {
1127 const ImageHeader& image_header = image_space->GetImageHeader();
1128 image_oat_checksum = image_header.GetOatChecksum();
1129 } else {
1130 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1131 image_space->GetImageLocation().c_str(), instruction_set));
1132 image_oat_checksum = image_header->GetOatChecksum();
1133 }
1134 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1135}
1136
1137bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1138 const InstructionSet instruction_set,
1139 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001140 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001141 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001142 if (image_space == nullptr) {
1143 *error_msg = "No image space for verification against";
1144 return false;
1145 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001146
1147 // If the requested instruction set is the same as the current runtime,
1148 // we can use the checksums directly. If it isn't, we'll have to read the
1149 // image header from the image for the right instruction set.
1150 uint32_t image_oat_checksum = 0;
1151 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001152 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001153 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001154 const ImageHeader& image_header = image_space->GetImageHeader();
1155 image_oat_checksum = image_header.GetOatChecksum();
1156 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001157 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001158 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001159 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001160 image_space->GetImageLocation().c_str(), instruction_set));
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 }
1165 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin96e83932014-10-29 19:45:42 -07001166 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1167
1168 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1169 if (!oat_file->IsPic()) {
1170 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1171 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1172 }
Alex Light6e183f22014-07-18 14:57:04 -07001173 if (!ret) {
1174 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1175 oat_file->GetLocation().c_str(),
1176 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1177 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1178 oat_file->GetOatHeader().GetImagePatchDelta(),
1179 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1180 }
1181 return ret;
1182}
1183
1184bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1185 const char* dex_location,
1186 uint32_t dex_location_checksum,
1187 const InstructionSet instruction_set,
1188 std::string* error_msg) {
1189 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1190 return false;
1191 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001192
Brian Carlstromf3632832014-05-20 15:36:53 -07001193 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1194 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001195 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001196 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1197 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001198 for (const OatFile::OatDexFile* oat_dex_file_in : oat_file->GetOatDexFiles()) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001199 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001200 oat_file->GetLocation().c_str(),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001201 oat_dex_file_in->GetDexFileLocation().c_str(),
1202 oat_dex_file_in->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001203 }
1204 return false;
1205 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001206
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001207 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001208 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001209}
1210
Alex Lighta59dd802014-07-02 16:28:08 -07001211bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1212 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001213 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001214 std::string* error_msg) {
1215 CHECK(oat_file != nullptr);
1216 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001217 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001218 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001219 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1220 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1221 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001222 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001223 if (oat_dex_file == nullptr) {
1224 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001225 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001226 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001227 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001228 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001229 dex_file = oat_dex_file->OpenDexFile(error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001230 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001231 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001232 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001233 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001234 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001235 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001236 dex_file = oat_file->GetOatDexFile(dex_location,
1237 dex_location_checksum)->OpenDexFile(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001238 }
Alex Lighta59dd802014-07-02 16:28:08 -07001239 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001240}
1241
Andreas Gampe833a4852014-05-21 18:46:59 -07001242const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001243 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001244 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001245 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001246 std::vector<std::string>* error_msgs,
1247 bool* obsolete_file_cleanup_failed) {
1248 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001249 bool already_opened = false;
1250 std::string dex_location_str(dex_location);
1251 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1252 &already_opened,
1253 obsolete_file_cleanup_failed,
1254 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001255 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001256 if (oat_file.get() == nullptr) {
1257 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1258 dex_location));
1259 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001260 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001261 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1262 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001263 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1264 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001265 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001266 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001267 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001268 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001269 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1270 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1271 "dex location '%s'. Image checksum incorrect.",
1272 oat_file->GetLocation().c_str(), dex_location));
1273 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001274 } else {
1275 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001276 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001277}
1278
Brian Carlstromae826982011-11-09 01:33:42 -08001279const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001280 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001281 for (size_t i = 0; i < oat_files_.size(); i++) {
1282 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001283 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001284 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001285 return oat_file;
1286 }
1287 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001288 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001289}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001290
Alex Lighta59dd802014-07-02 16:28:08 -07001291const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1292 InstructionSet isa,
1293 bool *already_opened,
1294 bool *obsolete_file_cleanup_failed,
1295 std::vector<std::string>* error_msgs) {
1296 // Find out if we've already opened the file
1297 const OatFile* ret = nullptr;
1298 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1299 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1300 if (ret != nullptr) {
1301 *already_opened = true;
1302 return ret;
1303 }
1304
1305 std::string dalvik_cache;
1306 bool have_android_data = false;
1307 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001308 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001309 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001310 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001311 std::string cache_filename;
1312 if (have_dalvik_cache) {
1313 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1314 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1315 if (ret != nullptr) {
1316 *already_opened = true;
1317 return ret;
1318 }
1319 } else {
1320 // If we need to relocate we should just place odex back where it started.
1321 cache_filename = odex_filename;
1322 }
1323
1324 ret = nullptr;
1325
1326 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1327 //
1328 // Now we do the following:
1329 // 1) Try and open the odex version
1330 // 2) If present, checksum-verified & relocated correctly return it
1331 // 3) Close the odex version to free up its address space.
1332 // 4) Try and open the cache version
1333 // 5) If present, checksum-verified & relocated correctly return it
1334 // 6) Close the cache version to free up its address space.
1335 // 7) If we should relocate:
1336 // a) If we have opened and checksum-verified the odex version relocate it to
1337 // 'cache_filename' and return it
1338 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1339 // it. This should not happen often (I think only the run-test's will hit this case).
1340 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1341 // this point.
1342 // 9) Return nullptr
1343
1344 *already_opened = false;
1345 const Runtime* runtime = Runtime::Current();
1346 CHECK(runtime != nullptr);
1347 bool executable = !runtime->IsCompiler();
1348
1349 std::string odex_error_msg;
1350 bool should_patch_system = false;
1351 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001352 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001353 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001354 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001355 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001356 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001357 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001358 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001359 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001360 &odex_checksum_verified,
1361 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001362 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001363 } else {
1364 if (odex_checksum_verified) {
1365 // We can just relocate
1366 should_patch_system = true;
1367 odex_error_msg = "Image Patches are incorrect";
1368 }
1369 if (odex_oat_file.get() != nullptr) {
1370 have_system_odex = true;
1371 }
Alex Lighta59dd802014-07-02 16:28:08 -07001372 }
1373 }
1374
Alex Lighta59dd802014-07-02 16:28:08 -07001375 std::string cache_error_msg;
1376 bool should_patch_cache = false;
1377 bool cache_checksum_verified = false;
1378 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001379 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001380 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001381 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001382 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001383 &cache_checksum_verified,
1384 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001385 return cache_oat_file.release();
1386 } else if (cache_checksum_verified) {
1387 // We can just relocate
1388 should_patch_cache = true;
1389 cache_error_msg = "Image Patches are incorrect";
1390 }
1391 } else if (have_android_data) {
1392 // dalvik_cache does not exist but android data does. This means we should be able to create
1393 // it, so we should try.
1394 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1395 }
1396
1397 ret = nullptr;
1398 std::string error_msg;
1399 if (runtime->CanRelocate()) {
1400 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001401 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1402 if (space != nullptr) {
1403 const std::string& image_location = space->GetImageLocation();
1404 if (odex_checksum_verified && should_patch_system) {
1405 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1406 } else if (cache_checksum_verified && should_patch_cache) {
1407 CHECK(have_dalvik_cache);
1408 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1409 }
Alex Light84d76052014-08-22 17:49:35 -07001410 } else if (have_system_odex) {
1411 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001412 }
1413 }
1414 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1415 // implicitly: were able to fine where the cached version is but we were unable to use it,
1416 // either as a destination for relocation or to open a file. We should delete it if it is
1417 // there.
1418 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1419 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1420 "searching for dex file %s: %s",
1421 cache_filename.c_str(), dex_location.c_str(),
1422 strerror(errno));
1423 error_msgs->push_back(rm_error_msg);
1424 VLOG(class_linker) << rm_error_msg;
1425 // Let the caller know that we couldn't remove the obsolete file.
1426 // This is a good indication that further writes may fail as well.
1427 *obsolete_file_cleanup_failed = true;
1428 }
1429 }
1430 if (ret == nullptr) {
1431 VLOG(class_linker) << error_msg;
1432 error_msgs->push_back(error_msg);
1433 std::string relocation_msg;
1434 if (runtime->CanRelocate()) {
1435 relocation_msg = StringPrintf(" and relocation failed");
1436 }
1437 if (have_dalvik_cache && cache_checksum_verified) {
1438 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1439 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1440 cache_filename.c_str(), cache_error_msg.c_str(),
1441 relocation_msg.c_str());
1442 } else {
1443 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1444 "dalvik_cache availible)%s.", odex_filename.c_str(),
1445 odex_error_msg.c_str(), relocation_msg.c_str());
1446 }
1447 VLOG(class_linker) << error_msg;
1448 error_msgs->push_back(error_msg);
1449 }
1450 return ret;
1451}
1452
Alex Light9dcc4572014-08-14 14:16:26 -07001453const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1454 InstructionSet isa,
1455 std::string* error_msg) {
1456 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001457 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001458 if (output.get() == nullptr) {
1459 return nullptr;
1460 }
Alex Light84d76052014-08-22 17:49:35 -07001461 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1462 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001463 return output.release();
1464 } else {
1465 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1466 oat_path.c_str());
1467 return nullptr;
1468 }
1469}
1470
Alex Lighta59dd802014-07-02 16:28:08 -07001471const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1472 const std::string& output_oat,
1473 const std::string& image_location,
1474 InstructionSet isa,
1475 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001476 Runtime* runtime = Runtime::Current();
1477 DCHECK(runtime != nullptr);
1478 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001479 // We don't have an image space so there is no point in trying to patchoat.
1480 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1481 << "running without an image. Attempting to use oat file for interpretation.";
1482 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1483 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001484 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001485 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1486 // input_oat but make sure we only do interpretation on it's dex files.
1487 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1488 << "disabled. Attempting to use oat file for interpretation";
1489 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1490 }
Alex Lighta59dd802014-07-02 16:28:08 -07001491 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001492 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001493
1494 std::string isa_arg("--instruction-set=");
1495 isa_arg += GetInstructionSetString(isa);
1496 std::string input_oat_filename_arg("--input-oat-file=");
1497 input_oat_filename_arg += input_oat;
1498 std::string output_oat_filename_arg("--output-oat-file=");
1499 output_oat_filename_arg += output_oat;
1500 std::string patched_image_arg("--patched-image-location=");
1501 patched_image_arg += image_location;
1502
1503 std::vector<std::string> argv;
1504 argv.push_back(patchoat);
1505 argv.push_back(isa_arg);
1506 argv.push_back(input_oat_filename_arg);
1507 argv.push_back(output_oat_filename_arg);
1508 argv.push_back(patched_image_arg);
1509
1510 std::string command_line(Join(argv, ' '));
1511 LOG(INFO) << "Relocate Oat File: " << command_line;
1512 bool success = Exec(argv, error_msg);
1513 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001514 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gampe7ba64962014-10-23 11:37:40 -07001515 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001516 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001517 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1518 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001519 return output.release();
1520 } else if (output.get() != nullptr) {
1521 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1522 "but output file '%s' failed verifcation: %s",
1523 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1524 } else {
1525 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1526 "but was unable to open output file '%s': %s",
1527 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1528 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001529 } else if (!runtime->IsCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001530 // patchoat failed which means we probably don't have enough room to place the output oat file,
1531 // instead of failing we should just run the interpreter from the dex files in the input oat.
1532 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1533 << "for interpretation. patchoat failure was: " << *error_msg;
1534 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001535 } else {
1536 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1537 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1538 error_msg->c_str());
1539 }
1540 return nullptr;
1541}
1542
Andreas Gampe7ba64962014-10-23 11:37:40 -07001543bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001544 bool* checksum_verified,
1545 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001546 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001547 if (image_space == nullptr) {
1548 *error_msg = "No image space present";
1549 return false;
1550 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001551 uint32_t real_image_checksum;
1552 void* real_image_oat_offset;
1553 int32_t real_patch_delta;
1554 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001555 const ImageHeader& image_header = image_space->GetImageHeader();
1556 real_image_checksum = image_header.GetOatChecksum();
1557 real_image_oat_offset = image_header.GetOatDataBegin();
1558 real_patch_delta = image_header.GetPatchDelta();
1559 } else {
1560 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1561 image_space->GetImageLocation().c_str(), isa));
1562 real_image_checksum = image_header->GetOatChecksum();
1563 real_image_oat_offset = image_header->GetOatDataBegin();
1564 real_patch_delta = image_header->GetPatchDelta();
1565 }
1566
1567 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001568 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001569
1570 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1571 *checksum_verified = oat_image_checksum == real_image_checksum;
1572 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001573 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1574 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001575 }
1576
Andreas Gampe7ba64962014-10-23 11:37:40 -07001577 bool offset_verified;
1578 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001579
Andreas Gampe7ba64962014-10-23 11:37:40 -07001580 if (!oat_file->IsPic()) {
1581 // If an oat file is not PIC, we need to check that the image is at the expected location and
1582 // patched in the same way.
1583 void* oat_image_oat_offset =
1584 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1585 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1586 if (!offset_verified) {
1587 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1588 real_image_oat_offset, oat_image_oat_offset);
1589 }
1590
1591 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1592 patch_delta_verified = oat_patch_delta == real_patch_delta;
1593 if (!patch_delta_verified) {
1594 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1595 "received 0x%x)", real_patch_delta, oat_patch_delta);
1596 }
1597 } else {
1598 // If an oat file is PIC, we ignore offset and patching delta.
1599 offset_verified = true;
1600 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001601 }
1602
1603 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001604 if (!ret) {
1605 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001606 }
1607 return ret;
1608}
1609
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001610const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1611 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001612 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001613 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001614 return oat_file;
1615 }
1616
Igor Murashkin46774762014-10-22 11:37:02 -07001617 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001618 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001619}
1620
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001621void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001622 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001623 DCHECK(obj != nullptr);
1624 DCHECK(class_linker != nullptr);
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001625 size_t pointer_size = class_linker->image_pointer_size_;
Ian Rogers848871b2013-08-05 10:56:33 -07001626
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001627 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001628 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001629 if (!method->IsNative()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001630 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001631 if (method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001632 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1633 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001634 }
1635 }
1636 }
1637}
1638
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001639void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001640 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001641 CHECK(!init_done_);
1642
Mathieu Chartier590fee92013-09-13 13:46:47 -07001643 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001644 gc::Heap* heap = Runtime::Current()->GetHeap();
1645 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001646 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001647 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001648 OatFile& oat_file = GetImageOatFile(space);
1649 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1650 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001651 const char* image_file_location = oat_file.GetOatHeader().
1652 GetStoreValueByKey(OatHeader::kImageLocationKey);
1653 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001654 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001655 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001656 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001657 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001658 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1659 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1660 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001661
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001662 StackHandleScope<1> hs(self);
1663 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1664 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1665 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001666 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001667
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001668 // Special case of setting up the String class early so that we can test arbitrary objects
1669 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001670 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001671
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001672 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001673 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001674 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001675 StackHandleScope<1> hs2(self);
1676 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001677 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001678 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1679 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001680 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001681 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001682 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
1683 if (dex_file.get() == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001684 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001685 << " from within oat file " << oat_file.GetLocation()
1686 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -08001687 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001688 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001689
1690 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1691
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001692 AppendToBootClassPath(*dex_file.get(), dex_cache);
1693 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001694 }
1695
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001696 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1697 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001698 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001699 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
1700 if (!Runtime::Current()->IsCompiler()) {
1701 // Compiler supports having an image with a different pointer size than the runtime. This
1702 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
1703 // also use 32 bit dex2oat on a system with 64 bit apps.
1704 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
1705 << sizeof(void*);
1706 }
1707 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
1708 image_pointer_size_ = 4;
1709 } else {
1710 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
1711 image_pointer_size_ = 8;
1712 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001713
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001714 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001715 Runtime* runtime = Runtime::Current();
1716 if (!runtime->IsCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001717 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001718 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001719 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001720
1721 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001722 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001723 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001724
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001725 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001726 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001727 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001728 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001729 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001730 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001731 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1732 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1733 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1734 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1735 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1736 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1737 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1738 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1739 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1740 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001741
Ian Rogers98379392014-02-24 16:53:16 -08001742 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001743
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001744 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001745}
1746
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001747void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1748 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1749 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001750 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001751 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001752 }
1753 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001754 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001755 }
1756 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001757 for (auto& root : new_class_roots_) {
1758 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001759 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001760 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001761 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001762 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1763 // corresponding object. This is slow, but luckily for us, this may only happen with a
1764 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001765 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001766 DCHECK(it != class_table_.end());
1767 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001768 }
1769 }
1770 }
1771 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1772 new_class_roots_.clear();
1773 }
1774 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1775 log_new_class_table_roots_ = true;
1776 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1777 log_new_class_table_roots_ = false;
1778 }
1779 // We deliberately ignore the class roots in the image since we
1780 // handle image roots by using the MS/CMS rescanning of dirty cards.
1781}
1782
Brian Carlstroma663ea52011-08-19 23:33:41 -07001783// Keep in sync with InitCallback. Anything we visit, we need to
1784// reinit references to when reinitializing a ClassLinker from a
1785// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001786void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001787 class_roots_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers50b35e22012-10-04 10:09:15 -07001788 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001789 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001790 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001791 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001792 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001793 dex_cache.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001794 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001795 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1796 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001797 dex_caches_[index].VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001798 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001799 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001800 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1801 new_dex_cache_roots_.clear();
1802 }
1803 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1804 log_new_dex_caches_roots_ = true;
1805 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1806 log_new_dex_caches_roots_ = false;
1807 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001808 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001809 VisitClassRoots(callback, arg, flags);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001810 array_iftable_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001811 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001812 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001813 find_array_class_cache_[i].VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001814 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001815}
1816
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001817void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1818 if (dex_cache_image_class_lookup_required_) {
1819 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001820 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001821 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001822 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001823 for (GcRoot<mirror::Class>& root : class_table_) {
1824 if (!visitor(root.Read(), arg)) {
1825 return;
1826 }
1827 }
1828 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1829 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001830 return;
1831 }
1832 }
1833}
1834
Ian Rogersdbf3be02014-08-29 15:40:08 -07001835static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001836 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001837 classes->insert(c);
1838 return true;
1839}
1840
Ian Rogersdbf3be02014-08-29 15:40:08 -07001841struct GetClassesVisitorArrayArg {
1842 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1843 int32_t index;
1844 bool success;
1845};
1846
1847static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1848 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1849 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1850 if (arg->index < (*arg->classes)->GetLength()) {
1851 (*arg->classes)->Set(arg->index, c);
1852 arg->index++;
1853 return true;
1854 } else {
1855 arg->success = false;
1856 return false;
1857 }
1858}
1859
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001860void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001861 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1862 // is avoiding duplicates.
1863 if (!kMovingClasses) {
1864 std::set<mirror::Class*> classes;
1865 VisitClasses(GetClassesVisitorSet, &classes);
1866 for (mirror::Class* klass : classes) {
1867 if (!visitor(klass, arg)) {
1868 return;
1869 }
1870 }
1871 } else {
1872 Thread* self = Thread::Current();
1873 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001874 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001875 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1876 GetClassesVisitorArrayArg local_arg;
1877 local_arg.classes = &classes;
1878 local_arg.success = false;
1879 // We size the array assuming classes won't be added to the class table during the visit.
1880 // If this assumption fails we iterate again.
1881 while (!local_arg.success) {
1882 size_t class_table_size;
1883 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001884 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001885 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001886 }
1887 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1888 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1889 classes.Assign(
1890 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1891 CHECK(classes.Get() != nullptr); // OOME.
1892 local_arg.index = 0;
1893 local_arg.success = true;
1894 VisitClasses(GetClassesVisitorArray, &local_arg);
1895 }
1896 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1897 // If the class table shrank during creation of the clases array we expect null elements. If
1898 // the class table grew then the loop repeats. If classes are created after the loop has
1899 // finished then we don't visit.
1900 mirror::Class* klass = classes->Get(i);
1901 if (klass != nullptr && !visitor(klass, arg)) {
1902 return;
1903 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001904 }
1905 }
1906}
1907
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001908ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001909 mirror::Class::ResetClass();
1910 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001911 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001912 mirror::ArtField::ResetClass();
1913 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001914 mirror::BooleanArray::ResetArrayClass();
1915 mirror::ByteArray::ResetArrayClass();
1916 mirror::CharArray::ResetArrayClass();
1917 mirror::DoubleArray::ResetArrayClass();
1918 mirror::FloatArray::ResetArrayClass();
1919 mirror::IntArray::ResetArrayClass();
1920 mirror::LongArray::ResetArrayClass();
1921 mirror::ShortArray::ResetArrayClass();
1922 mirror::Throwable::ResetClass();
1923 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001924 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001925}
1926
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001927mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001928 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001929 StackHandleScope<16> hs(self);
1930 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1931 Handle<mirror::DexCache> dex_cache(
1932 hs.NewHandle(down_cast<mirror::DexCache*>(
1933 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1934 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001935 if (dex_cache.Get() == nullptr) {
1936 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001937 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001938 Handle<mirror::String>
1939 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001940 if (location.Get() == nullptr) {
1941 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001942 }
Ian Rogers700a4022014-05-19 16:49:03 -07001943 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001944 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001945 if (strings.Get() == nullptr) {
1946 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001947 }
Ian Rogers700a4022014-05-19 16:49:03 -07001948 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001949 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001950 if (types.Get() == nullptr) {
1951 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001952 }
Ian Rogers700a4022014-05-19 16:49:03 -07001953 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001954 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001955 if (methods.Get() == nullptr) {
1956 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001957 }
Ian Rogers700a4022014-05-19 16:49:03 -07001958 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001959 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001960 if (fields.Get() == nullptr) {
1961 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001962 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001963 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1964 fields.Get());
1965 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001966}
1967
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001968mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001969 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001970 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001971 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001972 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001973 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001974 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1975 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001976 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001977 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001978 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001979 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001980 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001981}
1982
Ian Rogers6fac4472014-02-25 17:01:10 -08001983mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001984 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001985}
1986
Brian Carlstromea46f952013-07-30 01:26:50 -07001987mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001988 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001989 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001990}
1991
Brian Carlstromea46f952013-07-30 01:26:50 -07001992mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001993 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001994 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001995}
1996
Mathieu Chartier590fee92013-09-13 13:46:47 -07001997mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1998 Thread* self, size_t length) {
1999 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2000 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002001}
2002
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002003mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
2004 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002005 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002006
2007 // For temporary classes we must wait for them to be retired.
2008 if (init_done_ && klass->IsTemp()) {
2009 CHECK(!klass->IsResolved());
2010 if (klass->IsErroneous()) {
2011 ThrowEarlierClassFailure(klass);
2012 return nullptr;
2013 }
2014 StackHandleScope<1> hs(self);
2015 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2016 ObjectLock<mirror::Class> lock(self, h_class);
2017 // Loop and wait for the resolving thread to retire this class.
2018 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2019 lock.WaitIgnoringInterrupts();
2020 }
2021 if (h_class->IsErroneous()) {
2022 ThrowEarlierClassFailure(h_class.Get());
2023 return nullptr;
2024 }
2025 CHECK(h_class->IsRetired());
2026 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002027 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2028 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002029 }
2030
Brian Carlstromaded5f72011-10-07 17:15:04 -07002031 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002032 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002033 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002034 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2035 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002036 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002037 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2038 ThrowClassCircularityError(h_class.Get());
2039 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002040 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002041 }
2042 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002043 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002044 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002045 }
2046 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002047
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002048 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002049 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002050 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002051 }
2052 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002053 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002054 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002055 return klass;
2056}
2057
Ian Rogers68b56852014-08-29 20:19:11 -07002058typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2059
2060// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002061ClassPathEntry FindInClassPath(const char* descriptor,
2062 size_t hash, const std::vector<const DexFile*>& class_path) {
2063 for (const DexFile* dex_file : class_path) {
2064 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002065 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002066 return ClassPathEntry(dex_file, dex_class_def);
2067 }
2068 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002069 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002070}
2071
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002072mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2073 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002074 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002075 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08002076 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002077 if (class_loader->GetClass() !=
2078 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2079 class_loader->GetParent()->GetClass() !=
2080 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2081 return nullptr;
2082 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002083 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002084 // Check if this would be found in the parent boot class loader.
2085 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002086 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002087 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08002088 // May return null if resolution on another thread fails.
2089 klass = EnsureResolved(self, descriptor, klass);
2090 } else {
2091 // May OOME.
2092 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2093 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002094 }
Ian Rogers32427292014-11-19 14:05:21 -08002095 if (klass == nullptr) {
2096 CHECK(self->IsExceptionPending()) << descriptor;
2097 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002098 }
Ian Rogers32427292014-11-19 14:05:21 -08002099 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002100 } else {
Ian Rogers32427292014-11-19 14:05:21 -08002101 // Handle as if this is the child PathClassLoader.
2102 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002103 StackHandleScope<3> hs(self);
2104 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2105 // We need to get the DexPathList and loop through it.
2106 Handle<mirror::ArtField> cookie_field =
2107 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2108 Handle<mirror::ArtField> dex_file_field =
2109 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002110 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002111 mirror::Object* dex_path_list =
2112 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2113 GetObject(class_loader.Get());
2114 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2115 cookie_field.Get() != nullptr) {
2116 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2117 mirror::Object* dex_elements_obj =
2118 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2119 GetObject(dex_path_list);
2120 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2121 // at the mCookie which is a DexFile vector.
2122 if (dex_elements_obj != nullptr) {
2123 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2124 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2125 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2126 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2127 if (element == nullptr) {
2128 // Should never happen, fall back to java code to throw a NPE.
2129 break;
2130 }
2131 mirror::Object* dex_file = dex_file_field->GetObject(element);
2132 if (dex_file != nullptr) {
2133 const uint64_t cookie = cookie_field->GetLong(dex_file);
2134 auto* dex_files =
2135 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2136 if (dex_files == nullptr) {
2137 // This should never happen so log a warning.
2138 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2139 break;
2140 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002141 for (const DexFile* cp_dex_file : *dex_files) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002142 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002143 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002144 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002145 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2146 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002147 if (klass == nullptr) {
2148 CHECK(self->IsExceptionPending()) << descriptor;
2149 self->ClearException();
2150 return nullptr;
2151 }
2152 return klass;
2153 }
2154 }
2155 }
2156 }
2157 }
2158 }
Ian Rogers32427292014-11-19 14:05:21 -08002159 self->AssertNoPendingException();
2160 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002161 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002162}
2163
Ian Rogers98379392014-02-24 16:53:16 -08002164mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002165 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002166 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002167 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002168 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002169 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002170 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2171 // for primitive classes that aren't backed by dex files.
2172 return FindPrimitiveClass(descriptor[0]);
2173 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002174 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002175 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002176 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002177 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002178 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002179 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002180 // Class is not yet loaded.
2181 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002182 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002183 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002184 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002185 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002186 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002187 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002188 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002189 } else {
2190 // The boot class loader is searched ahead of the application class loader, failures are
2191 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2192 // trigger the chaining with a proper stack trace.
2193 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2194 self->SetException(ThrowLocation(), pre_allocated);
2195 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002196 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002197 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002198 // First try with the bootstrap class loader.
2199 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002200 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002201 if (klass != nullptr) {
2202 return EnsureResolved(self, descriptor, klass);
2203 }
2204 }
Ian Rogers63557452014-06-04 16:57:15 -07002205 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2206 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002207 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002208 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002209 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002210 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002211 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002212 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002213 const std::vector<const DexFile*>* class_path;
2214 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002215 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002216 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002217 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002218 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2219 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002220 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07002221 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002222 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07002223 } else {
2224 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2225 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2226 self->SetException(ThrowLocation(), pre_allocated);
2227 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002228 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002229 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002230 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002231 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2232 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002233 if (cp_klass != nullptr) {
2234 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002235 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002236 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002237 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002238 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002239 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002240 {
2241 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002242 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2243 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002244 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002245 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002246 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002247 }
Ian Rogers68b56852014-08-29 20:19:11 -07002248 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002249 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2250 WellKnownClasses::java_lang_ClassLoader_loadClass,
2251 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002252 }
Ian Rogers98379392014-02-24 16:53:16 -08002253 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002254 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002255 return nullptr;
2256 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002257 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002258 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002259 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002260 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002261 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002262 // success, return mirror::Class*
2263 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002264 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002265 }
Ian Rogers07140832014-09-30 15:43:59 -07002266 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002267}
2268
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002269mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002270 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002271 const DexFile& dex_file,
2272 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002273 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002274 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002275
Brian Carlstromaded5f72011-10-07 17:15:04 -07002276 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002277 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002278 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002279 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002280 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002281 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002282 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002283 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002284 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002285 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2286 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002287 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002288 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002289 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002290 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002291 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002292 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002293 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002294 }
2295
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002296 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002297 // Allocate a class with the status of not ready.
2298 // Interface object should get the right size here. Regular class will
2299 // figure out the right size later and be replaced with one of the right
2300 // size when the class becomes resolved.
2301 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002302 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002303 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002304 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002305 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002306 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002307 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002308 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002309 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002310 if (self->IsExceptionPending()) {
2311 // An exception occured during load, set status to erroneous while holding klass' lock in case
2312 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002313 if (!klass->IsErroneous()) {
2314 klass->SetStatus(mirror::Class::kStatusError, self);
2315 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002316 return nullptr;
2317 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002318 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002319
Mathieu Chartier590fee92013-09-13 13:46:47 -07002320 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002321 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002322 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002323 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2324 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002325 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002326 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002327
Brian Carlstromaded5f72011-10-07 17:15:04 -07002328 // Finish loading (if necessary) by finding parents
2329 CHECK(!klass->IsLoaded());
2330 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2331 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002332 if (!klass->IsErroneous()) {
2333 klass->SetStatus(mirror::Class::kStatusError, self);
2334 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002335 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002336 }
2337 CHECK(klass->IsLoaded());
2338 // Link the class (if necessary)
2339 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002340 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002341 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002342
2343 mirror::Class* new_class = nullptr;
2344 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002345 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002346 if (!klass->IsErroneous()) {
2347 klass->SetStatus(mirror::Class::kStatusError, self);
2348 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002349 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002350 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002351 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002352 CHECK(new_class != nullptr) << descriptor;
2353 CHECK(new_class->IsResolved()) << descriptor;
2354
2355 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002356
2357 /*
2358 * We send CLASS_PREPARE events to the debugger from here. The
2359 * definition of "preparation" is creating the static fields for a
2360 * class and initializing them to the standard default values, but not
2361 * executing any code (that comes later, during "initialization").
2362 *
2363 * We did the static preparation in LinkClass.
2364 *
2365 * The class has been prepared and resolved but possibly not yet verified
2366 * at this point.
2367 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002368 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002369
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002370 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002371}
2372
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002373uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2374 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002375 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002376 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002377 size_t num_8 = 0;
2378 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002379 size_t num_32 = 0;
2380 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002381 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002382 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2383 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002384 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002385 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002386 switch (c) {
2387 case 'L':
2388 case '[':
2389 num_ref++;
2390 break;
2391 case 'J':
2392 case 'D':
2393 num_64++;
2394 break;
2395 case 'I':
2396 case 'F':
2397 num_32++;
2398 break;
2399 case 'S':
2400 case 'C':
2401 num_16++;
2402 break;
2403 case 'B':
2404 case 'Z':
2405 num_8++;
2406 break;
2407 default:
2408 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002409 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002410 }
2411 }
2412 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002413 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002414}
2415
Ian Rogers97b52f82014-08-14 11:34:07 -07002416OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2417 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002418 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002419 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2420 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002421 *found = false;
2422 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002423 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002424 *found = true;
2425 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002426}
2427
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002428static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2429 uint32_t method_idx) {
2430 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002431 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002432 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002433 ClassDataItemIterator it(dex_file, class_data);
2434 // Skip fields
2435 while (it.HasNextStaticField()) {
2436 it.Next();
2437 }
2438 while (it.HasNextInstanceField()) {
2439 it.Next();
2440 }
2441 // Process methods
2442 size_t class_def_method_index = 0;
2443 while (it.HasNextDirectMethod()) {
2444 if (it.GetMemberIndex() == method_idx) {
2445 return class_def_method_index;
2446 }
2447 class_def_method_index++;
2448 it.Next();
2449 }
2450 while (it.HasNextVirtualMethod()) {
2451 if (it.GetMemberIndex() == method_idx) {
2452 return class_def_method_index;
2453 }
2454 class_def_method_index++;
2455 it.Next();
2456 }
2457 DCHECK(!it.HasNext());
2458 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08002459 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002460}
2461
Ian Rogers97b52f82014-08-14 11:34:07 -07002462const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002463 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002464 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002465 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002466 size_t oat_method_index;
2467 if (method->IsStatic() || method->IsDirect()) {
2468 // Simple case where the oat method index was stashed at load time.
2469 oat_method_index = method->GetMethodIndex();
2470 } else {
2471 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2472 // by search for its position in the declared virtual methods.
2473 oat_method_index = declaring_class->NumDirectMethods();
2474 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002475 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002476 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002477 // Check method index instead of identity in case of duplicate method definitions.
2478 if (method->GetDexMethodIndex() ==
2479 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002480 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002481 break;
2482 }
Ian Rogersf320b632012-03-13 18:47:47 -07002483 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002484 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002485 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2486 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002487 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002488 DCHECK_EQ(oat_method_index,
2489 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002490 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002491 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002492 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2493 declaring_class->GetDexClassDefIndex(),
2494 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002495 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002496 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002497 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002498 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002499}
2500
2501// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002502const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002503 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002504 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002505 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002506 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002507 bool found;
2508 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002509 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002510 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002511 result = oat_method.GetQuickCode();
2512 }
2513
Ian Rogersef7d42f2014-01-06 12:55:46 -08002514 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002515 if (method->IsNative()) {
2516 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002517 result = GetQuickGenericJniStub();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002518 } else {
2519 // No code? You must mean to go into the interpreter.
2520 result = GetQuickToInterpreterBridge();
2521 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002522 }
2523 return result;
TDYa12785321912012-04-01 15:24:56 -07002524}
2525
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002526const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2527 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2528 return nullptr;
2529 }
2530 bool found;
2531 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2532 return found ? oat_method.GetQuickCode() : nullptr;
2533}
2534
Ian Rogersef7d42f2014-01-06 12:55:46 -08002535const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2536 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002537 bool found;
2538 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2539 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002540 return nullptr;
2541 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002542 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002543 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002544}
2545
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002546// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08002547static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07002548 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08002549 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002550 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002551 // May return true for native code, in the case of generic JNI
2552 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002553 return true;
2554 }
2555 // If interpreter mode is enabled, every method (except native and proxy) must
2556 // be run with interpreter.
2557 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2558 !method->IsNative() && !method->IsProxyMethod();
2559}
2560
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002561void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002562 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002563 if (klass->NumDirectMethods() == 0) {
2564 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002565 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002566 Runtime* runtime = Runtime::Current();
2567 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002568 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2569 return; // OAT file unavailable.
2570 }
Ian Rogers19846512012-02-24 11:42:47 -08002571 }
Alex Light64ad14d2014-08-19 14:23:13 -07002572
Mathieu Chartierf8322842014-05-16 10:59:25 -07002573 const DexFile& dex_file = klass->GetDexFile();
2574 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002575 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002576 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002577 // There should always be class data if there were direct methods.
2578 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002579 ClassDataItemIterator it(dex_file, class_data);
2580 // Skip fields
2581 while (it.HasNextStaticField()) {
2582 it.Next();
2583 }
2584 while (it.HasNextInstanceField()) {
2585 it.Next();
2586 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002587 bool has_oat_class;
2588 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2589 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002590 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002591 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002592 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002593 if (!method->IsStatic()) {
2594 // Only update static methods.
2595 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002596 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002597 const void* quick_code = nullptr;
2598 if (has_oat_class) {
2599 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002600 quick_code = oat_method.GetQuickCode();
2601 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002602 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002603 if (enter_interpreter) {
2604 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002605 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08002606 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002607 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08002608 } else {
2609 quick_code = GetQuickToInterpreterBridge();
2610 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002611 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002612 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08002613 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002614 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002615}
2616
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002617void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002618 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002619 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002620 Runtime* runtime = Runtime::Current();
2621 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002622 // The following code only applies to a non-compiler runtime.
2623 return;
2624 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002625 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002626 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002627 if (oat_class != nullptr) {
2628 // Every kind of method should at least get an invoke stub from the oat_method.
2629 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002630 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002631 oat_method.LinkMethod(method.Get());
2632 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002633
Jeff Hao16743632013-05-08 10:59:04 -07002634 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002635 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08002636 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002637 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002638 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002639 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002640 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002641 }
2642
Brian Carlstrom92827a52011-10-10 15:50:01 -07002643 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002644 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002645 return;
2646 }
Ian Rogers19846512012-02-24 11:42:47 -08002647
2648 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002649 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002650 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2651 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002652 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002653 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002654 if (!method->IsNative()) {
2655 // Set entry point from compiled code if there's no code or in interpreter only mode.
2656 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002657 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002658 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002659 }
Ian Rogers0d6de042012-02-29 08:50:26 -08002660 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002661
Ian Rogers62d6c772013-02-27 08:32:07 -08002662 if (method->IsNative()) {
2663 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002664 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002665
2666 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002667 // We have a native method here without code. Then it should have either the generic JNI
2668 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2669 // TODO: this doesn't handle all the cases where trampolines may be installed.
2670 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2671 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002672 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002673 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002674
Ian Rogers62d6c772013-02-27 08:32:07 -08002675 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002676 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08002677 method->GetEntryPointFromQuickCompiledCode());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002678}
2679
Fred Shih37f05ef2014-07-16 18:38:08 -07002680
Fred Shih37f05ef2014-07-16 18:38:08 -07002681
Ian Rogers7b078e82014-09-10 14:44:24 -07002682void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002683 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002684 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002685 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002686 CHECK(klass.Get() != nullptr);
2687 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002688 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002689 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002690 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002691
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002692 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002693 if (kUseBakerOrBrooksReadBarrier) {
2694 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002695 }
Andreas Gampe51829322014-08-25 15:05:04 -07002696 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002697 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002698 klass->SetAccessFlags(access_flags);
2699 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002700 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002701 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002702
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002703 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002704 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002705 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002706
Ian Rogers13735952014-10-08 12:43:28 -07002707 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002708 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002709 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002710 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002711
Ian Rogers97b52f82014-08-14 11:34:07 -07002712
2713 bool has_oat_class = false;
2714 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2715 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2716 &has_oat_class);
2717 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002718 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002719 }
2720 }
2721 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002722 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002723 }
2724}
2725
Ian Rogers7b078e82014-09-10 14:44:24 -07002726void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002727 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002728 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002729 const OatFile::OatClass* oat_class) {
2730 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002731 ClassDataItemIterator it(dex_file, class_data);
2732 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002733 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002734 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002735 CHECK(self->IsExceptionPending()); // OOME.
2736 return;
2737 }
2738 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002739 }
2740 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002741 mirror::ObjectArray<mirror::ArtField>* fields =
2742 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002743 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002744 CHECK(self->IsExceptionPending()); // OOME.
2745 return;
2746 }
2747 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002748 }
2749 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002750 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002751 StackHandleScope<1> hs(self);
2752 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002753 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002754 CHECK(self->IsExceptionPending()); // OOME.
2755 return;
2756 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002757 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002758 LoadField(dex_file, it, klass, sfield);
2759 }
2760 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002761 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002762 StackHandleScope<1> hs(self);
2763 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002764 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002765 CHECK(self->IsExceptionPending()); // OOME.
2766 return;
2767 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002768 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002769 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002770 }
2771
Ian Rogers0571d352011-11-03 19:51:38 -07002772 // Load methods.
2773 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002774 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002775 mirror::ObjectArray<mirror::ArtMethod>* directs =
2776 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002777 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002778 CHECK(self->IsExceptionPending()); // OOME.
2779 return;
2780 }
2781 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002782 }
Ian Rogers0571d352011-11-03 19:51:38 -07002783 if (it.NumVirtualMethods() != 0) {
2784 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002785 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2786 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002787 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002788 CHECK(self->IsExceptionPending()); // OOME.
2789 return;
2790 }
2791 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002792 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002793 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002794 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2795 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002796 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002797 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002798 StackHandleScope<1> hs(self);
2799 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002800 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002801 CHECK(self->IsExceptionPending()); // OOME.
2802 return;
2803 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002804 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002805 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002806 uint32_t it_method_index = it.GetMemberIndex();
2807 if (last_dex_method_index == it_method_index) {
2808 // duplicate case
2809 method->SetMethodIndex(last_class_def_method_index);
2810 } else {
2811 method->SetMethodIndex(class_def_method_index);
2812 last_dex_method_index = it_method_index;
2813 last_class_def_method_index = class_def_method_index;
2814 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002815 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002816 }
2817 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002818 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002819 StackHandleScope<1> hs(self);
2820 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002821 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002822 CHECK(self->IsExceptionPending()); // OOME.
2823 return;
2824 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002825 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002826 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002827 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002828 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002829 }
2830 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002831}
2832
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002833void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002834 Handle<mirror::Class> klass,
2835 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002836 uint32_t field_idx = it.GetMemberIndex();
2837 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002838 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002839 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002840}
2841
Brian Carlstromea46f952013-07-30 01:26:50 -07002842mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002843 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002844 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002845 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002846 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002847 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002848
Brian Carlstromea46f952013-07-30 01:26:50 -07002849 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002850 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002851 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002852 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002853 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002854 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002855
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002856 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002857 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002858 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002859 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002860
Ian Rogers19846512012-02-24 11:42:47 -08002861 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002862 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002863
Andreas Gampe51829322014-08-25 15:05:04 -07002864 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002865
Ian Rogersdfb325e2013-10-30 01:00:44 -07002866 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002867 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002868 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2869 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002870 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002871 klass->SetFinalizable();
2872 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002873 std::string temp;
2874 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002875 // The Enum class declares a "final" finalize() method to prevent subclasses from
2876 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2877 // subclasses, so we exclude it here.
2878 // We also want to avoid setting the flag on Object, where we know that finalize() is
2879 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002880 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2881 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002882 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002883 }
2884 }
2885 }
2886 } else if (method_name[0] == '<') {
2887 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002888 bool is_init = (strcmp("<init>", method_name) == 0);
2889 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002890 if (UNLIKELY(!is_init && !is_clinit)) {
2891 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2892 } else {
2893 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2894 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002895 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002896 access_flags |= kAccConstructor;
2897 }
2898 }
2899 }
2900 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002901
Mathieu Chartier66f19252012-09-18 08:57:04 -07002902 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002903}
2904
Ian Rogers7b078e82014-09-10 14:44:24 -07002905void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002906 StackHandleScope<1> hs(self);
2907 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002908 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2909 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002910 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002911}
2912
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002913void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002914 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002915 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002916 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002917 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002918}
2919
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002920bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002921 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002922 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002923 mirror::DexCache* dex_cache = GetDexCache(i);
2924 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002925 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002926 }
2927 }
2928 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002929}
2930
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002931bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002932 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002933 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002934}
2935
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002936void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002937 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002938 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002939 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002940 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2941 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002942 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002943 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002944 if (log_new_dex_caches_roots_) {
2945 // TODO: This is not safe if we can remove dex caches.
2946 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2947 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002948}
2949
Brian Carlstromaded5f72011-10-07 17:15:04 -07002950void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002951 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002952 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002953 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002954 if (IsDexFileRegisteredLocked(dex_file)) {
2955 return;
2956 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002957 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002958 // Don't alloc while holding the lock, since allocation may need to
2959 // suspend all threads and another thread may need the dex_lock_ to
2960 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002961 StackHandleScope<1> hs(self);
2962 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002963 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2964 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002965 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002966 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002967 if (IsDexFileRegisteredLocked(dex_file)) {
2968 return;
2969 }
2970 RegisterDexFileLocked(dex_file, dex_cache);
2971 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002972}
2973
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002974void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002975 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002976 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002977 RegisterDexFileLocked(dex_file, dex_cache);
2978}
2979
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002980mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002981 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002982 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002983 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002984 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002985 if (dex_cache->GetDexFile() == &dex_file) {
2986 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002987 }
2988 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002989 // Search matching by location name.
2990 std::string location(dex_file.GetLocation());
2991 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002992 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002993 if (dex_cache->GetDexFile()->GetLocation() == location) {
2994 return dex_cache;
2995 }
2996 }
2997 // Failure, dump diagnostic and abort.
2998 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002999 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003000 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3001 }
3002 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003003 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003004}
3005
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003006void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003007 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003008 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003009 mirror::DexCache* dex_cache = GetDexCache(i);
3010 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003011 }
3012}
3013
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003014mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003015 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003016 if (UNLIKELY(klass == nullptr)) {
3017 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003018 }
3019 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003020}
3021
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003022mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3023 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003024 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003025 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003026 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003027 StackHandleScope<1> hs(self);
3028 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003029 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003030 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003031 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003032 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3033 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003034 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3035 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003036 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003037 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003038}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003039
Brian Carlstrombe977852011-07-19 14:54:54 -07003040// Create an array class (i.e. the class object for the array, not the
3041// array itself). "descriptor" looks like "[C" or "[[[[B" or
3042// "[Ljava/lang/String;".
3043//
3044// If "descriptor" refers to an array of primitives, look up the
3045// primitive type's internally-generated class object.
3046//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003047// "class_loader" is the class loader of the class that's referring to
3048// us. It's used to ensure that we're looking for the element type in
3049// the right context. It does NOT become the class loader for the
3050// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003051//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003052// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003053mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003054 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003055 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003056 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003057 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003058 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3059 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003060 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003061 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003062 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003063 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3064 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003065 if (component_type.Get() == nullptr) {
3066 DCHECK(self->IsExceptionPending());
3067 return nullptr;
3068 } else {
3069 self->ClearException();
3070 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003071 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003072 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3073 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3074 return nullptr;
3075 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003076 // See if the component type is already loaded. Array classes are
3077 // always associated with the class loader of their underlying
3078 // element type -- an array of Strings goes with the loader for
3079 // java/lang/String -- so we need to look for it there. (The
3080 // caller should have checked for the existence of the class
3081 // before calling here, but they did so with *their* class loader,
3082 // not the component type's loader.)
3083 //
3084 // If we find it, the caller adds "loader" to the class' initiating
3085 // loader list, which should prevent us from going through this again.
3086 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003087 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003088 // are the same, because our caller (FindClass) just did the
3089 // lookup. (Even if we get this wrong we still have correct behavior,
3090 // because we effectively do this lookup again when we add the new
3091 // class to the hash table --- necessary because of possible races with
3092 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003093 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003094 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003095 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003096 return new_class;
3097 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003098 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003099
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003100 // Fill out the fields in the Class.
3101 //
3102 // It is possible to execute some methods against arrays, because
3103 // all arrays are subclasses of java_lang_Object_, so we need to set
3104 // up a vtable. We can just point at the one in java_lang_Object_.
3105 //
3106 // Array classes are simple enough that we don't need to do a full
3107 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003108 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003109 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003110 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003111 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003112 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003113 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003114 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003115 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003116 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003117 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003118 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003119 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003120 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003121 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003122 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003123 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003124 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003125 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003126 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003127 }
3128 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003129 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003130 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003131 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003132 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003133 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003134 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003135 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003136 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003137 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003138 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003139 new_class->SetSuperClass(java_lang_Object);
3140 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003141 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003142 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003143 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003144 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003145 StackHandleScope<mirror::Class::kImtSize> hs2(self,
3146 Runtime::Current()->GetImtUnimplementedMethod());
3147 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003148 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003149 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003150 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003151 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003152
3153
3154 // All arrays have java/lang/Cloneable and java/io/Serializable as
3155 // interfaces. We need to set that up here, so that stuff like
3156 // "instanceof" works right.
3157 //
3158 // Note: The GC could run during the call to FindSystemClass,
3159 // so we need to make sure the class object is GC-valid while we're in
3160 // there. Do this by clearing the interface list so the GC will just
3161 // think that the entries are null.
3162
3163
3164 // Use the single, global copies of "interfaces" and "iftable"
3165 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003166 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003167 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003168 CHECK(array_iftable != nullptr);
3169 new_class->SetIfTable(array_iftable);
3170 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003171
Elliott Hughes00626c22013-06-14 15:04:14 -07003172 // Inherit access flags from the component type.
3173 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3174 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3175 access_flags &= kAccJavaFlagsMask;
3176 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003177 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003178 access_flags |= kAccAbstract | kAccFinal;
3179 access_flags &= ~kAccInterface;
3180
3181 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003182
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003183 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003184 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003185 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003186 }
3187 // Another thread must have loaded the class after we
3188 // started but before we finished. Abandon what we've
3189 // done.
3190 //
3191 // (Yes, this happens.)
3192
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003193 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003194}
3195
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003196mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003197 switch (type) {
3198 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003199 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003200 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003201 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003202 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003203 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003204 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003205 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003206 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003207 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003208 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003209 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003210 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003211 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003212 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003213 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003214 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003215 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003216 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003217 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003218 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003219 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003220 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003221 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003222}
3223
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003224mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3225 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003226 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003227 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003228 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003229 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003230 source += " from ";
3231 source += dex_cache->GetLocation()->ToModifiedUtf8();
3232 }
3233 LOG(INFO) << "Loaded class " << descriptor << source;
3234 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003235 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003236 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003237 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003238 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003239 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003240 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003241 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003242 // Check a class loaded with the system class loader matches one in the image if the class
3243 // is in the image.
3244 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003245 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003246 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003247 }
3248 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003249 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003250 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003251 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003252 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003253 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003254 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003255}
3256
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003257mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3258 size_t hash) {
3259 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003260 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3261 hash);
3262 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003263 CHECK(klass->IsProxyClass());
3264 return nullptr;
3265 }
3266
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003267 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003268 CHECK_NE(existing, klass) << descriptor;
3269 CHECK(!existing->IsResolved()) << descriptor;
3270 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3271
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003272 CHECK(!klass->IsTemp()) << descriptor;
3273 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3274 dex_cache_image_class_lookup_required_) {
3275 // Check a class loaded with the system class loader matches one in the image if the class
3276 // is in the image.
3277 existing = LookupClassFromImage(descriptor);
3278 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003279 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003280 }
3281 }
3282 VerifyObject(klass);
3283
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003284 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003285 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003286 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003287 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003288 }
3289
3290 return existing;
3291}
3292
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003293bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003294 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003295 auto pair = std::make_pair(descriptor, class_loader);
3296 auto it = class_table_.Find(pair);
3297 if (it != class_table_.end()) {
3298 class_table_.Erase(it);
3299 return true;
3300 }
3301 it = pre_zygote_class_table_.Find(pair);
3302 if (it != pre_zygote_class_table_.end()) {
3303 pre_zygote_class_table_.Erase(it);
3304 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003305 }
3306 return false;
3307}
3308
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003309mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003310 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003311 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003312 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003313 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003314 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003315 return result;
3316 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003317 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003318 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3319 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003320 } else {
3321 // Lookup failed but need to search dex_caches_.
3322 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003323 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003324 InsertClass(descriptor, result, hash);
3325 } else {
3326 // Searching the image dex files/caches failed, we don't want to get into this situation
3327 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3328 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003329 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003330 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3331 MoveImageClassesToClassTable();
3332 }
3333 }
3334 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003335 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003336}
3337
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003338mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003339 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003340 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003341 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3342 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3343 if (it == pre_zygote_class_table_.end()) {
3344 it = class_table_.FindWithHash(descriptor_pair, hash);
3345 if (it == class_table_.end()) {
3346 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003347 }
3348 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003349 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003350}
3351
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003352static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3353 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3354 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003355 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003356 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3357 return root->AsObjectArray<mirror::DexCache>();
3358}
3359
3360void ClassLinker::MoveImageClassesToClassTable() {
3361 Thread* self = Thread::Current();
3362 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3363 if (!dex_cache_image_class_lookup_required_) {
3364 return; // All dex cache classes are already in the class table.
3365 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003366 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003367 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003368 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003369 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3370 mirror::DexCache* dex_cache = dex_caches->Get(i);
3371 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3372 for (int32_t j = 0; j < types->GetLength(); j++) {
3373 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003374 if (klass != nullptr) {
3375 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003376 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003377 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003378 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3379 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003380 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003381 << PrettyClassAndClassLoader(klass);
3382 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003383 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003384 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003385 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003386 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003387 }
3388 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003389 }
3390 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003391 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003392}
3393
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003394void ClassLinker::MoveClassTableToPreZygote() {
3395 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3396 DCHECK(pre_zygote_class_table_.Empty());
3397 pre_zygote_class_table_ = std::move(class_table_);
3398 class_table_.Clear();
3399}
3400
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003401mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003402 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003403 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3404 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3405 mirror::DexCache* dex_cache = dex_caches->Get(i);
3406 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003407 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003408 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003409 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003410 const DexFile::TypeId* type_id =
3411 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003412 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003413 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3414 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003415 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003416 return klass;
3417 }
3418 }
3419 }
3420 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003421 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003422}
3423
3424void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3425 result.clear();
3426 if (dex_cache_image_class_lookup_required_) {
3427 MoveImageClassesToClassTable();
3428 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003429 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3430 while (true) {
3431 auto it = class_table_.Find(descriptor);
3432 if (it == class_table_.end()) {
3433 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003434 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003435 result.push_back(it->Read());
3436 class_table_.Erase(it);
3437 }
3438 for (mirror::Class* k : result) {
3439 class_table_.Insert(GcRoot<mirror::Class>(k));
3440 }
3441 size_t pre_zygote_start = result.size();
3442 // Now handle the pre zygote table.
3443 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3444 // called from the debugger.
3445 while (true) {
3446 auto it = pre_zygote_class_table_.Find(descriptor);
3447 if (it == pre_zygote_class_table_.end()) {
3448 break;
3449 }
3450 result.push_back(it->Read());
3451 pre_zygote_class_table_.Erase(it);
3452 }
3453 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3454 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003455 }
3456}
3457
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003458void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003459 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003460 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003461
Ian Rogers9ffb0392012-09-10 11:56:50 -07003462 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003463 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003464 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003465 return;
3466 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003467 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3468 return;
3469 }
jeffhao98eacac2011-09-14 16:11:53 -07003470
Ian Rogers9ffb0392012-09-10 11:56:50 -07003471 // The class might already be erroneous, for example at compile time if we attempted to verify
3472 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003473 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003474 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003475 return;
3476 }
3477
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003478 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003479 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003480 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003481 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003482 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003483 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003484 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003485 }
jeffhao98eacac2011-09-14 16:11:53 -07003486
Jeff Hao4a200f52014-04-01 14:58:49 -07003487 // Skip verification if disabled.
3488 if (!Runtime::Current()->IsVerificationEnabled()) {
3489 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003490 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003491 return;
3492 }
3493
Ian Rogers9ffb0392012-09-10 11:56:50 -07003494 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003495 StackHandleScope<2> hs(self);
3496 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003497 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003498 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003499 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003500
3501 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003502 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003503 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003504 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003505 std::string error_msg(
3506 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3507 PrettyDescriptor(klass.Get()).c_str(),
3508 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003509 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003510 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3511 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003512 self->ClearException();
3513 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003514 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3515 if (cause.Get() != nullptr) {
3516 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003517 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003518 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003519 if (Runtime::Current()->IsCompiler()) {
3520 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3521 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003522 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003523 return;
3524 }
3525 }
3526
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003527 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003528 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003529 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003530 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003531 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003532 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003533 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003534 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003535 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3536 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003537 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003538 return;
3539 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003540 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003541 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003542 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003543 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003544 Runtime::Current()->IsCompiler(),
3545 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003546 }
3547 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003548 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003549 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003550 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3551 << " because: " << error_msg;
3552 }
Ian Rogers1f539342012-10-03 21:09:42 -07003553 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003554 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003555 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003556 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003557 // Even though there were no verifier failures we need to respect whether the super-class
3558 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003559 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003560 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003561 } else {
3562 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003563 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003564 // Pretend a soft failure occured so that we don't consider the class verified below.
3565 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003566 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003567 } else {
3568 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3569 // Soft failures at compile time should be retried at runtime. Soft
3570 // failures at runtime will be handled by slow paths in the generated
3571 // code. Set status accordingly.
3572 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003573 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003574 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003575 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003576 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3577 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003578 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003579 }
3580 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003581 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003582 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003583 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3584 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003585 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003586 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003587 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003588 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003589 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003590 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003591 // Let the interpreter know it by setting the kAccPreverified flag onto each
3592 // method.
3593 // Note: we're going here during compilation and at runtime. When we set the
3594 // kAccPreverified flag when compiling image classes, the flag is recorded
3595 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003596 EnsurePreverifiedMethods(klass);
3597 }
3598}
3599
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003600void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003601 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003602 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003603 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003604 }
jeffhao98eacac2011-09-14 16:11:53 -07003605}
3606
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003607bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3608 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003609 // If we're compiling, we can only verify the class using the oat file if
3610 // we are not compiling the image or if the class we're verifying is not part of
3611 // the app. In other words, we will only check for preverification of bootclasspath
3612 // classes.
3613 if (Runtime::Current()->IsCompiler()) {
3614 // Are we compiling the bootclasspath?
3615 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3616 return false;
3617 }
3618 // We are compiling an app (not the image).
3619
3620 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003621 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003622 return false;
3623 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003624 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003625
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003626 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003627 // In case we run without an image there won't be a backing oat file.
3628 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003629 return false;
3630 }
3631
Andreas Gampe76bd8802014-12-10 16:43:58 -08003632 // We may be running with a preopted oat file but without image. In this case,
3633 // we don't skip verification of preverified classes to ensure we initialize
3634 // dex caches with all types resolved during verification.
3635 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
3636 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
3637 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
3638 // already pre-opted, as then the runtime is started.
3639 if (!Runtime::Current()->IsCompiler() &&
3640 !Runtime::Current()->GetHeap()->HasImageSpace() &&
3641 klass->GetClassLoader() != nullptr) {
3642 return false;
3643 }
3644
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003645 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003646 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003647 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3648 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003649 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003650 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003651 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003652 // Compile time verification failed with a soft error. Compile time verification can fail
3653 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003654 // class ... {
3655 // Foo x;
3656 // .... () {
3657 // if (...) {
3658 // v1 gets assigned a type of resolved class Foo
3659 // } else {
3660 // v1 gets assigned a type of unresolved class Bar
3661 // }
3662 // iput x = v1
3663 // } }
3664 // when we merge v1 following the if-the-else it results in Conflict
3665 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3666 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3667 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3668 // at compile time).
3669 return false;
3670 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003671 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003672 // Compile time verification failed with a hard error. This is caused by invalid instructions
3673 // in the class. These errors are unrecoverable.
3674 return false;
3675 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003676 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003677 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3678 // not loading the class.
3679 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3680 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003681 return false;
3682 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003683 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003684 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003685 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003686 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003687 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003688}
3689
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003690void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003691 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003692 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3693 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3694 }
3695 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3696 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3697 }
3698}
3699
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003700void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003701 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003702 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3703 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003704 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003705 return; // native or abstract method
3706 }
3707 if (code_item->tries_size_ == 0) {
3708 return; // nothing to process
3709 }
Ian Rogers13735952014-10-08 12:43:28 -07003710 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003711 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3712 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3713 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3714 CatchHandlerIterator iterator(handlers_ptr);
3715 for (; iterator.HasNext(); iterator.Next()) {
3716 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3717 // unresolved exception types will be ignored by exception delivery
3718 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003719 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003720 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003721 DCHECK(Thread::Current()->IsExceptionPending());
3722 Thread::Current()->ClearException();
3723 }
3724 }
3725 }
3726 handlers_ptr = iterator.EndDataPointer();
3727 }
3728}
3729
Brian Carlstromea46f952013-07-30 01:26:50 -07003730static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003731static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3732 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003733
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003734mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003735 jobjectArray interfaces, jobject loader,
3736 jobjectArray methods, jobjectArray throws) {
3737 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003738 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003739 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003740 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003741 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003742 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003743 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003744 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003745 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003746 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003747 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3748 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003749 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003750 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003751 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003752 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003753 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003754 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003755
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003756 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003757 {
3758 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003759 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003760 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003761 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003762 }
3763 klass->SetSFields(sfields);
3764 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003765 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3766 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003767 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3768 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003769 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003770 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003771 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003772 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003773 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003774 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003775 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3776 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003777 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3778 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003779 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003780 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003781 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003782 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003783 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003784 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003785 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003786
Ian Rogers466bb252011-10-14 03:29:56 -07003787 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003788 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003789 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003790 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003791 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003792 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003793 }
3794 klass->SetDirectMethods(directs);
3795 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003796 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003797 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003798 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003799 }
3800 klass->SetDirectMethod(0, constructor);
3801 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003802
Mathieu Chartier590fee92013-09-13 13:46:47 -07003803 // Create virtual method using specified prototypes.
3804 size_t num_virtual_methods =
3805 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003806 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003807 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3808 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003809 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003810 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003811 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003812 }
3813 klass->SetVirtualMethods(virtuals);
3814 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003815 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003816 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003817 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3818 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003819 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003820 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003821 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003822 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003823 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003824 }
3825 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003826 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003827
3828 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003829 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003830 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003831
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003832 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3833 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003834 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003835 // Must hold lock on object when resolved.
3836 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003837 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003838 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003839 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003840 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003841 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003842 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003843 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003844 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003845
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003846 CHECK(klass->IsRetired());
3847 CHECK_NE(klass.Get(), new_class);
3848 klass.Assign(new_class);
3849
3850 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003851 interfaces_sfield->SetObject<false>(klass.Get(),
3852 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003853 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003854 throws_sfield->SetObject<false>(klass.Get(),
3855 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003856
3857 {
3858 // Lock on klass is released. Lock new class object.
3859 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003860 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003861 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003862
3863 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003864 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003865 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003866 CheckProxyConstructor(klass->GetDirectMethod(0));
3867 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003868 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003869 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3870 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003871 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3872 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003873 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003874 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003875
Mathieu Chartier590fee92013-09-13 13:46:47 -07003876 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003877 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003878 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003879 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3880
3881 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003882 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003883 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003884
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003885 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003886 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003887 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003888 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003889 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003890 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3891 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003892 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003893 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003894}
3895
Ian Rogersef7d42f2014-01-06 12:55:46 -08003896std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003897 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003898 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003899 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003900 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3901}
3902
Ian Rogersef7d42f2014-01-06 12:55:46 -08003903mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3904 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003905 DCHECK(proxy_class->IsProxyClass());
3906 DCHECK(proxy_method->IsProxyMethod());
3907 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003908 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003909 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003910 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003911 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003912 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003913 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003914 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003915 break;
3916 }
3917 }
3918 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003919 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003920 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003921 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003922 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003923 return resolved_method;
3924}
3925
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003926
Brian Carlstromea46f952013-07-30 01:26:50 -07003927mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003928 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003929 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003930 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003931 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003932 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003933 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3934 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003935 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3936 // constructor method.
3937 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3938 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003939 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3940 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003941 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3942 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003943 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003944 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003945 }
Ian Rogers466bb252011-10-14 03:29:56 -07003946 // Make this constructor public and fix the class to be our Proxy version
3947 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003948 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003949 return constructor;
3950}
3951
Brian Carlstromea46f952013-07-30 01:26:50 -07003952static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003953 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003954 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003955 CHECK_STREQ(constructor->GetName(), "<init>");
3956 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3957 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003958 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003959}
3960
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003961mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003962 Handle<mirror::Class> klass,
3963 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003964 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3965 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003966 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003967 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003968 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003969 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003970 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003971 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003972 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003973 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003974 }
Ian Rogers466bb252011-10-14 03:29:56 -07003975
3976 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3977 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003978 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003979 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003980
Ian Rogers466bb252011-10-14 03:29:56 -07003981 // At runtime the method looks like a reference and argument saving method, clone the code
3982 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003983 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003984 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003985
Ian Rogersc2b44472011-12-14 21:17:17 -08003986 return method;
3987}
Jesse Wilson95caa792011-10-12 18:14:17 -04003988
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003989static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3990 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003991 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003992 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003993 CHECK(!prototype->IsFinal());
3994 CHECK(method->IsFinal());
3995 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003996
3997 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3998 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07003999 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4000 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004001 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4002
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004003 CHECK_STREQ(method->GetName(), prototype->GetName());
4004 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004005 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004006 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004007}
4008
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004009static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4010 bool can_init_parents)
4011 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004012 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004013 return true;
4014 }
4015 if (!can_init_statics) {
4016 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004017 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004018 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004019 return false;
4020 }
4021 // Check if there are encoded static values needing initialization.
4022 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004023 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004024 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004025 if (dex_class_def->static_values_off_ != 0) {
4026 return false;
4027 }
4028 }
4029 }
4030 if (!klass->IsInterface() && klass->HasSuperClass()) {
4031 mirror::Class* super_class = klass->GetSuperClass();
4032 if (!can_init_parents && !super_class->IsInitialized()) {
4033 return false;
4034 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004035 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004036 return false;
4037 }
4038 }
4039 }
4040 return true;
4041}
4042
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004043bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004044 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004045 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4046
4047 // Are we already initialized and therefore done?
4048 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4049 // an initialized class will never change its state.
4050 if (klass->IsInitialized()) {
4051 return true;
4052 }
4053
4054 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004055 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004056 return false;
4057 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004058
Ian Rogers7b078e82014-09-10 14:44:24 -07004059 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004060 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004061 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004062 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004063
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004064 // Re-check under the lock in case another thread initialized ahead of us.
4065 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004066 return true;
4067 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004068
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004069 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004070 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004071 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004072 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004073 return false;
4074 }
4075
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004076 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004077
4078 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004079 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004080 if (!klass->IsVerified()) {
4081 // We failed to verify, expect either the klass to be erroneous or verification failed at
4082 // compile time.
4083 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004084 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004085 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004086 } else {
4087 CHECK(Runtime::Current()->IsCompiler());
4088 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004089 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004090 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004091 } else {
4092 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004093 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004094 }
4095
Brian Carlstromd1422f82011-09-28 11:37:09 -07004096 // If the class is kStatusInitializing, either this thread is
4097 // initializing higher up the stack or another thread has beat us
4098 // to initializing and we need to wait. Either way, this
4099 // invocation of InitializeClass will not be responsible for
4100 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004101 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004102 // Could have got an exception during verification.
4103 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004104 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004105 return false;
4106 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004107 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004108 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004109 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004110 return true;
4111 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004112 // No. That's fine. Wait for another thread to finish initializing.
4113 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004114 }
4115
4116 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004117 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004118 return false;
4119 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004120 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004121
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004122 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004123
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004124 // From here out other threads may observe that we're initializing and so changes of state
4125 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004126 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004127 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004128
4129 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004130 }
4131
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004132 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004133 if (!klass->IsInterface() && klass->HasSuperClass()) {
4134 mirror::Class* super_class = klass->GetSuperClass();
4135 if (!super_class->IsInitialized()) {
4136 CHECK(!super_class->IsInterface());
4137 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004138 StackHandleScope<1> hs(self);
4139 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004140 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004141 if (!super_initialized) {
4142 // The super class was verified ahead of entering initializing, we should only be here if
4143 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004144 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004145 << "Super class initialization failed for "
4146 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004147 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004148 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004149 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004150 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004151 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004152 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004153 return false;
4154 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004155 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004156 }
4157
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004158 const size_t num_static_fields = klass->NumStaticFields();
4159 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004160 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004161 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004162 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004163 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004164 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004165 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004166
4167 // Eagerly fill in static fields so that the we don't have to do as many expensive
4168 // Class::FindStaticField in ResolveField.
4169 for (size_t i = 0; i < num_static_fields; ++i) {
4170 mirror::ArtField* field = klass->GetStaticField(i);
4171 const uint32_t field_idx = field->GetDexFieldIndex();
4172 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4173 if (resolved_field == nullptr) {
4174 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004175 } else {
4176 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004177 }
4178 }
4179
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004180 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4181 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004182 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004183 ClassDataItemIterator field_it(dex_file, class_data);
4184 if (value_it.HasNext()) {
4185 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004186 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004187 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004188 StackHandleScope<1> hs2(self);
4189 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004190 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004191 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004192 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004193 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004194 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004195 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004196 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004197 }
4198 }
4199 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004200
Ian Rogersd91d6d62013-09-25 20:26:14 -07004201 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004202 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004203 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004204 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004205 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004206 }
4207
Ian Rogers7b078e82014-09-10 14:44:24 -07004208 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004209 uint64_t t1 = NanoTime();
4210
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004211 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004212 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004213 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004214
4215 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004216 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004217 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004218 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004219 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004220 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4221 RuntimeStats* thread_stats = self->GetStats();
4222 ++global_stats->class_init_count;
4223 ++thread_stats->class_init_count;
4224 global_stats->class_init_time_ns += (t1 - t0);
4225 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004226 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004227 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004228 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004229 std::string temp;
4230 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004231 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004232 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004233 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004234 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004235 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004236 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004237 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004238}
4239
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004240bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004241 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004242 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004243 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004244 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004245 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004246 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004247
4248 // When we wake up, repeat the test for init-in-progress. If
4249 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004250 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004251 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004252 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004253 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004254 return false;
4255 }
4256 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004257 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004258 continue;
4259 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004260 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004261 // Compile time initialization failed.
4262 return false;
4263 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004264 if (klass->IsErroneous()) {
4265 // The caller wants an exception, but it was thrown in a
4266 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004267 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004268 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004269 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004270 return false;
4271 }
4272 if (klass->IsInitialized()) {
4273 return true;
4274 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004275 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004276 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004277 }
Ian Rogers07140832014-09-30 15:43:59 -07004278 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004279}
4280
Ian Rogersb5fb2072014-12-02 17:22:02 -08004281static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
4282 Handle<mirror::ArtMethod> method1,
4283 Handle<mirror::ArtMethod> method2)
4284 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4285 {
4286 StackHandleScope<1> hs(self);
4287 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
4288 if (UNLIKELY(method2->GetReturnType() != return_type.Get())) {
4289 return false;
4290 }
4291 }
4292 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4293 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4294 if (types1 == nullptr) {
4295 return (types2 == nullptr) || (types2->Size() == 0);
4296 } else if (UNLIKELY(types2 == nullptr)) {
4297 return types1->Size() == 0;
4298 }
4299 uint32_t num_types = types1->Size();
4300 if (UNLIKELY(num_types != types2->Size())) {
4301 return false;
4302 }
4303 for (uint32_t i = 0; i < num_types; ++i) {
4304 mirror::Class* param_type =
4305 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true);
4306 mirror::Class* other_param_type =
4307 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
4308 if (UNLIKELY(param_type != other_param_type)) {
4309 return false;
4310 }
4311 }
4312 return true;
4313}
4314
4315
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004316bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004317 if (klass->IsInterface()) {
4318 return true;
4319 }
Ian Rogers151f2212014-05-06 11:27:27 -07004320 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004321 Thread* self = Thread::Current();
4322 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004323 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
4324 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004325 if (klass->HasSuperClass() &&
4326 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004327 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004328 h_m.Assign(klass->GetVTableEntry(i));
4329 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
4330 if (h_m.Get() != super_h_m.Get() &&
4331 !HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004332 ThrowLinkageError(klass.Get(),
4333 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004334 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogersb5fb2072014-12-02 17:22:02 -08004335 PrettyMethod(h_m.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004336 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004337 return false;
4338 }
4339 }
4340 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004341 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004342 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4343 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4344 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004345 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4346 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
4347 if (h_m.Get() != super_h_m.Get() &&
4348 !HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004349 ThrowLinkageError(klass.Get(),
4350 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004351 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogersb5fb2072014-12-02 17:22:02 -08004352 PrettyMethod(h_m.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004353 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004354 return false;
4355 }
4356 }
4357 }
4358 }
4359 return true;
4360}
4361
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004362bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4363 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004364 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004365 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004366 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004367 return true;
4368 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004369 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004370 if (!success) {
4371 if (can_init_fields && can_init_parents) {
4372 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4373 }
4374 } else {
4375 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004376 }
4377 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004378}
4379
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004380void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4381 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4382 if (fields != nullptr) {
4383 for (int index = 0; index < fields->GetLength(); index ++) {
4384 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4385 fields->Get(index)->SetDeclaringClass(new_class);
4386 }
4387 }
4388 }
4389
4390 fields = new_class->GetSFields();
4391 if (fields != nullptr) {
4392 for (int index = 0; index < fields->GetLength(); index ++) {
4393 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4394 fields->Get(index)->SetDeclaringClass(new_class);
4395 }
4396 }
4397 }
4398
4399 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4400 if (methods != nullptr) {
4401 for (int index = 0; index < methods->GetLength(); index ++) {
4402 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4403 methods->Get(index)->SetDeclaringClass(new_class);
4404 }
4405 }
4406 }
4407
4408 methods = new_class->GetVirtualMethods();
4409 if (methods != nullptr) {
4410 for (int index = 0; index < methods->GetLength(); index ++) {
4411 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4412 methods->Get(index)->SetDeclaringClass(new_class);
4413 }
4414 }
4415 }
4416}
4417
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004418bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4419 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004420 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004421 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004422
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004423 if (!LinkSuperClass(klass)) {
4424 return false;
4425 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004426 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4427 self, Runtime::Current()->GetImtUnimplementedMethod());
4428 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004429 return false;
4430 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004431 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004432 return false;
4433 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004434 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004435 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004436 return false;
4437 }
4438 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004439 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004440
4441 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4442 // We don't need to retire this class as it has no embedded tables or it was created the
4443 // correct size during class linker initialization.
4444 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4445
4446 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004447 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004448 }
4449
4450 // This will notify waiters on klass that saw the not yet resolved
4451 // class in the class_table_ during EnsureResolved.
4452 klass->SetStatus(mirror::Class::kStatusResolved, self);
4453 *new_class = klass.Get();
4454 } else {
4455 CHECK(!klass->IsResolved());
4456 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004457 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004458 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004459 CHECK(self->IsExceptionPending()); // Expect an OOME.
4460 klass->SetStatus(mirror::Class::kStatusError, self);
4461 return false;
4462 }
4463
4464 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4465 StackHandleScope<1> hs(self);
4466 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4467 ObjectLock<mirror::Class> lock(self, new_class_h);
4468
4469 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4470
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004471 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4472 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004473 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004474
4475 // This will notify waiters on temp class that saw the not yet resolved class in the
4476 // class_table_ during EnsureResolved.
4477 klass->SetStatus(mirror::Class::kStatusRetired, self);
4478
4479 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4480 // This will notify waiters on new_class that saw the not yet resolved
4481 // class in the class_table_ during EnsureResolved.
4482 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004483 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004484 return true;
4485}
4486
Andreas Gampefd9eb392014-11-06 16:52:58 -08004487static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
4488 size_t* virtual_methods,
4489 size_t* direct_methods,
4490 size_t* static_fields,
4491 size_t* instance_fields) {
4492 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
4493
4494 while (dex_data.HasNextStaticField()) {
4495 dex_data.Next();
4496 (*static_fields)++;
4497 }
4498 while (dex_data.HasNextInstanceField()) {
4499 dex_data.Next();
4500 (*instance_fields)++;
4501 }
4502 while (dex_data.HasNextDirectMethod()) {
4503 (*direct_methods)++;
4504 dex_data.Next();
4505 }
4506 while (dex_data.HasNextVirtualMethod()) {
4507 (*virtual_methods)++;
4508 dex_data.Next();
4509 }
4510 DCHECK(!dex_data.HasNext());
4511}
4512
4513static void DumpClass(std::ostream& os,
4514 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
4515 const char* suffix) {
4516 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
4517 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
4518 os << " Static fields:\n";
4519 while (dex_data.HasNextStaticField()) {
4520 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4521 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4522 dex_data.Next();
4523 }
4524 os << " Instance fields:\n";
4525 while (dex_data.HasNextInstanceField()) {
4526 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4527 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4528 dex_data.Next();
4529 }
4530 os << " Direct methods:\n";
4531 while (dex_data.HasNextDirectMethod()) {
4532 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4533 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4534 dex_data.Next();
4535 }
4536 os << " Virtual methods:\n";
4537 while (dex_data.HasNextVirtualMethod()) {
4538 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4539 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4540 dex_data.Next();
4541 }
4542}
4543
4544static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4545 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
4546 std::ostringstream os;
4547 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
4548 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
4549 return os.str();
4550}
4551
4552
4553// Very simple structural check on whether the classes match. Only compares the number of
4554// methods and fields.
4555static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4556 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
4557 std::string* error_msg) {
4558 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
4559 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
4560
4561 // Counters for current dex file.
4562 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
4563 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
4564 &dex_instance_fields1);
4565 // Counters for compile-time dex file.
4566 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
4567 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
4568 &dex_instance_fields2);
4569
4570 if (dex_virtual_methods1 != dex_virtual_methods2) {
4571 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4572 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
4573 dex_virtual_methods2, class_dump.c_str());
4574 return false;
4575 }
4576 if (dex_direct_methods1 != dex_direct_methods2) {
4577 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4578 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
4579 dex_direct_methods2, class_dump.c_str());
4580 return false;
4581 }
4582 if (dex_static_fields1 != dex_static_fields2) {
4583 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4584 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
4585 dex_static_fields2, class_dump.c_str());
4586 return false;
4587 }
4588 if (dex_instance_fields1 != dex_instance_fields2) {
4589 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4590 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
4591 dex_instance_fields2, class_dump.c_str());
4592 return false;
4593 }
4594
4595 return true;
4596}
4597
4598// Checks whether a the super-class changed from what we had at compile-time. This would
4599// invalidate quickening.
4600static bool CheckSuperClassChange(Handle<mirror::Class> klass,
4601 const DexFile& dex_file,
4602 const DexFile::ClassDef& class_def,
4603 mirror::Class* super_class)
4604 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4605 // Check for unexpected changes in the superclass.
4606 // Quick check 1) is the super_class class-loader the boot class loader? This always has
4607 // precedence.
4608 if (super_class->GetClassLoader() != nullptr &&
4609 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
4610 // which is implied by different dex cache.
4611 klass->GetDexCache() != super_class->GetDexCache()) {
4612 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
4613 // definition for the super-class, and (b) the files are in separate oat files. The oat files
4614 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
4615 const OatFile* class_oat_file = dex_file.GetOatFile();
4616 if (class_oat_file != nullptr) {
4617 const OatFile* loaded_super_oat_file = super_class->GetDexFile().GetOatFile();
4618 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
4619 // Now check (a).
4620 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
4621 if (super_class_def != nullptr) {
4622 // Uh-oh, we found something. Do our check.
4623 std::string error_msg;
4624 if (!SimpleStructuralCheck(dex_file, *super_class_def,
4625 super_class->GetDexFile(), *super_class->GetClassDef(),
4626 &error_msg)) {
4627 // Print a warning to the log. This exception might be caught, e.g., as common in test
4628 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
4629 // only save the type of the exception.
4630 LOG(WARNING) << "Incompatible structural change detected: " <<
4631 StringPrintf(
4632 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4633 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4634 class_oat_file->GetLocation().c_str(),
4635 loaded_super_oat_file->GetLocation().c_str(),
4636 error_msg.c_str());
4637 ThrowIncompatibleClassChangeError(klass.Get(),
4638 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4639 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4640 class_oat_file->GetLocation().c_str(),
4641 loaded_super_oat_file->GetLocation().c_str(),
4642 error_msg.c_str());
4643 return false;
4644 }
4645 }
4646 }
4647 }
4648 }
4649 return true;
4650}
4651
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004652bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004653 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004654 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4655 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004656 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004657 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004658 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004659 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004660 return false;
4661 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004662 // Verify
4663 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004664 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004665 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004666 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004667 return false;
4668 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004669 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004670 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08004671
4672 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
4673 DCHECK(Thread::Current()->IsExceptionPending());
4674 return false;
4675 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004676 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004677 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004678 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004679 for (size_t i = 0; i < interfaces->Size(); i++) {
4680 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004681 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004682 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004683 DCHECK(Thread::Current()->IsExceptionPending());
4684 return false;
4685 }
4686 // Verify
4687 if (!klass->CanAccess(interface)) {
4688 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004689 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004690 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004691 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004692 return false;
4693 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004694 }
4695 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004696 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004697 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004698 return true;
4699}
4700
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004701bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004702 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004703 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004704 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004705 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004706 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004707 return false;
4708 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004709 return true;
4710 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004711 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004712 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4713 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004714 return false;
4715 }
4716 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004717 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004718 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004719 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004720 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004721 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004722 return false;
4723 }
4724 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004725 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004726 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004727 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004728 return false;
4729 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004730
Brian Carlstromf3632832014-05-20 15:36:53 -07004731 // Inherit kAccClassIsFinalizable from the superclass in case this
4732 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004733 if (super->IsFinalizable()) {
4734 klass->SetFinalizable();
4735 }
4736
Elliott Hughes2da50362011-10-10 16:57:08 -07004737 // Inherit reference flags (if any) from the superclass.
4738 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4739 if (reference_flags != 0) {
4740 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4741 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004742 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004743 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004744 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004745 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004746 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004747 return false;
4748 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004749
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004750 if (kIsDebugBuild) {
4751 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004752 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004753 CHECK(super->IsResolved());
4754 super = super->GetSuperClass();
4755 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004756 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004757 return true;
4758}
4759
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004760// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004761bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004762 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4763 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004764 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004765 if (klass->IsInterface()) {
4766 // No vtable.
4767 size_t count = klass->NumVirtualMethods();
4768 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004769 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004770 return false;
4771 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004772 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004773 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004774 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004775 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4776 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004777 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004778 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004779}
4780
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004781// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4782// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4783// caches in the implementation below.
4784class MethodNameAndSignatureComparator FINAL : public ValueObject {
4785 public:
4786 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4787 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4788 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4789 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004790 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4791 }
4792
4793 const char* GetName() {
4794 if (name_ == nullptr) {
4795 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4796 }
4797 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004798 }
4799
4800 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4801 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4802 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4803 const DexFile* other_dex_file = other->GetDexFile();
4804 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4805 if (dex_file_ == other_dex_file) {
4806 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4807 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004808 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004809 uint32_t other_name_len;
4810 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4811 &other_name_len);
4812 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4813 return false;
4814 }
4815 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4816 }
4817
4818 private:
4819 // Dex file for the method to compare against.
4820 const DexFile* const dex_file_;
4821 // MethodId for the method to compare against.
4822 const DexFile::MethodId* const mid_;
4823 // Lazily computed name from the dex file's strings.
4824 const char* name_;
4825 // Lazily computed name length.
4826 uint32_t name_len_;
4827};
4828
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004829class LinkVirtualHashTable {
4830 public:
4831 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4832 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4833 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4834 }
4835 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4836 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4837 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004838 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004839 uint32_t index = hash % hash_size_;
4840 // Linear probe until we have an empty slot.
4841 while (hash_table_[index] != invalid_index_) {
4842 if (++index == hash_size_) {
4843 index = 0;
4844 }
4845 }
4846 hash_table_[index] = virtual_method_index;
4847 }
4848 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4849 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4850 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004851 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004852 size_t index = hash % hash_size_;
4853 while (true) {
4854 const uint32_t value = hash_table_[index];
4855 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4856 // the block and can safely assume not found.
4857 if (value == invalid_index_) {
4858 break;
4859 }
4860 if (value != removed_index_) { // This signifies not already overriden.
4861 mirror::ArtMethod* virtual_method =
4862 klass_->GetVirtualMethodDuringLinking(value);
4863 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4864 hash_table_[index] = removed_index_;
4865 return value;
4866 }
4867 }
4868 if (++index == hash_size_) {
4869 index = 0;
4870 }
4871 }
4872 return GetNotFoundIndex();
4873 }
4874 static uint32_t GetNotFoundIndex() {
4875 return invalid_index_;
4876 }
4877
4878 private:
4879 static const uint32_t invalid_index_;
4880 static const uint32_t removed_index_;
4881
4882 Handle<mirror::Class> klass_;
4883 const size_t hash_size_;
4884 uint32_t* const hash_table_;
4885};
4886
4887const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4888const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4889
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004890bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004891 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004892 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004893 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4894 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004895 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004896 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004897 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004898 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4899 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4900 if (UNLIKELY(vtable.Get() == nullptr)) {
4901 CHECK(self->IsExceptionPending()); // OOME.
4902 return false;
4903 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004904 for (size_t i = 0; i < super_vtable_length; i++) {
4905 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004906 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004907 if (num_virtual_methods == 0) {
4908 klass->SetVTable(vtable.Get());
4909 return true;
4910 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004911 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004912 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4913 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4914 if (num_virtual_methods == 0) {
4915 klass->SetVTable(super_vtable);
4916 return true;
4917 }
4918 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004919 if (UNLIKELY(vtable.Get() == nullptr)) {
4920 CHECK(self->IsExceptionPending()); // OOME.
4921 return false;
4922 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004923 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004924 // How the algorithm works:
4925 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4926 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4927 // method which has not been matched to a vtable method, and j if the virtual method at the
4928 // index overrode the super virtual method at index j.
4929 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4930 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4931 // the need for the initial vtable which we later shrink back down).
4932 // 3. Add non overridden methods to the end of the vtable.
4933 static constexpr size_t kMaxStackHash = 250;
4934 const size_t hash_table_size = num_virtual_methods * 3;
4935 uint32_t* hash_table_ptr;
4936 std::unique_ptr<uint32_t[]> hash_heap_storage;
4937 if (hash_table_size <= kMaxStackHash) {
4938 hash_table_ptr = reinterpret_cast<uint32_t*>(
4939 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4940 } else {
4941 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4942 hash_table_ptr = hash_heap_storage.get();
4943 }
4944 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4945 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004946 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004947 hash_table.Add(i);
4948 }
4949 // Loop through each super vtable method and see if they are overriden by a method we added to
4950 // the hash table.
4951 for (size_t j = 0; j < super_vtable_length; ++j) {
4952 // Search the hash table to see if we are overidden by any method.
4953 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4954 MethodNameAndSignatureComparator super_method_name_comparator(
4955 super_method->GetInterfaceMethodIfProxy());
4956 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4957 if (hash_index != hash_table.GetNotFoundIndex()) {
4958 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4959 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4960 super_method->GetAccessFlags())) {
4961 if (super_method->IsFinal()) {
4962 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4963 PrettyMethod(virtual_method).c_str(),
4964 super_method->GetDeclaringClassDescriptor());
4965 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004966 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004967 vtable->SetWithoutChecks<false>(j, virtual_method);
4968 virtual_method->SetMethodIndex(j);
4969 } else {
4970 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004971 << " would have incorrectly overridden the package-private method in "
4972 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004973 }
4974 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004975 }
4976 // Add the non overridden methods at the end.
4977 size_t actual_count = super_vtable_length;
4978 for (size_t i = 0; i < num_virtual_methods; ++i) {
4979 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4980 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4981 if (method_idx < super_vtable_length &&
4982 local_method == vtable->GetWithoutChecks(method_idx)) {
4983 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004984 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004985 vtable->SetWithoutChecks<false>(actual_count, local_method);
4986 local_method->SetMethodIndex(actual_count);
4987 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004988 }
4989 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004990 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004991 return false;
4992 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004993 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004994 CHECK_LE(actual_count, max_count);
4995 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004996 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004997 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004998 CHECK(self->IsExceptionPending()); // OOME.
4999 return false;
5000 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005001 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005002 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005003 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005004 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005005 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005006 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5007 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005008 return false;
5009 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005010 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
5011 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005012 CHECK(self->IsExceptionPending()); // OOME.
5013 return false;
5014 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005015 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005016 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005017 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005018 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005019 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005020 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005021 }
5022 return true;
5023}
5024
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005025bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
5026 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
5027 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07005028 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005029 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005030 const bool has_superclass = klass->HasSuperClass();
5031 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
5032 const bool have_interfaces = interfaces.Get() != nullptr;
5033 const size_t num_interfaces =
5034 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
5035 if (num_interfaces == 0) {
5036 if (super_ifcount == 0) {
5037 // Class implements no interfaces.
5038 DCHECK_EQ(klass->GetIfTableCount(), 0);
5039 DCHECK(klass->GetIfTable() == nullptr);
5040 return true;
5041 }
Ian Rogers9bc81912012-10-11 21:43:36 -07005042 // Class implements same interfaces as parent, are any of these not marker interfaces?
5043 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005044 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005045 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005046 if (super_iftable->GetMethodArrayCount(i) > 0) {
5047 has_non_marker_interface = true;
5048 break;
5049 }
5050 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005051 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07005052 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005053 klass->SetIfTable(super_iftable);
5054 return true;
5055 }
5056 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005057 size_t ifcount = super_ifcount + num_interfaces;
5058 for (size_t i = 0; i < num_interfaces; i++) {
5059 mirror::Class* interface = have_interfaces ?
5060 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
5061 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005062 if (UNLIKELY(!interface->IsInterface())) {
5063 std::string temp;
5064 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
5065 PrettyDescriptor(klass.Get()).c_str(),
5066 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
5067 return false;
5068 }
5069 ifcount += interface->GetIfTableCount();
5070 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005071 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005072 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005073 CHECK(self->IsExceptionPending()); // OOME.
5074 return false;
5075 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005076 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005077 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005078 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005079 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07005080 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005081 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005082 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005083 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005084 // Flatten the interface inheritance hierarchy.
5085 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005086 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07005087 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
5088 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005089 // Check if interface is already in iftable
5090 bool duplicate = false;
5091 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005092 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005093 if (existing_interface == interface) {
5094 duplicate = true;
5095 break;
5096 }
5097 }
5098 if (!duplicate) {
5099 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07005100 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005101 // Add this interface's non-duplicate super-interfaces.
5102 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005103 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005104 bool super_duplicate = false;
5105 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005106 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005107 if (existing_interface == super_interface) {
5108 super_duplicate = true;
5109 break;
5110 }
5111 }
5112 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005113 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005114 }
5115 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005116 }
5117 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005118 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08005119 // Shrink iftable in case duplicates were found
5120 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005121 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005122 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005123 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005124 CHECK(self->IsExceptionPending()); // OOME.
5125 return false;
5126 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08005127 ifcount = idx;
5128 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005129 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005130 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005131 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07005132 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07005133 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005134 return true;
5135 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005136 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005137 size_t max_miranda_methods = 0; // The max size of miranda_list.
5138 for (size_t i = 0; i < ifcount; ++i) {
5139 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
5140 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005141 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005142 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005143 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
5144 hs.NewHandle(klass->GetVTableDuringLinking()));
5145 // Copy the IMT from the super class if possible.
5146 bool extend_super_iftable = false;
5147 if (has_superclass) {
5148 mirror::Class* super_class = klass->GetSuperClass();
5149 extend_super_iftable = true;
5150 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5151 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5152 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
5153 }
5154 } else {
5155 // No imt in the super class, need to reconstruct from the iftable.
5156 mirror::IfTable* if_table = super_class->GetIfTable();
5157 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5158 const size_t length = super_class->GetIfTableCount();
5159 for (size_t i = 0; i < length; ++i) {
5160 mirror::Class* interface = iftable->GetInterface(i);
5161 const size_t num_virtuals = interface->NumVirtualMethods();
5162 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5163 DCHECK_EQ(num_virtuals, method_array_count);
5164 if (method_array_count == 0) {
5165 continue;
5166 }
5167 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5168 for (size_t j = 0; j < num_virtuals; ++j) {
5169 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5170 if (method->IsMiranda()) {
5171 continue;
5172 }
5173 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5174 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5175 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5176 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5177 out_imt->SetReference(imt_index, method);
5178 } else if (imt_ref != conflict_method) {
5179 out_imt->SetReference(imt_index, conflict_method);
5180 }
5181 }
5182 }
5183 }
5184 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005185 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005186 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005187 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005188 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005189 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005190 const bool is_super = i < super_ifcount;
5191 const bool super_interface = is_super && extend_super_iftable;
5192 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5193 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5194 if (super_interface) {
5195 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5196 DCHECK(if_table != nullptr);
5197 DCHECK(if_table->GetMethodArray(i) != nullptr);
5198 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005199 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005200 AsObjectArray<mirror::ArtMethod>());
5201 // We are overwriting a super class interface, try to only virtual methods instead of the
5202 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005203 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005204 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005205 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005206 // A new interface, we need the whole vtable incase a new interface method is implemented
5207 // in the whole superclass.
5208 input_array = vtable;
5209 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005210 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005211 CHECK(self->IsExceptionPending()); // OOME.
5212 return false;
5213 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005214 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005215 if (input_array.Get() == nullptr) {
5216 // If the added virtual methods is empty, do nothing.
5217 DCHECK(super_interface);
5218 continue;
5219 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005220 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005221 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005222 MethodNameAndSignatureComparator interface_name_comparator(
5223 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005224 int32_t k;
5225 // For each method listed in the interface's method list, find the
5226 // matching method in our class's method list. We want to favor the
5227 // subclass over the superclass, which just requires walking
5228 // back from the end of the vtable. (This only matters if the
5229 // superclass defines a private method and this class redefines
5230 // it -- otherwise it would use the same vtable slot. In .dex files
5231 // those don't end up in the virtual method table, so it shouldn't
5232 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005233 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5234 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005235 mirror::ArtMethod* vtable_method_for_name_comparison =
5236 vtable_method->GetInterfaceMethodIfProxy();
5237 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005238 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005239 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005240 ThrowIllegalAccessError(
5241 klass.Get(),
5242 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005243 PrettyMethod(vtable_method).c_str(),
5244 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005245 return false;
5246 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005247 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005248 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005249 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5250 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5251 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5252 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5253 out_imt->SetReference(imt_index, vtable_method);
5254 } else if (imt_ref != conflict_method) {
5255 // If we are not a conflict and we have the same signature and name as the imt entry,
5256 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005257 MethodNameAndSignatureComparator imt_ref_name_comparator(
5258 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005259 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005260 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005261 out_imt->SetReference(imt_index, vtable_method);
5262 } else {
5263 out_imt->SetReference(imt_index, conflict_method);
5264 }
Jeff Hao88474b42013-10-23 16:24:40 -07005265 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005266 break;
5267 }
5268 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005269 if (k < 0 && !super_interface) {
5270 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005271 for (size_t l = 0; l < miranda_list_size; ++l) {
5272 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005273 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005274 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005275 break;
5276 }
5277 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005278 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005279 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005280 miranda_method = interface_method->Clone(self)->AsArtMethod();
5281 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005282 CHECK(self->IsExceptionPending()); // OOME.
5283 return false;
5284 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005285 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005286 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005287 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005288 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005289 }
5290 }
5291 }
5292 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005293 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005294 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005295 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005296 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5297 if (old_method_count == 0) {
5298 virtuals = AllocArtMethodArray(self, new_method_count);
5299 } else {
5300 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5301 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005302 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005303 CHECK(self->IsExceptionPending()); // OOME.
5304 return false;
5305 }
5306 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005307
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005308 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005309 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005310 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005311 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005312 CHECK(self->IsExceptionPending()); // OOME.
5313 return false;
5314 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005315 for (size_t i = 0; i < miranda_list_size; ++i) {
5316 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005317 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005318 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5319 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5320 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005321 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005322 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005323 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005324 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005325 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005326
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005327 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005328 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5329 for (int i = 0; i < check_vtable->GetLength(); ++i) {
5330 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005331 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005332 }
5333
Ian Rogers7b078e82014-09-10 14:44:24 -07005334 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005335 return true;
5336}
5337
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005338bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005339 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005340 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005341}
5342
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005343bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005344 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005345 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005346}
5347
Brian Carlstromdbc05252011-09-09 01:59:59 -07005348struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005349 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5350 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005351 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005352 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005353 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005354 // 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 -07005355 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5356 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005357 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005358 if (type1 == Primitive::kPrimNot) {
5359 // Reference always goes first.
5360 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005361 }
Vladimir Markod5777482014-11-12 17:02:02 +00005362 if (type2 == Primitive::kPrimNot) {
5363 // Reference always goes first.
5364 return false;
5365 }
5366 size_t size1 = Primitive::ComponentSize(type1);
5367 size_t size2 = Primitive::ComponentSize(type2);
5368 if (size1 != size2) {
5369 // Larger primitive types go first.
5370 return size1 > size2;
5371 }
5372 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5373 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005374 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005375 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5376 // by name and for equal names by type id index.
5377 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5378 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005379 }
5380};
5381
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005382bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005383 size_t* class_size) {
5384 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005385 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005386 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005387
Brian Carlstromea46f952013-07-30 01:26:50 -07005388 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005389 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005390
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005391 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005392 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005393 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00005394 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005395 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005396 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005397 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005398 CHECK(super_class->IsResolved())
5399 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005400 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005401 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005402 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005403
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005404 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005405
Brian Carlstromdbc05252011-09-09 01:59:59 -07005406 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005407 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005408 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005409 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005410 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005411 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005412 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005413 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005414 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005415 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005416 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5417 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005418
Fred Shih381e4ca2014-08-25 17:24:27 -07005419 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005420 size_t current_field = 0;
5421 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005422 FieldGaps gaps;
5423
Brian Carlstromdbc05252011-09-09 01:59:59 -07005424 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005425 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005426 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005427 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005428 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005429 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005430 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005431 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5432 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005433 MemberOffset old_offset = field_offset;
5434 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5435 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5436 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005437 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005438 grouped_and_sorted_fields.pop_front();
5439 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005440 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005441 field_offset = MemberOffset(field_offset.Uint32Value() +
5442 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005443 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005444 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5445 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005446 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5447 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5448 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5449 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005450 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5451 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005452 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005453
Elliott Hughesadb460d2011-10-05 17:02:34 -07005454 // 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 -07005455 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005456 // We know there are no non-reference fields in the Reference classes, and we know
5457 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005458 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005459 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005460 --num_reference_fields;
5461 }
5462
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005463 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005464 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005465 if (is_static) {
5466 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005467 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005468 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005469 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005470 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08005471 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
5472 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
5473 } else {
5474 std::string temp;
5475 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5476 size_t previous_size = klass->GetObjectSize();
5477 if (previous_size != 0) {
5478 // Make sure that we didn't originally have an incorrect size.
5479 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5480 }
5481 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005482 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005483 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005484 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005485
5486 if (kIsDebugBuild) {
5487 // Make sure that the fields array is ordered by name but all reference
5488 // offsets are at the beginning as far as alignment allows.
5489 MemberOffset start_ref_offset = is_static
5490 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5491 : klass->GetFirstReferenceInstanceFieldOffset();
5492 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5493 num_reference_fields *
5494 sizeof(mirror::HeapReference<mirror::Object>));
5495 MemberOffset current_ref_offset = start_ref_offset;
5496 for (size_t i = 0; i < num_fields; i++) {
5497 mirror::ArtField* field = fields->Get(i);
5498 if ((false)) { // enable to debug field layout
5499 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5500 << " class=" << PrettyClass(klass.Get())
5501 << " field=" << PrettyField(field)
5502 << " offset="
5503 << field->GetField32(mirror::ArtField::OffsetOffset());
5504 }
5505 if (i != 0) {
5506 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005507 // NOTE: The field names can be the same. This is not possible in the Java language
5508 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5509 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005510 }
5511 Primitive::Type type = field->GetTypeAsPrimitiveType();
5512 bool is_primitive = type != Primitive::kPrimNot;
5513 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5514 strcmp("referent", field->GetName()) == 0) {
5515 is_primitive = true; // We lied above, so we have to expect a lie here.
5516 }
5517 MemberOffset offset = field->GetOffsetDuringLinking();
5518 if (is_primitive) {
5519 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5520 // Shuffled before references.
5521 size_t type_size = Primitive::ComponentSize(type);
5522 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5523 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5524 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5525 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5526 }
5527 } else {
5528 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5529 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5530 sizeof(mirror::HeapReference<mirror::Object>));
5531 }
5532 }
5533 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5534 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005535 return true;
5536}
5537
Vladimir Marko76649e82014-11-10 18:32:59 +00005538// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005539void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005540 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005541 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005542 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005543 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005544 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005545 // Compute reference offsets unless our superclass overflowed.
5546 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5547 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005548 if (num_reference_fields != 0u) {
5549 // All of the fields that contain object references are guaranteed be grouped in memory
5550 // starting at an appropriately aligned address after super class object data.
5551 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5552 sizeof(mirror::HeapReference<mirror::Object>));
5553 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005554 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005555 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005556 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005557 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005558 reference_offsets |= (0xffffffffu << start_bit) &
5559 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005560 }
5561 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005562 }
5563 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005564 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005565}
5566
Mathieu Chartier590fee92013-09-13 13:46:47 -07005567mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005568 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005569 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005570 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005571 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005572 return resolved;
5573 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005574 uint32_t utf16_length;
5575 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005576 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005577 dex_cache->SetResolvedString(string_idx, string);
5578 return string;
5579}
5580
Mathieu Chartier590fee92013-09-13 13:46:47 -07005581mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005582 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005583 StackHandleScope<2> hs(Thread::Current());
5584 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5585 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005586 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5587}
5588
5589mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005590 Handle<mirror::DexCache> dex_cache,
5591 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005592 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005593 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005594 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005595 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005596 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005597 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005598 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005599 // TODO: we used to throw here if resolved's class loader was not the
5600 // boot class loader. This was to permit different classes with the
5601 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005602 dex_cache->SetResolvedType(type_idx, resolved);
5603 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005604 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005605 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005606 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005607 StackHandleScope<1> hs(self);
5608 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005609 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005610 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005611 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005612 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005613 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005614 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005615 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005616 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005617 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005618 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005619 return resolved;
5620}
5621
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005622mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005623 Handle<mirror::DexCache> dex_cache,
5624 Handle<mirror::ClassLoader> class_loader,
5625 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005626 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005627 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005628 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005629 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005630 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005631 return resolved;
5632 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005633 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005634 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005635 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005636 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005637 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005638 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005639 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005640 // Scan using method_idx, this saves string compares but will only hit for matching dex
5641 // caches/files.
5642 switch (type) {
5643 case kDirect: // Fall-through.
5644 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005645 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005646 break;
5647 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005648 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005649 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005650 break;
5651 case kSuper: // Fall-through.
5652 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005653 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005654 break;
5655 default:
5656 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005657 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005658 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005659 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005660 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005661 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005662 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005663 switch (type) {
5664 case kDirect: // Fall-through.
5665 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005666 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005667 break;
5668 case kInterface:
5669 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005670 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005671 break;
5672 case kSuper: // Fall-through.
5673 case kVirtual:
5674 resolved = klass->FindVirtualMethod(name, signature);
5675 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005676 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005677 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005678 // If we found a method, check for incompatible class changes.
5679 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005680 // Be a good citizen and update the dex cache to speed subsequent calls.
5681 dex_cache->SetResolvedMethod(method_idx, resolved);
5682 return resolved;
5683 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005684 // If we had a method, it's an incompatible-class-change error.
5685 if (resolved != nullptr) {
5686 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5687 } else {
5688 // We failed to find the method which means either an access error, an incompatible class
5689 // change, or no such method. First try to find the method among direct and virtual methods.
5690 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5691 const Signature signature = dex_file.GetMethodSignature(method_id);
5692 switch (type) {
5693 case kDirect:
5694 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005695 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005696 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5697 // have had a resolved method before, which triggers the "true" branch above.
5698 break;
5699 case kInterface:
5700 case kVirtual:
5701 case kSuper:
5702 resolved = klass->FindDirectMethod(name, signature);
5703 break;
5704 }
5705
5706 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005707 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005708 if (resolved != nullptr && referrer.Get() != nullptr) {
5709 mirror::Class* methods_class = resolved->GetDeclaringClass();
5710 mirror::Class* referring_class = referrer->GetDeclaringClass();
5711 if (!referring_class->CanAccess(methods_class)) {
5712 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5713 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005714 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005715 } else if (!referring_class->CanAccessMember(methods_class,
5716 resolved->GetAccessFlags())) {
5717 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005718 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005719 }
5720 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005721 if (!exception_generated) {
5722 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5723 // interface methods and throw if we find the method there. If we find nothing, throw a
5724 // NoSuchMethodError.
5725 switch (type) {
5726 case kDirect:
5727 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005728 if (resolved != nullptr) {
5729 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5730 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005731 resolved = klass->FindInterfaceMethod(name, signature);
5732 if (resolved != nullptr) {
5733 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5734 } else {
5735 ThrowNoSuchMethodError(type, klass, name, signature);
5736 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005737 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005738 break;
5739 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005740 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005741 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5742 } else {
5743 resolved = klass->FindVirtualMethod(name, signature);
5744 if (resolved != nullptr) {
5745 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5746 } else {
5747 ThrowNoSuchMethodError(type, klass, name, signature);
5748 }
5749 }
5750 break;
5751 case kSuper:
5752 if (resolved != nullptr) {
5753 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005754 } else {
5755 ThrowNoSuchMethodError(type, klass, name, signature);
5756 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005757 break;
5758 case kVirtual:
5759 if (resolved != nullptr) {
5760 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5761 } else {
5762 resolved = klass->FindInterfaceMethod(name, signature);
5763 if (resolved != nullptr) {
5764 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5765 } else {
5766 ThrowNoSuchMethodError(type, klass, name, signature);
5767 }
5768 }
5769 break;
5770 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005771 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005772 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005773 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005774 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005775 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005776}
5777
Mathieu Chartier590fee92013-09-13 13:46:47 -07005778mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005779 Handle<mirror::DexCache> dex_cache,
5780 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005781 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005782 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005783 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005784 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005785 return resolved;
5786 }
5787 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005788 Thread* const self = Thread::Current();
5789 StackHandleScope<1> hs(self);
5790 Handle<mirror::Class> klass(
5791 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005792 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005793 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005794 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005795 }
5796
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005797 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005798 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005799 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005800 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005801 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005802
Andreas Gampe58a5af82014-07-31 16:23:49 -07005803 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005804 const char* name = dex_file.GetFieldName(field_id);
5805 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5806 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005807 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005808 } else {
5809 resolved = klass->FindInstanceField(name, type);
5810 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005811 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005812 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005813 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005814 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005815 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005816 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005817 return resolved;
5818}
5819
Brian Carlstromea46f952013-07-30 01:26:50 -07005820mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005821 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005822 Handle<mirror::DexCache> dex_cache,
5823 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005824 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005825 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005826 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005827 return resolved;
5828 }
5829 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005830 Thread* self = Thread::Current();
5831 StackHandleScope<1> hs(self);
5832 Handle<mirror::Class> klass(
5833 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005834 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005835 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005836 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005837 }
5838
Ian Rogersdfb325e2013-10-30 01:00:44 -07005839 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5840 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005841 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005842 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005843 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005844 dex_cache->SetResolvedField(field_idx, resolved);
5845 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005846 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005847 }
5848 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005849}
5850
Brian Carlstromea46f952013-07-30 01:26:50 -07005851const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005852 uint32_t* length) {
5853 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5854 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005855 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005856 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005857 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005858}
5859
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005860void ClassLinker::DumpAllClasses(int flags) {
5861 if (dex_cache_image_class_lookup_required_) {
5862 MoveImageClassesToClassTable();
5863 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005864 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5865 // 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 -08005866 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005867 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005868 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005869 for (GcRoot<mirror::Class>& it : class_table_) {
5870 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005871 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005872 }
5873
5874 for (size_t i = 0; i < all_classes.size(); ++i) {
5875 all_classes[i]->DumpClass(std::cerr, flags);
5876 }
5877}
5878
Elliott Hughes956af0f2014-12-11 14:34:28 -08005879static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005880 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005881 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5882 base -= sizeof(void*); // Move backward so that code_offset != 0.
5883 const uint32_t code_offset = sizeof(void*);
5884 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005885}
5886
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005887bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5888 return (entry_point == GetQuickResolutionStub()) ||
5889 (quick_resolution_trampoline_ == entry_point);
5890}
5891
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005892bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5893 return (entry_point == GetQuickToInterpreterBridge()) ||
5894 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5895}
5896
5897bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5898 return (entry_point == GetQuickGenericJniStub()) ||
5899 (quick_generic_jni_trampoline_ == entry_point);
5900}
5901
5902const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5903 return GetQuickGenericJniStub();
5904}
5905
Elliott Hughes956af0f2014-12-11 14:34:28 -08005906void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5907 const void* method_code) const {
5908 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005909 oat_method.LinkMethod(method);
5910 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005911}
5912
5913void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5914 if (!method->IsNative()) {
5915 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005916 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5917 } else {
5918 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005919 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005920 oat_method.LinkMethod(method);
5921 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005922 }
5923}
5924
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005925void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005926 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005927 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005928 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005929 MoveImageClassesToClassTable();
5930 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005931 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005932 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5933 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005934}
5935
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005936size_t ClassLinker::NumLoadedClasses() {
5937 if (dex_cache_image_class_lookup_required_) {
5938 MoveImageClassesToClassTable();
5939 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005940 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005941 // Only return non zygote classes since these are the ones which apps which care about.
5942 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005943}
5944
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005945pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005946 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005947}
5948
5949pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005950 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005951}
5952
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005953void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005954 DCHECK(!init_done_);
5955
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005956 DCHECK(klass != nullptr);
5957 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005958
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005959 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005960 DCHECK(class_roots != nullptr);
5961 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005962 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005963}
5964
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005965const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5966 static const char* class_roots_descriptors[] = {
5967 "Ljava/lang/Class;",
5968 "Ljava/lang/Object;",
5969 "[Ljava/lang/Class;",
5970 "[Ljava/lang/Object;",
5971 "Ljava/lang/String;",
5972 "Ljava/lang/DexCache;",
5973 "Ljava/lang/ref/Reference;",
5974 "Ljava/lang/reflect/ArtField;",
5975 "Ljava/lang/reflect/ArtMethod;",
5976 "Ljava/lang/reflect/Proxy;",
5977 "[Ljava/lang/String;",
5978 "[Ljava/lang/reflect/ArtField;",
5979 "[Ljava/lang/reflect/ArtMethod;",
5980 "Ljava/lang/ClassLoader;",
5981 "Ljava/lang/Throwable;",
5982 "Ljava/lang/ClassNotFoundException;",
5983 "Ljava/lang/StackTraceElement;",
5984 "Z",
5985 "B",
5986 "C",
5987 "D",
5988 "F",
5989 "I",
5990 "J",
5991 "S",
5992 "V",
5993 "[Z",
5994 "[B",
5995 "[C",
5996 "[D",
5997 "[F",
5998 "[I",
5999 "[J",
6000 "[S",
6001 "[Ljava/lang/StackTraceElement;",
6002 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08006003 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
6004 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006005
6006 const char* descriptor = class_roots_descriptors[class_root];
6007 CHECK(descriptor != nullptr);
6008 return descriptor;
6009}
6010
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006011std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
6012 const {
6013 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006014 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006015}
6016
6017bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
6018 const GcRoot<mirror::Class>& b) {
6019 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
6020 return false;
6021 }
6022 std::string temp;
6023 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
6024}
6025
6026std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
6027 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006028 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006029}
6030
6031bool ClassLinker::ClassDescriptorHashEquals::operator()(
6032 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
6033 if (a.Read()->GetClassLoader() != b.second) {
6034 return false;
6035 }
6036 return a.Read()->DescriptorEquals(b.first);
6037}
6038
6039bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
6040 const char* descriptor) {
6041 return a.Read()->DescriptorEquals(descriptor);
6042}
6043
6044std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006045 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006046}
6047
Sebastien Hertz6963e442014-11-26 22:11:27 +01006048bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
6049 // Non-image methods don't use direct code pointer.
6050 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
6051 return false;
6052 }
6053 if (m->IsPrivate()) {
6054 // The method can only be called inside its own oat file. Therefore it won't be called using
6055 // its direct code if the oat file has been compiled in PIC mode.
6056 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
6057 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
6058 const OatFile::OatDexFile* oat_dex_file = class_linker->FindOpenedOatDexFileForDexFile(dex_file);
6059 if (oat_dex_file == nullptr) {
6060 // No oat file: the method has not been compiled.
6061 return false;
6062 }
6063 const OatFile* oat_file = oat_dex_file->GetOatFile();
6064 return oat_file != nullptr && !oat_file->IsPic();
6065 } else {
6066 // The method can be called outside its own oat file. Therefore it won't be called using its
6067 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
6068 ReaderMutexLock mu(Thread::Current(), dex_lock_);
6069 for (const OatFile* oat_file : oat_files_) {
6070 if (!oat_file->IsPic()) {
6071 return true;
6072 }
6073 }
6074 return false;
6075 }
6076}
6077
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006078} // namespace art