blob: 3f37fa09ccefafa71cb0ff69a928e9b64a716e3a [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 {
Andreas Gampef52857f2015-02-18 15:38:57 -0800160 // Sort by gap size, largest first. Secondary sort by starting offset.
161 return lhs.size > rhs.size || (lhs.size == rhs.size && lhs.start_offset < rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700162 }
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);
Jeff Haoc7d11882015-02-03 15:08:39 -0800380 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
381 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700382 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700383 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700384 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700385
386 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700387 Handle<mirror::Class> object_array_string(hs.NewHandle(
388 AllocClass(self, java_lang_Class.Get(),
389 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700390 object_array_string->SetComponentType(java_lang_String.Get());
391 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700392
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700393 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
394 AllocClass(self, java_lang_Class.Get(),
395 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700396 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
397 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700398
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700399 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
400 AllocClass(self, java_lang_Class.Get(),
401 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700402 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
403 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700404
Ian Rogers23435d02012-09-24 11:23:12 -0700405 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
406 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
407 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700408 CHECK_NE(0U, boot_class_path.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800409 for (auto& dex_file : boot_class_path) {
410 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700411 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800412 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700413 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700414
415 // now we can use FindSystemClass
416
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700417 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700418 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
419 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700420
Jeff Hao88474b42013-10-23 16:24:40 -0700421 // Create runtime resolution and imt conflict methods. Also setup the default imt.
422 Runtime* runtime = Runtime::Current();
423 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
424 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700425 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700426 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
427
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700428 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
429 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700430 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Alex Light64ad14d2014-08-19 14:23:13 -0700431 if (!runtime->IsCompiler()) {
432 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700433 quick_resolution_trampoline_ = GetQuickResolutionStub();
434 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
435 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700436 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700437
Mathieu Chartier66f19252012-09-18 08:57:04 -0700438 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700439 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800440 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700441 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700442 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700443 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800444 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700445 std::ostringstream os1, os2;
446 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
447 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
448 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
449 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700450 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800451 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700452 CHECK_EQ(java_lang_String.Get(), String_class);
453 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700454 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455
Ian Rogers23435d02012-09-24 11:23:12 -0700456 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800457 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800458 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459
Ian Rogers98379392014-02-24 16:53:16 -0800460 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800461 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700462
Ian Rogers98379392014-02-24 16:53:16 -0800463 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700464 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700465
Ian Rogers98379392014-02-24 16:53:16 -0800466 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800467 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700468
Ian Rogers98379392014-02-24 16:53:16 -0800469 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700470 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700471
Ian Rogers98379392014-02-24 16:53:16 -0800472 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800473 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700474
Ian Rogers98379392014-02-24 16:53:16 -0800475 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800476 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700477
Ian Rogers98379392014-02-24 16:53:16 -0800478 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800479 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700480
Ian Rogers98379392014-02-24 16:53:16 -0800481 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700482 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700483
Ian Rogers98379392014-02-24 16:53:16 -0800484 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700485 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700486
Ian Rogers23435d02012-09-24 11:23:12 -0700487 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800488 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700489 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800490 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700491 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700492 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
493 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700494 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700495 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700496 array_iftable->SetInterface(0, java_lang_Cloneable);
497 array_iftable->SetInterface(1, java_io_Serializable);
498 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700499
Ian Rogers23435d02012-09-24 11:23:12 -0700500 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700501 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
502 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
503 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
504 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700505 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700506 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800507 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700508 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700509
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700510 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800511 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700512 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700513
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700514 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800515 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700516 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700517
Brian Carlstromf3632832014-05-20 15:36:53 -0700518 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700519 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700520 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700521
Brian Carlstromea46f952013-07-30 01:26:50 -0700522 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700523 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700524 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700525
Brian Carlstromea46f952013-07-30 01:26:50 -0700526 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700527 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700528 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700529
Ian Rogers23435d02012-09-24 11:23:12 -0700530 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700531
Ian Rogers23435d02012-09-24 11:23:12 -0700532 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800533 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700534 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
535
Brian Carlstrom1f870082011-08-23 16:02:11 -0700536 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700537 // finish initializing Reference class
538 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
539 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
540 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
541 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
542 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700543 mirror::Class* java_lang_ref_FinalizerReference =
544 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700545 java_lang_ref_FinalizerReference->SetAccessFlags(
546 java_lang_ref_FinalizerReference->GetAccessFlags() |
547 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700548 mirror::Class* java_lang_ref_PhantomReference =
549 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700550 java_lang_ref_PhantomReference->SetAccessFlags(
551 java_lang_ref_PhantomReference->GetAccessFlags() |
552 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700553 mirror::Class* java_lang_ref_SoftReference =
554 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700555 java_lang_ref_SoftReference->SetAccessFlags(
556 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700557 mirror::Class* java_lang_ref_WeakReference =
558 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559 java_lang_ref_WeakReference->SetAccessFlags(
560 java_lang_ref_WeakReference->GetAccessFlags() |
561 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700562
Ian Rogers23435d02012-09-24 11:23:12 -0700563 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800564 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700565 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700566 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
567
jeffhao8cd6dda2012-02-22 10:15:34 -0800568 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700569 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800570 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800571 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700572 SetClassRoot(kJavaLangClassNotFoundException,
573 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800574 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700575 SetClassRoot(kJavaLangStackTraceElementArrayClass,
576 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800577 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700578
Andreas Gampe76bd8802014-12-10 16:43:58 -0800579 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
580 // initialized.
581 {
582 const DexFile& dex_file = java_lang_Object->GetDexFile();
583 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
584 CHECK(void_string_id != nullptr);
585 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
586 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
587 CHECK(void_type_id != nullptr);
588 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
589 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
590 // as referrer so the used dex cache is core's one.
591 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
592 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
593 self->AssertNoPendingException();
594 }
595
Ian Rogers98379392014-02-24 16:53:16 -0800596 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700597
Brian Carlstroma004aa92012-02-08 18:05:09 -0800598 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700599}
600
Ian Rogers98379392014-02-24 16:53:16 -0800601void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800602 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700603
604 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700605 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700606 // as the types of the field can't be resolved prior to the runtime being
607 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800608 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700609 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800610 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800611
Brian Carlstromea46f952013-07-30 01:26:50 -0700612 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700613 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
614 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700615
Brian Carlstromea46f952013-07-30 01:26:50 -0700616 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700617 CHECK_STREQ(queue->GetName(), "queue");
618 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700619
Brian Carlstromea46f952013-07-30 01:26:50 -0700620 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700621 CHECK_STREQ(queueNext->GetName(), "queueNext");
622 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700623
Brian Carlstromea46f952013-07-30 01:26:50 -0700624 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700625 CHECK_STREQ(referent->GetName(), "referent");
626 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700627
Brian Carlstromea46f952013-07-30 01:26:50 -0700628 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700629 CHECK_STREQ(zombie->GetName(), "zombie");
630 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700631
Brian Carlstroma663ea52011-08-19 23:33:41 -0700632 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700633 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700634 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800635 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700636 CHECK(klass != nullptr);
637 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700638 // note SetClassRoot does additional validation.
639 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700640 }
641
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700642 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700643
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700644 // disable the slow paths in FindClass and CreatePrimitiveClass now
645 // that Object, Class, and Object[] are setup
646 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700647
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800648 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700649}
650
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700651void ClassLinker::RunRootClinits() {
652 Thread* self = Thread::Current();
653 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800654 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700655 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700656 StackHandleScope<1> hs(self);
657 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700658 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700659 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700660 }
661 }
662}
663
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700664bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800665 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000666 const char* oat_cache_filename,
667 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700668 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700669 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800670
Ian Rogers1d54e732013-05-02 21:10:01 -0700671 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800672 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700673 if (heap->GetImageSpace() == nullptr) {
674 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
675 // out of space anyway it might not matter.
676 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
677 "without an image.", dex_filename);
678 return false;
679 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700680 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800681
Brian Carlstrom6449c622014-02-10 23:48:36 -0800682 std::string dex_file_option("--dex-file=");
683 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800684
Brian Carlstrom6449c622014-02-10 23:48:36 -0800685 std::string oat_fd_option("--oat-fd=");
686 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800687
Brian Carlstrom6449c622014-02-10 23:48:36 -0800688 std::string oat_location_option("--oat-location=");
689 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800690
Brian Carlstrom6449c622014-02-10 23:48:36 -0800691 std::vector<std::string> argv;
692 argv.push_back(dex2oat);
693 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800694 argv.push_back("-classpath");
695 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800696 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800697
Ian Rogers8afeb852014-04-02 14:55:49 -0700698 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800699
Jeff Hao4a200f52014-04-01 14:58:49 -0700700 if (!Runtime::Current()->IsVerificationEnabled()) {
701 argv.push_back("--compiler-filter=verify-none");
702 }
703
Alex Light6e183f22014-07-18 14:57:04 -0700704 if (Runtime::Current()->MustRelocateIfPossible()) {
705 argv.push_back("--runtime-arg");
706 argv.push_back("-Xrelocate");
707 } else {
708 argv.push_back("--runtime-arg");
709 argv.push_back("-Xnorelocate");
710 }
711
Brian Carlstrom6449c622014-02-10 23:48:36 -0800712 if (!kIsTargetBuild) {
713 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700714 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700715
Brian Carlstrom6449c622014-02-10 23:48:36 -0800716 argv.push_back(boot_image_option);
717 argv.push_back(dex_file_option);
718 argv.push_back(oat_fd_option);
719 argv.push_back(oat_location_option);
720 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800721 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800722 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700723 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800724
Andreas Gampea696c0a2014-12-10 20:51:45 -0800725 if (!Exec(argv, error_msg)) {
726 // Manually delete the file. Ensures there is no garbage left over if the process unexpectedly
727 // died. Ignore unlink failure, propagate the original error.
728 TEMP_FAILURE_RETRY(unlink(oat_cache_filename));
729 return false;
730 }
731
732 return true;
jeffhao262bf462011-10-20 18:36:32 -0700733}
734
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700735const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700736 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800737 if (kIsDebugBuild) {
738 for (size_t i = 0; i < oat_files_.size(); ++i) {
739 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700740 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800741 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700742 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
743 oat_files_.push_back(oat_file);
744 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800745}
746
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700747OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
748 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700749 OatFile* oat_file = space->ReleaseOatFile();
750 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700751 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700752 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700753}
754
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100755const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800756 const char* dex_location = dex_file.GetLocation().c_str();
757 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100758 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800759}
760
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100761const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
762 const char* dex_location,
763 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700764 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100765 for (const OatFile* oat_file : oat_files_) {
766 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700767
768 if (oat_location != nullptr) {
769 if (oat_file->GetLocation() != oat_location) {
770 continue;
771 }
772 }
773
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700774 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800775 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700776 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100777 if (oat_dex_file != nullptr) {
778 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800779 }
780 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100781 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800782}
783
Calin Juravle621962a2014-09-02 15:53:55 +0100784
785// Loads all multi dex files from the given oat file returning true on success.
786//
787// Parameters:
788// oat_file - the oat file to load from
789// dex_location - the dex location used to generate the oat file
790// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
791// generated - whether or not the oat_file existed before or was just (re)generated
792// error_msgs - any error messages will be appended here
793// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
794static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
795 const char* dex_location,
796 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700797 bool generated,
798 std::vector<std::string>* error_msgs,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800799 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700800 if (oat_file == nullptr) {
801 return false;
802 }
803
804 size_t old_size = dex_files->size(); // To rollback on error.
805
806 bool success = true;
807 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100808 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700809 const char* next_name = next_name_str.c_str();
810
Calin Juravle621962a2014-09-02 15:53:55 +0100811 uint32_t next_location_checksum;
812 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700813 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100814 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
815 // When i=0 the multidex name should be the same as the location name. We already have the
816 // checksum it so we don't need to recompute it.
817 if (dex_location_checksum == nullptr) {
818 next_location_checksum_pointer = nullptr;
819 } else {
820 next_location_checksum = *dex_location_checksum;
821 }
822 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700823 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100824 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700825 }
826
827 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
828
829 if (oat_dex_file == nullptr) {
830 if (i == 0 && generated) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700831 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100832 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700833 oat_file->GetLocation().c_str());
834 error_msgs->push_back(error_msg);
835 }
836 break; // Not found, done.
837 }
838
839 // Checksum test. Test must succeed when generated.
840 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100841 if (next_location_checksum_pointer != nullptr) {
842 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700843 }
844
845 if (success) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800846 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
847 if (dex_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700848 success = false;
849 error_msgs->push_back(error_msg);
850 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800851 dex_files->push_back(std::move(dex_file));
Andreas Gampe833a4852014-05-21 18:46:59 -0700852 }
853 }
854
855 // When we generated the file, we expect success, or something is terribly wrong.
856 CHECK_EQ(false, generated && !success)
857 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100858 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700859 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
860 }
861
862 if (dex_files->size() == old_size) {
863 success = false; // We did not even find classes.dex
864 }
865
866 if (success) {
867 return true;
868 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800869 dex_files->erase(dex_files->begin() + old_size, dex_files->end());
Andreas Gampe833a4852014-05-21 18:46:59 -0700870 return false;
871 }
872}
873
874// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
875// complicates the loading process, as we should not use an iterative loading process, because that
876// would register the oat file and dex files that come before the broken one. Instead, check all
877// multidex ahead of time.
878bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
879 std::vector<std::string>* error_msgs,
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800880 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700881 // 1) Check whether we have an open oat file.
882 // This requires a dex checksum, use the "primary" one.
883 uint32_t dex_location_checksum;
884 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
885 bool have_checksum = true;
886 std::string checksum_error_msg;
887 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100888 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700889 dex_location_checksum_pointer = nullptr;
890 have_checksum = false;
891 }
892
893 bool needs_registering = false;
894
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100895 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
896 dex_location_checksum_pointer);
897 std::unique_ptr<const OatFile> open_oat_file(
898 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700899
900 // 2) If we do not have an open one, maybe there's one on disk already.
901
902 // In case the oat file is not open, we play a locking game here so
903 // that if two different processes race to load and register or generate
904 // (or worse, one tries to open a partial generated file) we will be okay.
905 // This is actually common with apps that use DexClassLoader to work
906 // around the dex method reference limit and that have a background
907 // service running in a separate process.
908 ScopedFlock scoped_flock;
909
910 if (open_oat_file.get() == nullptr) {
911 if (oat_location != nullptr) {
912 // Can only do this if we have a checksum, else error.
913 if (!have_checksum) {
914 error_msgs->push_back(checksum_error_msg);
915 return false;
916 }
917
918 std::string error_msg;
919
920 // We are loading or creating one in the future. Time to set up the file lock.
921 if (!scoped_flock.Init(oat_location, &error_msg)) {
922 error_msgs->push_back(error_msg);
923 return false;
924 }
925
Alex Lighta59dd802014-07-02 16:28:08 -0700926 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700927 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
928 oat_location, &error_msg));
929
930 if (open_oat_file.get() == nullptr) {
931 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
932 dex_location, oat_location, error_msg.c_str());
933 VLOG(class_linker) << compound_msg;
934 error_msgs->push_back(compound_msg);
935 }
936 } else {
937 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100938 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700939 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
940 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100941 kRuntimeISA, error_msgs,
942 &obsolete_file_cleanup_failed));
943 // There's no point in going forward and eventually try to regenerate the
944 // file if we couldn't remove the obsolete one. Mostly likely we will fail
945 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100946 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
947 if (obsolete_file_cleanup_failed) {
948 return false;
949 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700950 }
951 needs_registering = true;
952 }
953
954 // 3) If we have an oat file, check all contained multidex files for our dex_location.
955 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100956 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
957 dex_location_checksum_pointer,
958 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700959 if (success) {
960 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
961 if (needs_registering) {
962 // We opened the oat file, so we must register it.
963 RegisterOatFile(oat_file);
964 }
Alex Light9dcc4572014-08-14 14:16:26 -0700965 // If the file isn't executable we failed patchoat but did manage to get the dex files.
966 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700967 } else {
968 if (needs_registering) {
969 // We opened it, delete it.
970 open_oat_file.reset();
971 } else {
972 open_oat_file.release(); // Do not delete open oat files.
973 }
974 }
975
976 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
977
978 // Need a checksum, fail else.
979 if (!have_checksum) {
980 error_msgs->push_back(checksum_error_msg);
981 return false;
982 }
983
984 // Look in cache location if no oat_location is given.
985 std::string cache_location;
986 if (oat_location == nullptr) {
987 // Use the dalvik cache.
988 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
989 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
990 oat_location = cache_location.c_str();
991 }
992
Alex Light64ad14d2014-08-19 14:23:13 -0700993 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700994 // Definitely need to lock now.
995 if (!scoped_flock.HasFile()) {
996 std::string error_msg;
997 if (!scoped_flock.Init(oat_location, &error_msg)) {
998 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700999 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -07001000 }
1001 }
1002
Alex Light64ad14d2014-08-19 14:23:13 -07001003 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001004 // Create the oat file.
1005 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1006 oat_location, error_msgs));
1007 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001008
1009 // Failed, bail.
1010 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001011 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -07001012 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
1013 std::string error_msg;
1014 if (!DexFile::Open(dex_location, dex_location, &error_msg, dex_files)) {
1015 error_msgs->push_back(error_msg);
1016 }
1017 } else {
1018 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
1019 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001020 return false;
1021 }
1022
1023 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001024 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1025 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001026 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001027 if (success) {
1028 RegisterOatFile(open_oat_file.release());
1029 return true;
1030 } else {
1031 return false;
1032 }
1033}
1034
1035const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1036 uint32_t dex_location_checksum,
1037 const char* oat_location,
1038 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001039 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001040 !Runtime::Current()->IsCompiler(),
1041 error_msg));
1042 if (oat_file.get() == nullptr) {
1043 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1044 error_msg->c_str());
1045 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001046 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001047 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001048 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1049 if (image_space != nullptr) {
1050 const ImageHeader& image_header = image_space->GetImageHeader();
1051 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1052 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1053 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1054 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1055 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1056 actual_image_oat_checksum);
1057 return nullptr;
1058 }
1059
1060 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1061 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1062 if (expected_image_oat_offset != actual_image_oat_offset) {
1063 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1064 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1065 actual_image_oat_offset);
1066 return nullptr;
1067 }
1068 int32_t expected_patch_delta = image_header.GetPatchDelta();
1069 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1070 if (expected_patch_delta != actual_patch_delta) {
1071 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1072 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1073 return nullptr;
1074 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001075 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001076
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001077 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1078 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001079 if (oat_dex_file == nullptr) {
1080 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1081 dex_location);
1082 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001083 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001084 uint32_t expected_dex_checksum = dex_location_checksum;
1085 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1086 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001087 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1088 "found 0x%x", oat_location, expected_dex_checksum,
1089 actual_dex_checksum);
1090 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001091 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001092 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1093 if (dex_file.get() != nullptr) {
1094 return oat_file.release();
1095 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001096 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001097 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001098}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001099
Andreas Gampe833a4852014-05-21 18:46:59 -07001100const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1101 int fd, const char* oat_location,
1102 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001103 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001104 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001105 std::string error_msg;
1106 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001107 CHECK(!error_msg.empty());
1108 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001109 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001110 }
Igor Murashkin46774762014-10-22 11:37:02 -07001111 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001112 !Runtime::Current()->IsCompiler(),
1113 &error_msg));
1114 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001115 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1116 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001117 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001118 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001119 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001120
1121 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001122}
1123
Alex Light6e183f22014-07-18 14:57:04 -07001124bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1125 const InstructionSet instruction_set) {
1126 Runtime* runtime = Runtime::Current();
1127 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001128 if (image_space == nullptr) {
1129 return false;
1130 }
Alex Light6e183f22014-07-18 14:57:04 -07001131 uint32_t image_oat_checksum = 0;
1132 if (instruction_set == kRuntimeISA) {
1133 const ImageHeader& image_header = image_space->GetImageHeader();
1134 image_oat_checksum = image_header.GetOatChecksum();
1135 } else {
1136 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1137 image_space->GetImageLocation().c_str(), instruction_set));
1138 image_oat_checksum = image_header->GetOatChecksum();
1139 }
1140 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1141}
1142
1143bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1144 const InstructionSet instruction_set,
1145 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001146 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001147 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001148 if (image_space == nullptr) {
1149 *error_msg = "No image space for verification against";
1150 return false;
1151 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001152
1153 // If the requested instruction set is the same as the current runtime,
1154 // we can use the checksums directly. If it isn't, we'll have to read the
1155 // image header from the image for the right instruction set.
1156 uint32_t image_oat_checksum = 0;
1157 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001158 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001159 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001160 const ImageHeader& image_header = image_space->GetImageHeader();
1161 image_oat_checksum = image_header.GetOatChecksum();
1162 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001163 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001164 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001165 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001166 image_space->GetImageLocation().c_str(), instruction_set));
1167 image_oat_checksum = image_header->GetOatChecksum();
1168 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001169 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001170 }
1171 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin96e83932014-10-29 19:45:42 -07001172 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1173
1174 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1175 if (!oat_file->IsPic()) {
1176 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1177 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1178 }
Alex Light6e183f22014-07-18 14:57:04 -07001179 if (!ret) {
1180 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1181 oat_file->GetLocation().c_str(),
1182 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1183 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1184 oat_file->GetOatHeader().GetImagePatchDelta(),
1185 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1186 }
1187 return ret;
1188}
1189
1190bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1191 const char* dex_location,
1192 uint32_t dex_location_checksum,
1193 const InstructionSet instruction_set,
1194 std::string* error_msg) {
1195 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1196 return false;
1197 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001198
Brian Carlstromf3632832014-05-20 15:36:53 -07001199 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1200 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001201 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001202 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1203 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001204 for (const OatFile::OatDexFile* oat_dex_file_in : oat_file->GetOatDexFiles()) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001205 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001206 oat_file->GetLocation().c_str(),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001207 oat_dex_file_in->GetDexFileLocation().c_str(),
1208 oat_dex_file_in->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001209 }
1210 return false;
1211 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001212
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001213 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001214 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001215}
1216
Alex Lighta59dd802014-07-02 16:28:08 -07001217bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1218 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001219 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001220 std::string* error_msg) {
1221 CHECK(oat_file != nullptr);
1222 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001223 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001224 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001225 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1226 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1227 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001228 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001229 if (oat_dex_file == nullptr) {
1230 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001231 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001232 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001233 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001234 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001235 dex_file = oat_dex_file->OpenDexFile(error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001236 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001237 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001238 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001239 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001240 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001241 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001242 dex_file = oat_file->GetOatDexFile(dex_location,
1243 dex_location_checksum)->OpenDexFile(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001244 }
Alex Lighta59dd802014-07-02 16:28:08 -07001245 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001246}
1247
Andreas Gampe833a4852014-05-21 18:46:59 -07001248const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001249 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001250 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001251 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001252 std::vector<std::string>* error_msgs,
1253 bool* obsolete_file_cleanup_failed) {
1254 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001255 bool already_opened = false;
1256 std::string dex_location_str(dex_location);
1257 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1258 &already_opened,
1259 obsolete_file_cleanup_failed,
1260 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001261 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001262 if (oat_file.get() == nullptr) {
1263 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1264 dex_location));
1265 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001266 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001267 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1268 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001269 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1270 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001271 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001272 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001273 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001274 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001275 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1276 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1277 "dex location '%s'. Image checksum incorrect.",
1278 oat_file->GetLocation().c_str(), dex_location));
1279 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001280 } else {
1281 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001282 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001283}
1284
Brian Carlstromae826982011-11-09 01:33:42 -08001285const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001286 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001287 for (size_t i = 0; i < oat_files_.size(); i++) {
1288 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001289 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001290 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001291 return oat_file;
1292 }
1293 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001294 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001295}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001296
Alex Lighta59dd802014-07-02 16:28:08 -07001297const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1298 InstructionSet isa,
1299 bool *already_opened,
1300 bool *obsolete_file_cleanup_failed,
1301 std::vector<std::string>* error_msgs) {
1302 // Find out if we've already opened the file
1303 const OatFile* ret = nullptr;
1304 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1305 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1306 if (ret != nullptr) {
1307 *already_opened = true;
1308 return ret;
1309 }
1310
1311 std::string dalvik_cache;
1312 bool have_android_data = false;
1313 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001314 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001315 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001316 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001317 std::string cache_filename;
1318 if (have_dalvik_cache) {
1319 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1320 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1321 if (ret != nullptr) {
1322 *already_opened = true;
1323 return ret;
1324 }
1325 } else {
1326 // If we need to relocate we should just place odex back where it started.
1327 cache_filename = odex_filename;
1328 }
1329
1330 ret = nullptr;
1331
1332 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1333 //
1334 // Now we do the following:
1335 // 1) Try and open the odex version
1336 // 2) If present, checksum-verified & relocated correctly return it
1337 // 3) Close the odex version to free up its address space.
1338 // 4) Try and open the cache version
1339 // 5) If present, checksum-verified & relocated correctly return it
1340 // 6) Close the cache version to free up its address space.
1341 // 7) If we should relocate:
1342 // a) If we have opened and checksum-verified the odex version relocate it to
1343 // 'cache_filename' and return it
1344 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1345 // it. This should not happen often (I think only the run-test's will hit this case).
1346 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1347 // this point.
1348 // 9) Return nullptr
1349
1350 *already_opened = false;
1351 const Runtime* runtime = Runtime::Current();
1352 CHECK(runtime != nullptr);
1353 bool executable = !runtime->IsCompiler();
1354
1355 std::string odex_error_msg;
1356 bool should_patch_system = false;
1357 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001358 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001359 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001360 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001361 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001362 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001363 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001364 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001365 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001366 &odex_checksum_verified,
1367 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001368 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001369 } else {
1370 if (odex_checksum_verified) {
1371 // We can just relocate
1372 should_patch_system = true;
1373 odex_error_msg = "Image Patches are incorrect";
1374 }
1375 if (odex_oat_file.get() != nullptr) {
1376 have_system_odex = true;
1377 }
Alex Lighta59dd802014-07-02 16:28:08 -07001378 }
1379 }
1380
Alex Lighta59dd802014-07-02 16:28:08 -07001381 std::string cache_error_msg;
1382 bool should_patch_cache = false;
1383 bool cache_checksum_verified = false;
1384 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001385 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001386 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001387 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001388 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001389 &cache_checksum_verified,
1390 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001391 return cache_oat_file.release();
1392 } else if (cache_checksum_verified) {
1393 // We can just relocate
1394 should_patch_cache = true;
1395 cache_error_msg = "Image Patches are incorrect";
1396 }
1397 } else if (have_android_data) {
1398 // dalvik_cache does not exist but android data does. This means we should be able to create
1399 // it, so we should try.
1400 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1401 }
1402
1403 ret = nullptr;
1404 std::string error_msg;
1405 if (runtime->CanRelocate()) {
1406 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001407 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1408 if (space != nullptr) {
1409 const std::string& image_location = space->GetImageLocation();
1410 if (odex_checksum_verified && should_patch_system) {
1411 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1412 } else if (cache_checksum_verified && should_patch_cache) {
1413 CHECK(have_dalvik_cache);
1414 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1415 }
Alex Light84d76052014-08-22 17:49:35 -07001416 } else if (have_system_odex) {
1417 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001418 }
1419 }
1420 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1421 // implicitly: were able to fine where the cached version is but we were unable to use it,
1422 // either as a destination for relocation or to open a file. We should delete it if it is
1423 // there.
1424 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1425 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1426 "searching for dex file %s: %s",
1427 cache_filename.c_str(), dex_location.c_str(),
1428 strerror(errno));
1429 error_msgs->push_back(rm_error_msg);
1430 VLOG(class_linker) << rm_error_msg;
1431 // Let the caller know that we couldn't remove the obsolete file.
1432 // This is a good indication that further writes may fail as well.
1433 *obsolete_file_cleanup_failed = true;
1434 }
1435 }
1436 if (ret == nullptr) {
1437 VLOG(class_linker) << error_msg;
1438 error_msgs->push_back(error_msg);
1439 std::string relocation_msg;
1440 if (runtime->CanRelocate()) {
1441 relocation_msg = StringPrintf(" and relocation failed");
1442 }
1443 if (have_dalvik_cache && cache_checksum_verified) {
1444 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1445 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1446 cache_filename.c_str(), cache_error_msg.c_str(),
1447 relocation_msg.c_str());
1448 } else {
1449 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1450 "dalvik_cache availible)%s.", odex_filename.c_str(),
1451 odex_error_msg.c_str(), relocation_msg.c_str());
1452 }
1453 VLOG(class_linker) << error_msg;
1454 error_msgs->push_back(error_msg);
1455 }
1456 return ret;
1457}
1458
Alex Light9dcc4572014-08-14 14:16:26 -07001459const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1460 InstructionSet isa,
1461 std::string* error_msg) {
1462 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001463 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001464 if (output.get() == nullptr) {
1465 return nullptr;
1466 }
Alex Light84d76052014-08-22 17:49:35 -07001467 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1468 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001469 return output.release();
1470 } else {
1471 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1472 oat_path.c_str());
1473 return nullptr;
1474 }
1475}
1476
Alex Lighta59dd802014-07-02 16:28:08 -07001477const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1478 const std::string& output_oat,
1479 const std::string& image_location,
1480 InstructionSet isa,
1481 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001482 Runtime* runtime = Runtime::Current();
1483 DCHECK(runtime != nullptr);
1484 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001485 // We don't have an image space so there is no point in trying to patchoat.
1486 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1487 << "running without an image. Attempting to use oat file for interpretation.";
1488 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1489 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001490 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001491 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1492 // input_oat but make sure we only do interpretation on it's dex files.
1493 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1494 << "disabled. Attempting to use oat file for interpretation";
1495 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1496 }
Alex Lighta59dd802014-07-02 16:28:08 -07001497 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001498 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001499
1500 std::string isa_arg("--instruction-set=");
1501 isa_arg += GetInstructionSetString(isa);
1502 std::string input_oat_filename_arg("--input-oat-file=");
1503 input_oat_filename_arg += input_oat;
1504 std::string output_oat_filename_arg("--output-oat-file=");
1505 output_oat_filename_arg += output_oat;
1506 std::string patched_image_arg("--patched-image-location=");
1507 patched_image_arg += image_location;
1508
1509 std::vector<std::string> argv;
1510 argv.push_back(patchoat);
1511 argv.push_back(isa_arg);
1512 argv.push_back(input_oat_filename_arg);
1513 argv.push_back(output_oat_filename_arg);
1514 argv.push_back(patched_image_arg);
1515
1516 std::string command_line(Join(argv, ' '));
1517 LOG(INFO) << "Relocate Oat File: " << command_line;
1518 bool success = Exec(argv, error_msg);
1519 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001520 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gampe7ba64962014-10-23 11:37:40 -07001521 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001522 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001523 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1524 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001525 return output.release();
1526 } else if (output.get() != nullptr) {
1527 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1528 "but output file '%s' failed verifcation: %s",
1529 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1530 } else {
1531 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1532 "but was unable to open output file '%s': %s",
1533 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1534 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001535 } else if (!runtime->IsCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001536 // patchoat failed which means we probably don't have enough room to place the output oat file,
1537 // instead of failing we should just run the interpreter from the dex files in the input oat.
1538 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1539 << "for interpretation. patchoat failure was: " << *error_msg;
1540 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001541 } else {
1542 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1543 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1544 error_msg->c_str());
1545 }
1546 return nullptr;
1547}
1548
Andreas Gampe7ba64962014-10-23 11:37:40 -07001549bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001550 bool* checksum_verified,
1551 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001552 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001553 if (image_space == nullptr) {
1554 *error_msg = "No image space present";
1555 return false;
1556 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001557 uint32_t real_image_checksum;
1558 void* real_image_oat_offset;
1559 int32_t real_patch_delta;
1560 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001561 const ImageHeader& image_header = image_space->GetImageHeader();
1562 real_image_checksum = image_header.GetOatChecksum();
1563 real_image_oat_offset = image_header.GetOatDataBegin();
1564 real_patch_delta = image_header.GetPatchDelta();
1565 } else {
1566 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1567 image_space->GetImageLocation().c_str(), isa));
1568 real_image_checksum = image_header->GetOatChecksum();
1569 real_image_oat_offset = image_header->GetOatDataBegin();
1570 real_patch_delta = image_header->GetPatchDelta();
1571 }
1572
1573 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001574 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001575
1576 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1577 *checksum_verified = oat_image_checksum == real_image_checksum;
1578 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001579 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1580 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001581 }
1582
Andreas Gampe7ba64962014-10-23 11:37:40 -07001583 bool offset_verified;
1584 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001585
Andreas Gampe7ba64962014-10-23 11:37:40 -07001586 if (!oat_file->IsPic()) {
1587 // If an oat file is not PIC, we need to check that the image is at the expected location and
1588 // patched in the same way.
1589 void* oat_image_oat_offset =
1590 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1591 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1592 if (!offset_verified) {
1593 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1594 real_image_oat_offset, oat_image_oat_offset);
1595 }
1596
1597 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1598 patch_delta_verified = oat_patch_delta == real_patch_delta;
1599 if (!patch_delta_verified) {
1600 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1601 "received 0x%x)", real_patch_delta, oat_patch_delta);
1602 }
1603 } else {
1604 // If an oat file is PIC, we ignore offset and patching delta.
1605 offset_verified = true;
1606 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001607 }
1608
1609 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001610 if (!ret) {
1611 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001612 }
1613 return ret;
1614}
1615
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001616const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1617 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001618 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001619 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001620 return oat_file;
1621 }
1622
Igor Murashkin46774762014-10-22 11:37:02 -07001623 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001624 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001625}
1626
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001627void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001628 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001629 DCHECK(obj != nullptr);
1630 DCHECK(class_linker != nullptr);
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001631 size_t pointer_size = class_linker->image_pointer_size_;
Ian Rogers848871b2013-08-05 10:56:33 -07001632
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001633 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001634 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001635 if (!method->IsNative()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001636 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001637 if (method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001638 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1639 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001640 }
1641 }
1642 }
1643}
1644
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001645void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001646 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001647 CHECK(!init_done_);
1648
Mathieu Chartier590fee92013-09-13 13:46:47 -07001649 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001650 gc::Heap* heap = Runtime::Current()->GetHeap();
1651 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001652 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001653 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001654 OatFile& oat_file = GetImageOatFile(space);
1655 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1656 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001657 const char* image_file_location = oat_file.GetOatHeader().
1658 GetStoreValueByKey(OatHeader::kImageLocationKey);
1659 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001660 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001661 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001662 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001663 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001664 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1665 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1666 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001667
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001668 StackHandleScope<1> hs(self);
1669 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1670 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1671 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001672 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001673
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001674 // Special case of setting up the String class early so that we can test arbitrary objects
1675 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001676 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001677
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001678 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001679 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001680 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001681 StackHandleScope<1> hs2(self);
1682 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001683 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001684 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1685 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001686 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001687 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001688 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
1689 if (dex_file.get() == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001690 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001691 << " from within oat file " << oat_file.GetLocation()
1692 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -08001693 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001694 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001695
1696 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1697
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001698 AppendToBootClassPath(*dex_file.get(), dex_cache);
1699 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001700 }
1701
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001702 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1703 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001704 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001705 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
1706 if (!Runtime::Current()->IsCompiler()) {
1707 // Compiler supports having an image with a different pointer size than the runtime. This
1708 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
1709 // also use 32 bit dex2oat on a system with 64 bit apps.
1710 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
1711 << sizeof(void*);
1712 }
1713 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
1714 image_pointer_size_ = 4;
1715 } else {
1716 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
1717 image_pointer_size_ = 8;
1718 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001719
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001720 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001721 Runtime* runtime = Runtime::Current();
1722 if (!runtime->IsCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001723 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001724 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001725
1726 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001727 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001728 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001729
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001730 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001731 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001732 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001733 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001734 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001735 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001736 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1737 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1738 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1739 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1740 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1741 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1742 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1743 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1744 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1745 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001746
Ian Rogers98379392014-02-24 16:53:16 -08001747 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001748
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001749 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001750}
1751
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001752void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1753 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1754 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001755 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001756 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001757 }
1758 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001759 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001760 }
1761 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001762 for (auto& root : new_class_roots_) {
1763 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001764 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001765 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001766 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001767 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1768 // corresponding object. This is slow, but luckily for us, this may only happen with a
1769 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001770 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001771 DCHECK(it != class_table_.end());
1772 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001773 }
1774 }
1775 }
1776 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1777 new_class_roots_.clear();
1778 }
1779 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1780 log_new_class_table_roots_ = true;
1781 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1782 log_new_class_table_roots_ = false;
1783 }
1784 // We deliberately ignore the class roots in the image since we
1785 // handle image roots by using the MS/CMS rescanning of dirty cards.
1786}
1787
Brian Carlstroma663ea52011-08-19 23:33:41 -07001788// Keep in sync with InitCallback. Anything we visit, we need to
1789// reinit references to when reinitializing a ClassLinker from a
1790// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001791void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001792 class_roots_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers50b35e22012-10-04 10:09:15 -07001793 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001794 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001795 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001796 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001797 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001798 dex_cache.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001799 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001800 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1801 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001802 dex_caches_[index].VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001803 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001804 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001805 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1806 new_dex_cache_roots_.clear();
1807 }
1808 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1809 log_new_dex_caches_roots_ = true;
1810 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1811 log_new_dex_caches_roots_ = false;
1812 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001813 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001814 VisitClassRoots(callback, arg, flags);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001815 array_iftable_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001816 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001817 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001818 find_array_class_cache_[i].VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001819 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001820}
1821
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001822void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1823 if (dex_cache_image_class_lookup_required_) {
1824 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001825 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001826 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001827 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001828 for (GcRoot<mirror::Class>& root : class_table_) {
1829 if (!visitor(root.Read(), arg)) {
1830 return;
1831 }
1832 }
1833 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1834 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001835 return;
1836 }
1837 }
1838}
1839
Ian Rogersdbf3be02014-08-29 15:40:08 -07001840static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001841 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001842 classes->insert(c);
1843 return true;
1844}
1845
Ian Rogersdbf3be02014-08-29 15:40:08 -07001846struct GetClassesVisitorArrayArg {
1847 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1848 int32_t index;
1849 bool success;
1850};
1851
1852static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1853 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1854 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1855 if (arg->index < (*arg->classes)->GetLength()) {
1856 (*arg->classes)->Set(arg->index, c);
1857 arg->index++;
1858 return true;
1859 } else {
1860 arg->success = false;
1861 return false;
1862 }
1863}
1864
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001865void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001866 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1867 // is avoiding duplicates.
1868 if (!kMovingClasses) {
1869 std::set<mirror::Class*> classes;
1870 VisitClasses(GetClassesVisitorSet, &classes);
1871 for (mirror::Class* klass : classes) {
1872 if (!visitor(klass, arg)) {
1873 return;
1874 }
1875 }
1876 } else {
1877 Thread* self = Thread::Current();
1878 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001879 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001880 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1881 GetClassesVisitorArrayArg local_arg;
1882 local_arg.classes = &classes;
1883 local_arg.success = false;
1884 // We size the array assuming classes won't be added to the class table during the visit.
1885 // If this assumption fails we iterate again.
1886 while (!local_arg.success) {
1887 size_t class_table_size;
1888 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001889 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001890 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001891 }
1892 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1893 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1894 classes.Assign(
1895 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1896 CHECK(classes.Get() != nullptr); // OOME.
1897 local_arg.index = 0;
1898 local_arg.success = true;
1899 VisitClasses(GetClassesVisitorArray, &local_arg);
1900 }
1901 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1902 // If the class table shrank during creation of the clases array we expect null elements. If
1903 // the class table grew then the loop repeats. If classes are created after the loop has
1904 // finished then we don't visit.
1905 mirror::Class* klass = classes->Get(i);
1906 if (klass != nullptr && !visitor(klass, arg)) {
1907 return;
1908 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001909 }
1910 }
1911}
1912
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001913ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001914 mirror::Class::ResetClass();
1915 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001916 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001917 mirror::ArtField::ResetClass();
1918 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001919 mirror::BooleanArray::ResetArrayClass();
1920 mirror::ByteArray::ResetArrayClass();
1921 mirror::CharArray::ResetArrayClass();
1922 mirror::DoubleArray::ResetArrayClass();
1923 mirror::FloatArray::ResetArrayClass();
1924 mirror::IntArray::ResetArrayClass();
1925 mirror::LongArray::ResetArrayClass();
1926 mirror::ShortArray::ResetArrayClass();
1927 mirror::Throwable::ResetClass();
1928 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001929 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001930}
1931
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001932mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001933 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001934 StackHandleScope<16> hs(self);
1935 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1936 Handle<mirror::DexCache> dex_cache(
1937 hs.NewHandle(down_cast<mirror::DexCache*>(
1938 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1939 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001940 if (dex_cache.Get() == nullptr) {
1941 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001942 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001943 Handle<mirror::String>
1944 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001945 if (location.Get() == nullptr) {
1946 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001947 }
Ian Rogers700a4022014-05-19 16:49:03 -07001948 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001949 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001950 if (strings.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::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001954 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001955 if (types.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::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001959 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001960 if (methods.Get() == nullptr) {
1961 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001962 }
Ian Rogers700a4022014-05-19 16:49:03 -07001963 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001964 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001965 if (fields.Get() == nullptr) {
1966 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001967 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001968 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1969 fields.Get());
1970 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001971}
1972
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001973mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001974 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001975 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001976 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001977 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001978 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001979 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1980 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001981 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001982 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001983 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001984 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001985 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001986}
1987
Ian Rogers6fac4472014-02-25 17:01:10 -08001988mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001989 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001990}
1991
Brian Carlstromea46f952013-07-30 01:26:50 -07001992mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001993 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001994 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001995}
1996
Brian Carlstromea46f952013-07-30 01:26:50 -07001997mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001998 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001999 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002000}
2001
Mathieu Chartier590fee92013-09-13 13:46:47 -07002002mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
2003 Thread* self, size_t length) {
2004 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2005 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002006}
2007
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002008mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
2009 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002010 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002011
2012 // For temporary classes we must wait for them to be retired.
2013 if (init_done_ && klass->IsTemp()) {
2014 CHECK(!klass->IsResolved());
2015 if (klass->IsErroneous()) {
2016 ThrowEarlierClassFailure(klass);
2017 return nullptr;
2018 }
2019 StackHandleScope<1> hs(self);
2020 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2021 ObjectLock<mirror::Class> lock(self, h_class);
2022 // Loop and wait for the resolving thread to retire this class.
2023 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2024 lock.WaitIgnoringInterrupts();
2025 }
2026 if (h_class->IsErroneous()) {
2027 ThrowEarlierClassFailure(h_class.Get());
2028 return nullptr;
2029 }
2030 CHECK(h_class->IsRetired());
2031 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002032 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2033 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002034 }
2035
Brian Carlstromaded5f72011-10-07 17:15:04 -07002036 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002037 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002038 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002039 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2040 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002041 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002042 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2043 ThrowClassCircularityError(h_class.Get());
2044 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002045 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002046 }
2047 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002048 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002049 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002050 }
2051 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002052
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002053 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002054 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002055 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002056 }
2057 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002058 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002059 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002060 return klass;
2061}
2062
Ian Rogers68b56852014-08-29 20:19:11 -07002063typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2064
2065// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002066ClassPathEntry FindInClassPath(const char* descriptor,
2067 size_t hash, const std::vector<const DexFile*>& class_path) {
2068 for (const DexFile* dex_file : class_path) {
2069 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002070 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002071 return ClassPathEntry(dex_file, dex_class_def);
2072 }
2073 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002074 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002075}
2076
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002077mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2078 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002079 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002080 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08002081 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002082 if (class_loader->GetClass() !=
2083 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2084 class_loader->GetParent()->GetClass() !=
2085 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2086 return nullptr;
2087 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002088 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002089 // Check if this would be found in the parent boot class loader.
2090 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002091 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002092 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08002093 // May return null if resolution on another thread fails.
2094 klass = EnsureResolved(self, descriptor, klass);
2095 } else {
2096 // May OOME.
2097 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2098 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002099 }
Ian Rogers32427292014-11-19 14:05:21 -08002100 if (klass == nullptr) {
2101 CHECK(self->IsExceptionPending()) << descriptor;
2102 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002103 }
Ian Rogers32427292014-11-19 14:05:21 -08002104 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002105 } else {
Ian Rogers32427292014-11-19 14:05:21 -08002106 // Handle as if this is the child PathClassLoader.
2107 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002108 StackHandleScope<3> hs(self);
2109 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2110 // We need to get the DexPathList and loop through it.
2111 Handle<mirror::ArtField> cookie_field =
2112 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2113 Handle<mirror::ArtField> dex_file_field =
2114 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002115 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002116 mirror::Object* dex_path_list =
2117 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2118 GetObject(class_loader.Get());
2119 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2120 cookie_field.Get() != nullptr) {
2121 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2122 mirror::Object* dex_elements_obj =
2123 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2124 GetObject(dex_path_list);
2125 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2126 // at the mCookie which is a DexFile vector.
2127 if (dex_elements_obj != nullptr) {
2128 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2129 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2130 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2131 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2132 if (element == nullptr) {
2133 // Should never happen, fall back to java code to throw a NPE.
2134 break;
2135 }
2136 mirror::Object* dex_file = dex_file_field->GetObject(element);
2137 if (dex_file != nullptr) {
Andreas Gampe324b9bb2015-02-23 16:33:22 -08002138 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
2139 if (long_array == nullptr) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002140 // This should never happen so log a warning.
2141 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2142 break;
2143 }
Andreas Gampe324b9bb2015-02-23 16:33:22 -08002144 int32_t long_array_size = long_array->GetLength();
2145 for (int32_t j = 0; j < long_array_size; ++j) {
2146 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
2147 long_array->GetWithoutChecks(j)));
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002148 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002149 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002150 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002151 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2152 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002153 if (klass == nullptr) {
2154 CHECK(self->IsExceptionPending()) << descriptor;
2155 self->ClearException();
2156 return nullptr;
2157 }
2158 return klass;
2159 }
2160 }
2161 }
2162 }
2163 }
2164 }
Ian Rogers32427292014-11-19 14:05:21 -08002165 self->AssertNoPendingException();
2166 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002167 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002168}
2169
Ian Rogers98379392014-02-24 16:53:16 -08002170mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002171 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002172 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002173 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002174 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002175 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002176 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2177 // for primitive classes that aren't backed by dex files.
2178 return FindPrimitiveClass(descriptor[0]);
2179 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002180 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002181 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002182 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002183 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002184 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002185 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002186 // Class is not yet loaded.
2187 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002188 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002189 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002190 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002191 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002192 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002193 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002194 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002195 } else {
2196 // The boot class loader is searched ahead of the application class loader, failures are
2197 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2198 // trigger the chaining with a proper stack trace.
2199 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2200 self->SetException(ThrowLocation(), pre_allocated);
2201 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002202 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002203 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002204 // First try with the bootstrap class loader.
2205 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002206 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002207 if (klass != nullptr) {
2208 return EnsureResolved(self, descriptor, klass);
2209 }
2210 }
Ian Rogers63557452014-06-04 16:57:15 -07002211 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2212 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002213 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002214 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002215 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002216 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002217 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002218 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002219 const std::vector<const DexFile*>* class_path;
2220 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002221 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002222 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002223 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002224 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2225 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002226 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07002227 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002228 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07002229 } else {
2230 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2231 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2232 self->SetException(ThrowLocation(), pre_allocated);
2233 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002234 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002235 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002236 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002237 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2238 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002239 if (cp_klass != nullptr) {
2240 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002241 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002242 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002243 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002244 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002245 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002246 {
2247 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002248 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2249 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002250 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002251 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002252 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002253 }
Ian Rogers68b56852014-08-29 20:19:11 -07002254 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002255 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2256 WellKnownClasses::java_lang_ClassLoader_loadClass,
2257 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002258 }
Ian Rogers98379392014-02-24 16:53:16 -08002259 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002260 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002261 return nullptr;
2262 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002263 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002264 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002265 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002266 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002267 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002268 // success, return mirror::Class*
2269 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002270 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002271 }
Ian Rogers07140832014-09-30 15:43:59 -07002272 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002273}
2274
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002275mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002276 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002277 const DexFile& dex_file,
2278 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002279 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002280 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002281
Brian Carlstromaded5f72011-10-07 17:15:04 -07002282 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002283 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002284 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002285 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002286 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002287 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002288 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002289 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002290 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002291 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2292 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002293 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002294 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002295 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002296 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002297 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002298 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002299 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002300 }
2301
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002302 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002303 // Allocate a class with the status of not ready.
2304 // Interface object should get the right size here. Regular class will
2305 // figure out the right size later and be replaced with one of the right
2306 // size when the class becomes resolved.
2307 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002308 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002309 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002310 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002311 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002312 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002313 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002314 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002315 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002316 if (self->IsExceptionPending()) {
2317 // An exception occured during load, set status to erroneous while holding klass' lock in case
2318 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002319 if (!klass->IsErroneous()) {
2320 klass->SetStatus(mirror::Class::kStatusError, self);
2321 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002322 return nullptr;
2323 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002324 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002325
Mathieu Chartier590fee92013-09-13 13:46:47 -07002326 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002327 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002328 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002329 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2330 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002331 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002332 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002333
Brian Carlstromaded5f72011-10-07 17:15:04 -07002334 // Finish loading (if necessary) by finding parents
2335 CHECK(!klass->IsLoaded());
2336 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2337 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002338 if (!klass->IsErroneous()) {
2339 klass->SetStatus(mirror::Class::kStatusError, self);
2340 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002341 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002342 }
2343 CHECK(klass->IsLoaded());
2344 // Link the class (if necessary)
2345 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002346 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002347 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002348
2349 mirror::Class* new_class = nullptr;
2350 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002351 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002352 if (!klass->IsErroneous()) {
2353 klass->SetStatus(mirror::Class::kStatusError, self);
2354 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002355 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002356 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002357 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002358 CHECK(new_class != nullptr) << descriptor;
2359 CHECK(new_class->IsResolved()) << descriptor;
2360
2361 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002362
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002363 // Instrumentation may have updated entrypoints for all methods of all
2364 // classes. However it could not update methods of this class while we
2365 // were loading it. Now the class is resolved, we can update entrypoints
2366 // as required by instrumentation.
2367 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2368 // We must be in the kRunnable state to prevent instrumentation from
2369 // suspending all threads to update entrypoints while we are doing it
2370 // for this class.
2371 DCHECK_EQ(self->GetState(), kRunnable);
2372 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(new_class_h.Get());
2373 }
2374
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002375 /*
2376 * We send CLASS_PREPARE events to the debugger from here. The
2377 * definition of "preparation" is creating the static fields for a
2378 * class and initializing them to the standard default values, but not
2379 * executing any code (that comes later, during "initialization").
2380 *
2381 * We did the static preparation in LinkClass.
2382 *
2383 * The class has been prepared and resolved but possibly not yet verified
2384 * at this point.
2385 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002386 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002387
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002388 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002389}
2390
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002391uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2392 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002393 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002394 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002395 size_t num_8 = 0;
2396 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002397 size_t num_32 = 0;
2398 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002399 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002400 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2401 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002402 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002403 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002404 switch (c) {
2405 case 'L':
2406 case '[':
2407 num_ref++;
2408 break;
2409 case 'J':
2410 case 'D':
2411 num_64++;
2412 break;
2413 case 'I':
2414 case 'F':
2415 num_32++;
2416 break;
2417 case 'S':
2418 case 'C':
2419 num_16++;
2420 break;
2421 case 'B':
2422 case 'Z':
2423 num_8++;
2424 break;
2425 default:
2426 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002427 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002428 }
2429 }
2430 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002431 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002432}
2433
Ian Rogers97b52f82014-08-14 11:34:07 -07002434OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2435 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002436 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002437 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2438 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002439 *found = false;
2440 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002441 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002442 *found = true;
2443 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002444}
2445
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002446static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2447 uint32_t method_idx) {
2448 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002449 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002450 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002451 ClassDataItemIterator it(dex_file, class_data);
2452 // Skip fields
2453 while (it.HasNextStaticField()) {
2454 it.Next();
2455 }
2456 while (it.HasNextInstanceField()) {
2457 it.Next();
2458 }
2459 // Process methods
2460 size_t class_def_method_index = 0;
2461 while (it.HasNextDirectMethod()) {
2462 if (it.GetMemberIndex() == method_idx) {
2463 return class_def_method_index;
2464 }
2465 class_def_method_index++;
2466 it.Next();
2467 }
2468 while (it.HasNextVirtualMethod()) {
2469 if (it.GetMemberIndex() == method_idx) {
2470 return class_def_method_index;
2471 }
2472 class_def_method_index++;
2473 it.Next();
2474 }
2475 DCHECK(!it.HasNext());
2476 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08002477 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002478}
2479
Ian Rogers97b52f82014-08-14 11:34:07 -07002480const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002481 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002482 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002483 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002484 size_t oat_method_index;
2485 if (method->IsStatic() || method->IsDirect()) {
2486 // Simple case where the oat method index was stashed at load time.
2487 oat_method_index = method->GetMethodIndex();
2488 } else {
2489 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2490 // by search for its position in the declared virtual methods.
2491 oat_method_index = declaring_class->NumDirectMethods();
2492 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002493 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002494 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002495 // Check method index instead of identity in case of duplicate method definitions.
2496 if (method->GetDexMethodIndex() ==
2497 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002498 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002499 break;
2500 }
Ian Rogersf320b632012-03-13 18:47:47 -07002501 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002502 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002503 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2504 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002505 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002506 DCHECK_EQ(oat_method_index,
2507 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002508 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002509 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002510 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2511 declaring_class->GetDexClassDefIndex(),
2512 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002513 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002514 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002515 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002516 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002517}
2518
2519// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002520const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002521 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002522 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002523 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002524 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002525 bool found;
2526 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002527 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002528 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002529 result = oat_method.GetQuickCode();
2530 }
2531
Ian Rogersef7d42f2014-01-06 12:55:46 -08002532 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002533 if (method->IsNative()) {
2534 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002535 result = GetQuickGenericJniStub();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002536 } else {
2537 // No code? You must mean to go into the interpreter.
2538 result = GetQuickToInterpreterBridge();
2539 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002540 }
2541 return result;
TDYa12785321912012-04-01 15:24:56 -07002542}
2543
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002544const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2545 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2546 return nullptr;
2547 }
2548 bool found;
2549 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2550 return found ? oat_method.GetQuickCode() : nullptr;
2551}
2552
Ian Rogersef7d42f2014-01-06 12:55:46 -08002553const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2554 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002555 bool found;
2556 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2557 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002558 return nullptr;
2559 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002560 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002561 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002562}
2563
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002564// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08002565static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07002566 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08002567 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002568 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002569 // May return true for native code, in the case of generic JNI
2570 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002571 return true;
2572 }
2573 // If interpreter mode is enabled, every method (except native and proxy) must
2574 // be run with interpreter.
2575 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2576 !method->IsNative() && !method->IsProxyMethod();
2577}
2578
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002579void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002580 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002581 if (klass->NumDirectMethods() == 0) {
2582 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002583 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002584 Runtime* runtime = Runtime::Current();
2585 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002586 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2587 return; // OAT file unavailable.
2588 }
Ian Rogers19846512012-02-24 11:42:47 -08002589 }
Alex Light64ad14d2014-08-19 14:23:13 -07002590
Mathieu Chartierf8322842014-05-16 10:59:25 -07002591 const DexFile& dex_file = klass->GetDexFile();
2592 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002593 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002594 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002595 // There should always be class data if there were direct methods.
2596 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002597 ClassDataItemIterator it(dex_file, class_data);
2598 // Skip fields
2599 while (it.HasNextStaticField()) {
2600 it.Next();
2601 }
2602 while (it.HasNextInstanceField()) {
2603 it.Next();
2604 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002605 bool has_oat_class;
2606 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2607 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002608 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002609 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002610 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002611 if (!method->IsStatic()) {
2612 // Only update static methods.
2613 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002614 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002615 const void* quick_code = nullptr;
2616 if (has_oat_class) {
2617 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002618 quick_code = oat_method.GetQuickCode();
2619 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002620 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002621 if (enter_interpreter) {
2622 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002623 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08002624 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002625 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08002626 } else {
2627 quick_code = GetQuickToInterpreterBridge();
2628 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002629 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002630 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08002631 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002632 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002633}
2634
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002635void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002636 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002637 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002638 Runtime* runtime = Runtime::Current();
2639 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002640 // The following code only applies to a non-compiler runtime.
2641 return;
2642 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002643 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002644 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002645 if (oat_class != nullptr) {
2646 // Every kind of method should at least get an invoke stub from the oat_method.
2647 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002648 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002649 oat_method.LinkMethod(method.Get());
2650 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002651
Jeff Hao16743632013-05-08 10:59:04 -07002652 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002653 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08002654 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002655 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002656 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002657 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002658 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002659 }
2660
Brian Carlstrom92827a52011-10-10 15:50:01 -07002661 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002662 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002663 return;
2664 }
Ian Rogers19846512012-02-24 11:42:47 -08002665
2666 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002667 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002668 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2669 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002670 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002671 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002672 if (!method->IsNative()) {
2673 // Set entry point from compiled code if there's no code or in interpreter only mode.
2674 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002675 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002676 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002677 }
Ian Rogers0d6de042012-02-29 08:50:26 -08002678 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002679
Ian Rogers62d6c772013-02-27 08:32:07 -08002680 if (method->IsNative()) {
2681 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002682 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002683
2684 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002685 // We have a native method here without code. Then it should have either the generic JNI
2686 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2687 // TODO: this doesn't handle all the cases where trampolines may be installed.
2688 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2689 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002690 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002691 }
2692}
2693
Fred Shih37f05ef2014-07-16 18:38:08 -07002694
Fred Shih37f05ef2014-07-16 18:38:08 -07002695
Ian Rogers7b078e82014-09-10 14:44:24 -07002696void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002697 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002698 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002699 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002700 CHECK(klass.Get() != nullptr);
2701 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002702 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002703 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002704 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002705
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002706 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07002707 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002708 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002709 klass->SetAccessFlags(access_flags);
2710 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002711 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002712 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002713
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002714 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002715 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002716 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002717
Ian Rogers13735952014-10-08 12:43:28 -07002718 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002719 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002720 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002721 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002722
Ian Rogers97b52f82014-08-14 11:34:07 -07002723
2724 bool has_oat_class = false;
2725 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2726 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2727 &has_oat_class);
2728 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002729 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002730 }
2731 }
2732 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002733 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002734 }
2735}
2736
Ian Rogers7b078e82014-09-10 14:44:24 -07002737void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002738 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002739 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002740 const OatFile::OatClass* oat_class) {
2741 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002742 ClassDataItemIterator it(dex_file, class_data);
2743 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002744 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002745 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002746 CHECK(self->IsExceptionPending()); // OOME.
2747 return;
2748 }
2749 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002750 }
2751 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002752 mirror::ObjectArray<mirror::ArtField>* fields =
2753 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002754 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002755 CHECK(self->IsExceptionPending()); // OOME.
2756 return;
2757 }
2758 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002759 }
2760 for (size_t i = 0; it.HasNextStaticField(); 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> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002764 if (UNLIKELY(sfield.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->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002769 LoadField(dex_file, it, klass, sfield);
2770 }
2771 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002772 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002773 StackHandleScope<1> hs(self);
2774 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002775 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002776 CHECK(self->IsExceptionPending()); // OOME.
2777 return;
2778 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002779 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002780 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002781 }
2782
Ian Rogers0571d352011-11-03 19:51:38 -07002783 // Load methods.
2784 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002785 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002786 mirror::ObjectArray<mirror::ArtMethod>* directs =
2787 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002788 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002789 CHECK(self->IsExceptionPending()); // OOME.
2790 return;
2791 }
2792 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002793 }
Ian Rogers0571d352011-11-03 19:51:38 -07002794 if (it.NumVirtualMethods() != 0) {
2795 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002796 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2797 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002798 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002799 CHECK(self->IsExceptionPending()); // OOME.
2800 return;
2801 }
2802 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002803 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002804 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002805 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2806 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002807 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002808 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002809 StackHandleScope<1> hs(self);
2810 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002811 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002812 CHECK(self->IsExceptionPending()); // OOME.
2813 return;
2814 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002815 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002816 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002817 uint32_t it_method_index = it.GetMemberIndex();
2818 if (last_dex_method_index == it_method_index) {
2819 // duplicate case
2820 method->SetMethodIndex(last_class_def_method_index);
2821 } else {
2822 method->SetMethodIndex(class_def_method_index);
2823 last_dex_method_index = it_method_index;
2824 last_class_def_method_index = class_def_method_index;
2825 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002826 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002827 }
2828 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002829 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002830 StackHandleScope<1> hs(self);
2831 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002832 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002833 CHECK(self->IsExceptionPending()); // OOME.
2834 return;
2835 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002836 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002837 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002838 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002839 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002840 }
2841 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002842}
2843
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002844void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002845 Handle<mirror::Class> klass,
2846 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002847 uint32_t field_idx = it.GetMemberIndex();
2848 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002849 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002850 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002851}
2852
Brian Carlstromea46f952013-07-30 01:26:50 -07002853mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002854 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002855 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002856 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002857 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002858 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002859
Brian Carlstromea46f952013-07-30 01:26:50 -07002860 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002861 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002862 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002863 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002864 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002865 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002866
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002867 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002868 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002869 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002870 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002871
Ian Rogers19846512012-02-24 11:42:47 -08002872 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002873 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002874
Andreas Gampe51829322014-08-25 15:05:04 -07002875 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002876
Ian Rogersdfb325e2013-10-30 01:00:44 -07002877 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002878 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002879 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2880 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002881 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002882 klass->SetFinalizable();
2883 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002884 std::string temp;
2885 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002886 // The Enum class declares a "final" finalize() method to prevent subclasses from
2887 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2888 // subclasses, so we exclude it here.
2889 // We also want to avoid setting the flag on Object, where we know that finalize() is
2890 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002891 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2892 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002893 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002894 }
2895 }
2896 }
2897 } else if (method_name[0] == '<') {
2898 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002899 bool is_init = (strcmp("<init>", method_name) == 0);
2900 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002901 if (UNLIKELY(!is_init && !is_clinit)) {
2902 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2903 } else {
2904 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2905 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002906 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002907 access_flags |= kAccConstructor;
2908 }
2909 }
2910 }
2911 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002912
Mathieu Chartier66f19252012-09-18 08:57:04 -07002913 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002914}
2915
Ian Rogers7b078e82014-09-10 14:44:24 -07002916void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002917 StackHandleScope<1> hs(self);
2918 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002919 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2920 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002921 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002922}
2923
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002924void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002925 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002926 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002927 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002928 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002929}
2930
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002931bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002932 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002933 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002934 mirror::DexCache* dex_cache = GetDexCache(i);
2935 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002936 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002937 }
2938 }
2939 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002940}
2941
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002942bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002943 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002944 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002945}
2946
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002947void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002948 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002949 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002950 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002951 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2952 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002953 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002954 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002955 if (log_new_dex_caches_roots_) {
2956 // TODO: This is not safe if we can remove dex caches.
2957 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2958 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002959}
2960
Brian Carlstromaded5f72011-10-07 17:15:04 -07002961void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002962 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002963 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002964 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002965 if (IsDexFileRegisteredLocked(dex_file)) {
2966 return;
2967 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002968 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002969 // Don't alloc while holding the lock, since allocation may need to
2970 // suspend all threads and another thread may need the dex_lock_ to
2971 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002972 StackHandleScope<1> hs(self);
2973 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002974 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2975 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002976 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002977 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002978 if (IsDexFileRegisteredLocked(dex_file)) {
2979 return;
2980 }
2981 RegisterDexFileLocked(dex_file, dex_cache);
2982 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002983}
2984
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002985void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002986 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002987 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002988 RegisterDexFileLocked(dex_file, dex_cache);
2989}
2990
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002991mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002992 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002993 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002994 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002995 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002996 if (dex_cache->GetDexFile() == &dex_file) {
2997 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002998 }
2999 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003000 // Search matching by location name.
3001 std::string location(dex_file.GetLocation());
3002 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003003 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003004 if (dex_cache->GetDexFile()->GetLocation() == location) {
3005 return dex_cache;
3006 }
3007 }
3008 // Failure, dump diagnostic and abort.
3009 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003010 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003011 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3012 }
3013 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003014 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003015}
3016
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003017void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003018 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003019 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003020 mirror::DexCache* dex_cache = GetDexCache(i);
3021 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003022 }
3023}
3024
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003025mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003026 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003027 if (UNLIKELY(klass == nullptr)) {
3028 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003029 }
3030 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003031}
3032
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003033mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3034 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003035 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003036 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003037 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003038 StackHandleScope<1> hs(self);
3039 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003040 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003041 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003042 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003043 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3044 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003045 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3046 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003047 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003048 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003049}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003050
Brian Carlstrombe977852011-07-19 14:54:54 -07003051// Create an array class (i.e. the class object for the array, not the
3052// array itself). "descriptor" looks like "[C" or "[[[[B" or
3053// "[Ljava/lang/String;".
3054//
3055// If "descriptor" refers to an array of primitives, look up the
3056// primitive type's internally-generated class object.
3057//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003058// "class_loader" is the class loader of the class that's referring to
3059// us. It's used to ensure that we're looking for the element type in
3060// the right context. It does NOT become the class loader for the
3061// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003062//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003063// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003064mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003065 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003066 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003067 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003068 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003069 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3070 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003071 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003072 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003073 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003074 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3075 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003076 if (component_type.Get() == nullptr) {
3077 DCHECK(self->IsExceptionPending());
3078 return nullptr;
3079 } else {
3080 self->ClearException();
3081 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003082 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003083 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3084 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3085 return nullptr;
3086 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003087 // See if the component type is already loaded. Array classes are
3088 // always associated with the class loader of their underlying
3089 // element type -- an array of Strings goes with the loader for
3090 // java/lang/String -- so we need to look for it there. (The
3091 // caller should have checked for the existence of the class
3092 // before calling here, but they did so with *their* class loader,
3093 // not the component type's loader.)
3094 //
3095 // If we find it, the caller adds "loader" to the class' initiating
3096 // loader list, which should prevent us from going through this again.
3097 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003098 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003099 // are the same, because our caller (FindClass) just did the
3100 // lookup. (Even if we get this wrong we still have correct behavior,
3101 // because we effectively do this lookup again when we add the new
3102 // class to the hash table --- necessary because of possible races with
3103 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003104 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003105 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003106 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003107 return new_class;
3108 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003109 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003110
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003111 // Fill out the fields in the Class.
3112 //
3113 // It is possible to execute some methods against arrays, because
3114 // all arrays are subclasses of java_lang_Object_, so we need to set
3115 // up a vtable. We can just point at the one in java_lang_Object_.
3116 //
3117 // Array classes are simple enough that we don't need to do a full
3118 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003119 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003120 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003121 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003122 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003123 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003124 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003125 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003126 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003127 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003128 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003129 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003130 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003131 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003132 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003133 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003134 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003135 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003136 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003137 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003138 }
3139 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003140 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003141 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003142 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003143 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003144 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003145 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003146 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003147 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003148 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003149 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003150 new_class->SetSuperClass(java_lang_Object);
3151 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003152 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003153 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003154 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003155 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003156 StackHandleScope<mirror::Class::kImtSize> hs2(self,
3157 Runtime::Current()->GetImtUnimplementedMethod());
3158 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003159 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003160 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003161 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003162 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003163
3164
3165 // All arrays have java/lang/Cloneable and java/io/Serializable as
3166 // interfaces. We need to set that up here, so that stuff like
3167 // "instanceof" works right.
3168 //
3169 // Note: The GC could run during the call to FindSystemClass,
3170 // so we need to make sure the class object is GC-valid while we're in
3171 // there. Do this by clearing the interface list so the GC will just
3172 // think that the entries are null.
3173
3174
3175 // Use the single, global copies of "interfaces" and "iftable"
3176 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003177 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003178 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003179 CHECK(array_iftable != nullptr);
3180 new_class->SetIfTable(array_iftable);
3181 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003182
Elliott Hughes00626c22013-06-14 15:04:14 -07003183 // Inherit access flags from the component type.
3184 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3185 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3186 access_flags &= kAccJavaFlagsMask;
3187 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003188 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003189 access_flags |= kAccAbstract | kAccFinal;
3190 access_flags &= ~kAccInterface;
3191
3192 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003193
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003194 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003195 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003196 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003197 }
3198 // Another thread must have loaded the class after we
3199 // started but before we finished. Abandon what we've
3200 // done.
3201 //
3202 // (Yes, this happens.)
3203
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003204 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003205}
3206
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003207mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003208 switch (type) {
3209 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003210 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003211 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003212 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003213 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003214 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003215 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003216 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003217 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003218 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003219 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003220 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003221 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003222 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003223 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003224 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003225 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003226 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003227 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003228 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003229 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003230 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003231 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003232 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003233}
3234
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003235mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3236 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003237 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003238 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003239 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003240 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003241 source += " from ";
3242 source += dex_cache->GetLocation()->ToModifiedUtf8();
3243 }
3244 LOG(INFO) << "Loaded class " << descriptor << source;
3245 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003246 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003247 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003248 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003249 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003250 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003251 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003252 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003253 // Check a class loaded with the system class loader matches one in the image if the class
3254 // is in the image.
3255 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003256 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003257 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003258 }
3259 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003260 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003261 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003262 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003263 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003264 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003265 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003266}
3267
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003268mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3269 size_t hash) {
3270 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003271 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3272 hash);
3273 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003274 CHECK(klass->IsProxyClass());
3275 return nullptr;
3276 }
3277
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003278 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003279 CHECK_NE(existing, klass) << descriptor;
3280 CHECK(!existing->IsResolved()) << descriptor;
3281 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3282
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003283 CHECK(!klass->IsTemp()) << descriptor;
3284 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3285 dex_cache_image_class_lookup_required_) {
3286 // Check a class loaded with the system class loader matches one in the image if the class
3287 // is in the image.
3288 existing = LookupClassFromImage(descriptor);
3289 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003290 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003291 }
3292 }
3293 VerifyObject(klass);
3294
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003295 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003296 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003297 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003298 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003299 }
3300
3301 return existing;
3302}
3303
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003304bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003305 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003306 auto pair = std::make_pair(descriptor, class_loader);
3307 auto it = class_table_.Find(pair);
3308 if (it != class_table_.end()) {
3309 class_table_.Erase(it);
3310 return true;
3311 }
3312 it = pre_zygote_class_table_.Find(pair);
3313 if (it != pre_zygote_class_table_.end()) {
3314 pre_zygote_class_table_.Erase(it);
3315 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003316 }
3317 return false;
3318}
3319
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003320mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003321 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003322 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003323 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003324 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003325 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003326 return result;
3327 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003328 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003329 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3330 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003331 } else {
3332 // Lookup failed but need to search dex_caches_.
3333 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003334 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003335 InsertClass(descriptor, result, hash);
3336 } else {
3337 // Searching the image dex files/caches failed, we don't want to get into this situation
3338 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3339 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003340 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003341 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3342 MoveImageClassesToClassTable();
3343 }
3344 }
3345 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003346 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003347}
3348
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003349mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003350 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003351 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003352 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3353 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3354 if (it == pre_zygote_class_table_.end()) {
3355 it = class_table_.FindWithHash(descriptor_pair, hash);
3356 if (it == class_table_.end()) {
3357 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003358 }
3359 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003360 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003361}
3362
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003363static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3364 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3365 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003366 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003367 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3368 return root->AsObjectArray<mirror::DexCache>();
3369}
3370
3371void ClassLinker::MoveImageClassesToClassTable() {
3372 Thread* self = Thread::Current();
3373 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3374 if (!dex_cache_image_class_lookup_required_) {
3375 return; // All dex cache classes are already in the class table.
3376 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003377 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003378 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003379 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003380 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3381 mirror::DexCache* dex_cache = dex_caches->Get(i);
3382 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3383 for (int32_t j = 0; j < types->GetLength(); j++) {
3384 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003385 if (klass != nullptr) {
3386 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003387 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003388 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003389 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3390 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003391 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003392 << PrettyClassAndClassLoader(klass);
3393 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003394 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003395 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003396 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003397 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003398 }
3399 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003400 }
3401 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003402 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003403}
3404
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003405void ClassLinker::MoveClassTableToPreZygote() {
3406 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3407 DCHECK(pre_zygote_class_table_.Empty());
3408 pre_zygote_class_table_ = std::move(class_table_);
3409 class_table_.Clear();
3410}
3411
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003412mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003413 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003414 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3415 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3416 mirror::DexCache* dex_cache = dex_caches->Get(i);
3417 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003418 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003419 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003420 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003421 const DexFile::TypeId* type_id =
3422 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003423 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003424 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3425 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003426 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003427 return klass;
3428 }
3429 }
3430 }
3431 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003432 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003433}
3434
3435void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3436 result.clear();
3437 if (dex_cache_image_class_lookup_required_) {
3438 MoveImageClassesToClassTable();
3439 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003440 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3441 while (true) {
3442 auto it = class_table_.Find(descriptor);
3443 if (it == class_table_.end()) {
3444 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003445 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003446 result.push_back(it->Read());
3447 class_table_.Erase(it);
3448 }
3449 for (mirror::Class* k : result) {
3450 class_table_.Insert(GcRoot<mirror::Class>(k));
3451 }
3452 size_t pre_zygote_start = result.size();
3453 // Now handle the pre zygote table.
3454 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3455 // called from the debugger.
3456 while (true) {
3457 auto it = pre_zygote_class_table_.Find(descriptor);
3458 if (it == pre_zygote_class_table_.end()) {
3459 break;
3460 }
3461 result.push_back(it->Read());
3462 pre_zygote_class_table_.Erase(it);
3463 }
3464 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3465 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003466 }
3467}
3468
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003469void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003470 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003471 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003472
Ian Rogers9ffb0392012-09-10 11:56:50 -07003473 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003474 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003475 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003476 return;
3477 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003478 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3479 return;
3480 }
jeffhao98eacac2011-09-14 16:11:53 -07003481
Ian Rogers9ffb0392012-09-10 11:56:50 -07003482 // The class might already be erroneous, for example at compile time if we attempted to verify
3483 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003484 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003485 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003486 return;
3487 }
3488
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003489 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003490 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003491 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003492 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003493 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003494 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003495 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003496 }
jeffhao98eacac2011-09-14 16:11:53 -07003497
Jeff Hao4a200f52014-04-01 14:58:49 -07003498 // Skip verification if disabled.
3499 if (!Runtime::Current()->IsVerificationEnabled()) {
3500 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003501 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003502 return;
3503 }
3504
Ian Rogers9ffb0392012-09-10 11:56:50 -07003505 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003506 StackHandleScope<2> hs(self);
3507 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003508 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003509 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003510 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003511
3512 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003513 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003514 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003515 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003516 std::string error_msg(
3517 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3518 PrettyDescriptor(klass.Get()).c_str(),
3519 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08003520 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003521 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3522 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003523 self->ClearException();
3524 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003525 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3526 if (cause.Get() != nullptr) {
3527 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003528 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003529 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003530 if (Runtime::Current()->IsCompiler()) {
3531 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3532 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003533 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003534 return;
3535 }
3536 }
3537
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003538 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003539 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003540 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003541 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003542 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003543 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003544 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003545 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003546 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3547 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003548 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003549 return;
3550 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003551 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003552 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003553 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003554 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003555 Runtime::Current()->IsCompiler(),
3556 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003557 }
3558 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003559 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003560 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003561 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3562 << " because: " << error_msg;
3563 }
Ian Rogers1f539342012-10-03 21:09:42 -07003564 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003565 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003566 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003567 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003568 // Even though there were no verifier failures we need to respect whether the super-class
3569 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003570 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003571 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003572 } else {
3573 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003574 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003575 // Pretend a soft failure occured so that we don't consider the class verified below.
3576 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003577 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003578 } else {
3579 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3580 // Soft failures at compile time should be retried at runtime. Soft
3581 // failures at runtime will be handled by slow paths in the generated
3582 // code. Set status accordingly.
3583 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003584 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003585 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003586 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003587 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3588 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003589 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003590 }
3591 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003592 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08003593 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003594 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3595 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003596 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003597 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003598 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003599 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003600 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003601 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003602 // Let the interpreter know it by setting the kAccPreverified flag onto each
3603 // method.
3604 // Note: we're going here during compilation and at runtime. When we set the
3605 // kAccPreverified flag when compiling image classes, the flag is recorded
3606 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003607 EnsurePreverifiedMethods(klass);
3608 }
3609}
3610
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003611void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003612 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003613 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003614 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003615 }
jeffhao98eacac2011-09-14 16:11:53 -07003616}
3617
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003618bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3619 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003620 // If we're compiling, we can only verify the class using the oat file if
3621 // we are not compiling the image or if the class we're verifying is not part of
3622 // the app. In other words, we will only check for preverification of bootclasspath
3623 // classes.
3624 if (Runtime::Current()->IsCompiler()) {
3625 // Are we compiling the bootclasspath?
3626 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3627 return false;
3628 }
3629 // We are compiling an app (not the image).
3630
3631 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003632 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003633 return false;
3634 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003635 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003636
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003637 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003638 // In case we run without an image there won't be a backing oat file.
3639 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003640 return false;
3641 }
3642
Andreas Gampe76bd8802014-12-10 16:43:58 -08003643 // We may be running with a preopted oat file but without image. In this case,
3644 // we don't skip verification of preverified classes to ensure we initialize
3645 // dex caches with all types resolved during verification.
3646 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
3647 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
3648 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
3649 // already pre-opted, as then the runtime is started.
3650 if (!Runtime::Current()->IsCompiler() &&
3651 !Runtime::Current()->GetHeap()->HasImageSpace() &&
3652 klass->GetClassLoader() != nullptr) {
3653 return false;
3654 }
3655
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003656 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003657 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003658 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3659 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003660 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003661 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003662 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003663 // Compile time verification failed with a soft error. Compile time verification can fail
3664 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003665 // class ... {
3666 // Foo x;
3667 // .... () {
3668 // if (...) {
3669 // v1 gets assigned a type of resolved class Foo
3670 // } else {
3671 // v1 gets assigned a type of unresolved class Bar
3672 // }
3673 // iput x = v1
3674 // } }
3675 // when we merge v1 following the if-the-else it results in Conflict
3676 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3677 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3678 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3679 // at compile time).
3680 return false;
3681 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003682 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003683 // Compile time verification failed with a hard error. This is caused by invalid instructions
3684 // in the class. These errors are unrecoverable.
3685 return false;
3686 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003687 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003688 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3689 // not loading the class.
3690 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3691 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003692 return false;
3693 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003694 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003695 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003696 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003697 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003698 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003699}
3700
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003701void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003702 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003703 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3704 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3705 }
3706 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3707 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3708 }
3709}
3710
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003711void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003712 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003713 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3714 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003715 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003716 return; // native or abstract method
3717 }
3718 if (code_item->tries_size_ == 0) {
3719 return; // nothing to process
3720 }
Ian Rogers13735952014-10-08 12:43:28 -07003721 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003722 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3723 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3724 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3725 CatchHandlerIterator iterator(handlers_ptr);
3726 for (; iterator.HasNext(); iterator.Next()) {
3727 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3728 // unresolved exception types will be ignored by exception delivery
3729 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003730 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003731 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003732 DCHECK(Thread::Current()->IsExceptionPending());
3733 Thread::Current()->ClearException();
3734 }
3735 }
3736 }
3737 handlers_ptr = iterator.EndDataPointer();
3738 }
3739}
3740
Brian Carlstromea46f952013-07-30 01:26:50 -07003741static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003742static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3743 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003744
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003745mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003746 jobjectArray interfaces, jobject loader,
3747 jobjectArray methods, jobjectArray throws) {
3748 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003749 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003750 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003751 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003752 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003753 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003754 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003755 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003756 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003757 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003758 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3759 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003760 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003761 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003762 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003763 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003764 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003765 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003766
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003767 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003768 {
3769 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003770 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003771 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003772 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003773 }
3774 klass->SetSFields(sfields);
3775 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003776 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3777 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003778 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3779 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003780 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003781 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003782 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003783 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003784 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003785 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003786 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3787 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003788 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3789 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003790 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003791 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003792 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003793 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003794 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003795 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003796 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003797
Ian Rogers466bb252011-10-14 03:29:56 -07003798 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003799 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003800 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003801 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003802 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003803 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003804 }
3805 klass->SetDirectMethods(directs);
3806 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003807 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003808 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003809 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003810 }
3811 klass->SetDirectMethod(0, constructor);
3812 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003813
Mathieu Chartier590fee92013-09-13 13:46:47 -07003814 // Create virtual method using specified prototypes.
3815 size_t num_virtual_methods =
3816 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003817 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003818 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3819 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003820 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003821 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003822 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003823 }
3824 klass->SetVirtualMethods(virtuals);
3825 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003826 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003827 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003828 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3829 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003830 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003831 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003832 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003833 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003834 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003835 }
3836 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003837 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003838
3839 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003840 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003841 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003842
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003843 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3844 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003845 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003846 // Must hold lock on object when resolved.
3847 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003848 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003849 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003850 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003851 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003852 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003853 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003854 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003855 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003856
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003857 CHECK(klass->IsRetired());
3858 CHECK_NE(klass.Get(), new_class);
3859 klass.Assign(new_class);
3860
3861 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003862 interfaces_sfield->SetObject<false>(klass.Get(),
3863 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003864 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003865 throws_sfield->SetObject<false>(klass.Get(),
3866 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003867
3868 {
3869 // Lock on klass is released. Lock new class object.
3870 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003871 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003872 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003873
3874 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003875 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003876 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003877 CheckProxyConstructor(klass->GetDirectMethod(0));
3878 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003879 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003880 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3881 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003882 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3883 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003884 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003885 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003886
Mathieu Chartier590fee92013-09-13 13:46:47 -07003887 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003888 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003889 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003890 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3891
3892 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003893 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003894 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003895
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003896 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003897 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003898 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003899 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003900 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003901 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3902 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003903 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003904 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003905}
3906
Ian Rogersef7d42f2014-01-06 12:55:46 -08003907std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003908 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003909 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003910 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003911 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3912}
3913
Ian Rogersef7d42f2014-01-06 12:55:46 -08003914mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3915 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003916 DCHECK(proxy_class->IsProxyClass());
3917 DCHECK(proxy_method->IsProxyMethod());
3918 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003919 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003920 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003921 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003922 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003923 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003924 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003925 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003926 break;
3927 }
3928 }
3929 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003930 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003931 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003932 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003933 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003934 return resolved_method;
3935}
3936
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003937
Brian Carlstromea46f952013-07-30 01:26:50 -07003938mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003939 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003940 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003941 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003942 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003943 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003944 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3945 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003946 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3947 // constructor method.
3948 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3949 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003950 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3951 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003952 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3953 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003954 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003955 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003956 }
Ian Rogers466bb252011-10-14 03:29:56 -07003957 // Make this constructor public and fix the class to be our Proxy version
3958 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003959 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003960 return constructor;
3961}
3962
Brian Carlstromea46f952013-07-30 01:26:50 -07003963static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003964 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003965 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003966 CHECK_STREQ(constructor->GetName(), "<init>");
3967 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3968 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003969 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003970}
3971
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003972mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003973 Handle<mirror::Class> klass,
3974 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003975 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3976 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003977 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003978 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003979 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003980 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003981 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003982 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003983 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003984 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003985 }
Ian Rogers466bb252011-10-14 03:29:56 -07003986
3987 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3988 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003989 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003990 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003991
Ian Rogers466bb252011-10-14 03:29:56 -07003992 // At runtime the method looks like a reference and argument saving method, clone the code
3993 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003994 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003995 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003996
Ian Rogersc2b44472011-12-14 21:17:17 -08003997 return method;
3998}
Jesse Wilson95caa792011-10-12 18:14:17 -04003999
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004000static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4001 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004002 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004003 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004004 CHECK(!prototype->IsFinal());
4005 CHECK(method->IsFinal());
4006 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004007
4008 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4009 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07004010 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4011 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004012 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4013
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004014 CHECK_STREQ(method->GetName(), prototype->GetName());
4015 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004016 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004017 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004018}
4019
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004020static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4021 bool can_init_parents)
4022 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004023 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004024 return true;
4025 }
4026 if (!can_init_statics) {
4027 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004028 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004029 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004030 return false;
4031 }
4032 // Check if there are encoded static values needing initialization.
4033 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004034 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004035 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004036 if (dex_class_def->static_values_off_ != 0) {
4037 return false;
4038 }
4039 }
4040 }
4041 if (!klass->IsInterface() && klass->HasSuperClass()) {
4042 mirror::Class* super_class = klass->GetSuperClass();
4043 if (!can_init_parents && !super_class->IsInitialized()) {
4044 return false;
4045 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004046 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004047 return false;
4048 }
4049 }
4050 }
4051 return true;
4052}
4053
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004054bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004055 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004056 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4057
4058 // Are we already initialized and therefore done?
4059 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4060 // an initialized class will never change its state.
4061 if (klass->IsInitialized()) {
4062 return true;
4063 }
4064
4065 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004066 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004067 return false;
4068 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004069
Ian Rogers7b078e82014-09-10 14:44:24 -07004070 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004071 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004072 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004073 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004074
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004075 // Re-check under the lock in case another thread initialized ahead of us.
4076 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004077 return true;
4078 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004079
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004080 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004081 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004082 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004083 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004084 return false;
4085 }
4086
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004087 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004088
4089 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004090 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004091 if (!klass->IsVerified()) {
4092 // We failed to verify, expect either the klass to be erroneous or verification failed at
4093 // compile time.
4094 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004095 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004096 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004097 } else {
4098 CHECK(Runtime::Current()->IsCompiler());
4099 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004100 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004101 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004102 } else {
4103 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004104 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004105 }
4106
Brian Carlstromd1422f82011-09-28 11:37:09 -07004107 // If the class is kStatusInitializing, either this thread is
4108 // initializing higher up the stack or another thread has beat us
4109 // to initializing and we need to wait. Either way, this
4110 // invocation of InitializeClass will not be responsible for
4111 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004112 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004113 // Could have got an exception during verification.
4114 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004115 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004116 return false;
4117 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004118 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004119 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004120 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004121 return true;
4122 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004123 // No. That's fine. Wait for another thread to finish initializing.
4124 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004125 }
4126
4127 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004128 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004129 return false;
4130 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004131 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004132
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004133 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004134
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004135 // From here out other threads may observe that we're initializing and so changes of state
4136 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004137 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004138 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004139
4140 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004141 }
4142
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004143 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004144 if (!klass->IsInterface() && klass->HasSuperClass()) {
4145 mirror::Class* super_class = klass->GetSuperClass();
4146 if (!super_class->IsInitialized()) {
4147 CHECK(!super_class->IsInterface());
4148 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004149 StackHandleScope<1> hs(self);
4150 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004151 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004152 if (!super_initialized) {
4153 // The super class was verified ahead of entering initializing, we should only be here if
4154 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004155 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004156 << "Super class initialization failed for "
4157 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004158 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004159 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004160 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004161 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004162 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004163 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004164 return false;
4165 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004166 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004167 }
4168
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004169 const size_t num_static_fields = klass->NumStaticFields();
4170 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004171 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004172 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004173 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004174 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004175 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004176 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004177
4178 // Eagerly fill in static fields so that the we don't have to do as many expensive
4179 // Class::FindStaticField in ResolveField.
4180 for (size_t i = 0; i < num_static_fields; ++i) {
4181 mirror::ArtField* field = klass->GetStaticField(i);
4182 const uint32_t field_idx = field->GetDexFieldIndex();
4183 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4184 if (resolved_field == nullptr) {
4185 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004186 } else {
4187 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004188 }
4189 }
4190
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004191 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4192 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004193 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004194 ClassDataItemIterator field_it(dex_file, class_data);
4195 if (value_it.HasNext()) {
4196 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004197 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004198 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004199 StackHandleScope<1> hs2(self);
4200 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004201 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004202 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004203 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004204 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004205 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004206 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004207 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004208 }
4209 }
4210 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004211
Ian Rogersd91d6d62013-09-25 20:26:14 -07004212 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004213 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004214 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004215 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004216 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004217 }
4218
Ian Rogers7b078e82014-09-10 14:44:24 -07004219 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004220 uint64_t t1 = NanoTime();
4221
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004222 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004223 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004224 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004225
4226 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004227 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004228 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004229 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004230 } else if (Runtime::Current()->IsTransactionAborted()) {
4231 // The exception thrown when the transaction aborted has been caught and cleared
4232 // so we need to throw it again now.
4233 LOG(WARNING) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
4234 << " without exception while transaction was aborted: re-throw it now.";
4235 Runtime::Current()->ThrowInternalErrorForAbortedTransaction(self);
4236 klass->SetStatus(mirror::Class::kStatusError, self);
4237 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004238 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004239 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4240 RuntimeStats* thread_stats = self->GetStats();
4241 ++global_stats->class_init_count;
4242 ++thread_stats->class_init_count;
4243 global_stats->class_init_time_ns += (t1 - t0);
4244 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004245 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004246 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004247 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004248 std::string temp;
4249 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004250 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004251 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004252 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004253 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004254 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004255 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004256 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004257}
4258
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004259bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004260 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004261 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004262 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004263 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004264 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004265 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004266
4267 // When we wake up, repeat the test for init-in-progress. If
4268 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004269 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004270 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004271 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004272 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004273 return false;
4274 }
4275 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004276 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004277 continue;
4278 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004279 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004280 // Compile time initialization failed.
4281 return false;
4282 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004283 if (klass->IsErroneous()) {
4284 // The caller wants an exception, but it was thrown in a
4285 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004286 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004287 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004288 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004289 return false;
4290 }
4291 if (klass->IsInitialized()) {
4292 return true;
4293 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004294 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004295 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004296 }
Ian Rogers07140832014-09-30 15:43:59 -07004297 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004298}
4299
Ian Rogersb5fb2072014-12-02 17:22:02 -08004300static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
4301 Handle<mirror::ArtMethod> method1,
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004302 Handle<mirror::ArtMethod> method2,
4303 std::string* error_msg)
Ian Rogersb5fb2072014-12-02 17:22:02 -08004304 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4305 {
4306 StackHandleScope<1> hs(self);
4307 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
Vladimir Marko862f43c2015-02-10 18:22:57 +00004308 mirror::Class* other_return_type = method2->GetReturnType();
4309 // NOTE: return_type.Get() must be sequenced after method2->GetReturnType().
4310 if (UNLIKELY(other_return_type != return_type.Get())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004311 *error_msg = StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
4312 PrettyClassAndClassLoader(return_type.Get()).c_str(),
4313 return_type.Get(),
4314 PrettyClassAndClassLoader(other_return_type).c_str(),
4315 other_return_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004316 return false;
4317 }
4318 }
4319 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4320 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4321 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004322 if (types2 != nullptr && types2->Size() != 0) {
4323 *error_msg = StringPrintf("Type list mismatch with %s",
4324 PrettyMethod(method2.Get(), true).c_str());
4325 return false;
4326 }
4327 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08004328 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004329 if (types1->Size() != 0) {
4330 *error_msg = StringPrintf("Type list mismatch with %s",
4331 PrettyMethod(method2.Get(), true).c_str());
4332 return false;
4333 }
4334 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08004335 }
4336 uint32_t num_types = types1->Size();
4337 if (UNLIKELY(num_types != types2->Size())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004338 *error_msg = StringPrintf("Type list mismatch with %s",
4339 PrettyMethod(method2.Get(), true).c_str());
Ian Rogersb5fb2072014-12-02 17:22:02 -08004340 return false;
4341 }
4342 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00004343 StackHandleScope<1> hs(self);
4344 Handle<mirror::Class> param_type(hs.NewHandle(
4345 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true)));
Ian Rogersb5fb2072014-12-02 17:22:02 -08004346 mirror::Class* other_param_type =
4347 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
Vladimir Marko862f43c2015-02-10 18:22:57 +00004348 // NOTE: param_type.Get() must be sequenced after method2->GetClassFromTypeIndex(...).
4349 if (UNLIKELY(param_type.Get() != other_param_type)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004350 *error_msg = StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
4351 i,
4352 PrettyClassAndClassLoader(param_type.Get()).c_str(),
4353 param_type.Get(),
4354 PrettyClassAndClassLoader(other_param_type).c_str(),
4355 other_param_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004356 return false;
4357 }
4358 }
4359 return true;
4360}
4361
4362
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004363bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004364 if (klass->IsInterface()) {
4365 return true;
4366 }
Ian Rogers151f2212014-05-06 11:27:27 -07004367 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004368 Thread* self = Thread::Current();
4369 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004370 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
4371 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004372 if (klass->HasSuperClass() &&
4373 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004374 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004375 h_m.Assign(klass->GetVTableEntry(i));
4376 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004377 if (h_m.Get() != super_h_m.Get()) {
4378 std::string error_msg;
4379 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
4380 ThrowLinkageError(klass.Get(),
4381 "Class %s method %s resolves differently in superclass %s: %s",
4382 PrettyDescriptor(klass.Get()).c_str(),
4383 PrettyMethod(h_m.Get()).c_str(),
4384 PrettyDescriptor(klass->GetSuperClass()).c_str(),
4385 error_msg.c_str());
4386 return false;
4387 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004388 }
4389 }
4390 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004391 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004392 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4393 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4394 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004395 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4396 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004397 if (h_m.Get() != super_h_m.Get()) {
4398 std::string error_msg;
4399 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
4400 ThrowLinkageError(klass.Get(),
4401 "Class %s method %s resolves differently in interface %s: %s",
4402 PrettyDescriptor(klass.Get()).c_str(),
4403 PrettyMethod(h_m.Get()).c_str(),
4404 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str(),
4405 error_msg.c_str());
4406 return false;
4407 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004408 }
4409 }
4410 }
4411 }
4412 return true;
4413}
4414
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004415bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4416 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004417 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004418 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004419 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004420 return true;
4421 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004422 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004423 if (!success) {
4424 if (can_init_fields && can_init_parents) {
4425 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4426 }
4427 } else {
4428 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004429 }
4430 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004431}
4432
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004433void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4434 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4435 if (fields != nullptr) {
4436 for (int index = 0; index < fields->GetLength(); index ++) {
4437 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4438 fields->Get(index)->SetDeclaringClass(new_class);
4439 }
4440 }
4441 }
4442
4443 fields = new_class->GetSFields();
4444 if (fields != nullptr) {
4445 for (int index = 0; index < fields->GetLength(); index ++) {
4446 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4447 fields->Get(index)->SetDeclaringClass(new_class);
4448 }
4449 }
4450 }
4451
4452 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4453 if (methods != nullptr) {
4454 for (int index = 0; index < methods->GetLength(); index ++) {
4455 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4456 methods->Get(index)->SetDeclaringClass(new_class);
4457 }
4458 }
4459 }
4460
4461 methods = new_class->GetVirtualMethods();
4462 if (methods != nullptr) {
4463 for (int index = 0; index < methods->GetLength(); index ++) {
4464 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4465 methods->Get(index)->SetDeclaringClass(new_class);
4466 }
4467 }
4468 }
4469}
4470
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004471bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4472 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004473 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004474 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004475
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004476 if (!LinkSuperClass(klass)) {
4477 return false;
4478 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004479 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4480 self, Runtime::Current()->GetImtUnimplementedMethod());
4481 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004482 return false;
4483 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004484 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004485 return false;
4486 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004487 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004488 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004489 return false;
4490 }
4491 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004492 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004493
4494 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4495 // We don't need to retire this class as it has no embedded tables or it was created the
4496 // correct size during class linker initialization.
4497 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4498
4499 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004500 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004501 }
4502
4503 // This will notify waiters on klass that saw the not yet resolved
4504 // class in the class_table_ during EnsureResolved.
4505 klass->SetStatus(mirror::Class::kStatusResolved, self);
4506 *new_class = klass.Get();
4507 } else {
4508 CHECK(!klass->IsResolved());
4509 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004510 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004511 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004512 CHECK(self->IsExceptionPending()); // Expect an OOME.
4513 klass->SetStatus(mirror::Class::kStatusError, self);
4514 return false;
4515 }
4516
4517 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4518 StackHandleScope<1> hs(self);
4519 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4520 ObjectLock<mirror::Class> lock(self, new_class_h);
4521
4522 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4523
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004524 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4525 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004526 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004527
4528 // This will notify waiters on temp class that saw the not yet resolved class in the
4529 // class_table_ during EnsureResolved.
4530 klass->SetStatus(mirror::Class::kStatusRetired, self);
4531
4532 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4533 // This will notify waiters on new_class that saw the not yet resolved
4534 // class in the class_table_ during EnsureResolved.
4535 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004536 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004537 return true;
4538}
4539
Andreas Gampefd9eb392014-11-06 16:52:58 -08004540static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
4541 size_t* virtual_methods,
4542 size_t* direct_methods,
4543 size_t* static_fields,
4544 size_t* instance_fields) {
4545 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
4546
4547 while (dex_data.HasNextStaticField()) {
4548 dex_data.Next();
4549 (*static_fields)++;
4550 }
4551 while (dex_data.HasNextInstanceField()) {
4552 dex_data.Next();
4553 (*instance_fields)++;
4554 }
4555 while (dex_data.HasNextDirectMethod()) {
4556 (*direct_methods)++;
4557 dex_data.Next();
4558 }
4559 while (dex_data.HasNextVirtualMethod()) {
4560 (*virtual_methods)++;
4561 dex_data.Next();
4562 }
4563 DCHECK(!dex_data.HasNext());
4564}
4565
4566static void DumpClass(std::ostream& os,
4567 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
4568 const char* suffix) {
4569 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
4570 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
4571 os << " Static fields:\n";
4572 while (dex_data.HasNextStaticField()) {
4573 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4574 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4575 dex_data.Next();
4576 }
4577 os << " Instance fields:\n";
4578 while (dex_data.HasNextInstanceField()) {
4579 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4580 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4581 dex_data.Next();
4582 }
4583 os << " Direct methods:\n";
4584 while (dex_data.HasNextDirectMethod()) {
4585 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4586 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4587 dex_data.Next();
4588 }
4589 os << " Virtual methods:\n";
4590 while (dex_data.HasNextVirtualMethod()) {
4591 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4592 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4593 dex_data.Next();
4594 }
4595}
4596
4597static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4598 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
4599 std::ostringstream os;
4600 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
4601 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
4602 return os.str();
4603}
4604
4605
4606// Very simple structural check on whether the classes match. Only compares the number of
4607// methods and fields.
4608static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4609 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
4610 std::string* error_msg) {
4611 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
4612 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
4613
4614 // Counters for current dex file.
4615 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
4616 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
4617 &dex_instance_fields1);
4618 // Counters for compile-time dex file.
4619 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
4620 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
4621 &dex_instance_fields2);
4622
4623 if (dex_virtual_methods1 != dex_virtual_methods2) {
4624 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4625 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
4626 dex_virtual_methods2, class_dump.c_str());
4627 return false;
4628 }
4629 if (dex_direct_methods1 != dex_direct_methods2) {
4630 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4631 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
4632 dex_direct_methods2, class_dump.c_str());
4633 return false;
4634 }
4635 if (dex_static_fields1 != dex_static_fields2) {
4636 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4637 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
4638 dex_static_fields2, class_dump.c_str());
4639 return false;
4640 }
4641 if (dex_instance_fields1 != dex_instance_fields2) {
4642 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4643 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
4644 dex_instance_fields2, class_dump.c_str());
4645 return false;
4646 }
4647
4648 return true;
4649}
4650
4651// Checks whether a the super-class changed from what we had at compile-time. This would
4652// invalidate quickening.
4653static bool CheckSuperClassChange(Handle<mirror::Class> klass,
4654 const DexFile& dex_file,
4655 const DexFile::ClassDef& class_def,
4656 mirror::Class* super_class)
4657 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4658 // Check for unexpected changes in the superclass.
4659 // Quick check 1) is the super_class class-loader the boot class loader? This always has
4660 // precedence.
4661 if (super_class->GetClassLoader() != nullptr &&
4662 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
4663 // which is implied by different dex cache.
4664 klass->GetDexCache() != super_class->GetDexCache()) {
4665 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
4666 // definition for the super-class, and (b) the files are in separate oat files. The oat files
4667 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
4668 const OatFile* class_oat_file = dex_file.GetOatFile();
4669 if (class_oat_file != nullptr) {
4670 const OatFile* loaded_super_oat_file = super_class->GetDexFile().GetOatFile();
4671 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
4672 // Now check (a).
4673 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
4674 if (super_class_def != nullptr) {
4675 // Uh-oh, we found something. Do our check.
4676 std::string error_msg;
4677 if (!SimpleStructuralCheck(dex_file, *super_class_def,
4678 super_class->GetDexFile(), *super_class->GetClassDef(),
4679 &error_msg)) {
4680 // Print a warning to the log. This exception might be caught, e.g., as common in test
4681 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
4682 // only save the type of the exception.
4683 LOG(WARNING) << "Incompatible structural change detected: " <<
4684 StringPrintf(
4685 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4686 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4687 class_oat_file->GetLocation().c_str(),
4688 loaded_super_oat_file->GetLocation().c_str(),
4689 error_msg.c_str());
4690 ThrowIncompatibleClassChangeError(klass.Get(),
4691 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4692 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4693 class_oat_file->GetLocation().c_str(),
4694 loaded_super_oat_file->GetLocation().c_str(),
4695 error_msg.c_str());
4696 return false;
4697 }
4698 }
4699 }
4700 }
4701 }
4702 return true;
4703}
4704
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004705bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004706 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004707 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4708 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004709 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004710 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004711 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004712 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004713 return false;
4714 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004715 // Verify
4716 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004717 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004718 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004719 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004720 return false;
4721 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004722 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004723 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08004724
4725 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
4726 DCHECK(Thread::Current()->IsExceptionPending());
4727 return false;
4728 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004729 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004730 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004731 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004732 for (size_t i = 0; i < interfaces->Size(); i++) {
4733 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004734 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004735 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004736 DCHECK(Thread::Current()->IsExceptionPending());
4737 return false;
4738 }
4739 // Verify
4740 if (!klass->CanAccess(interface)) {
4741 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004742 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004743 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004744 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004745 return false;
4746 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004747 }
4748 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004749 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004750 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004751 return true;
4752}
4753
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004754bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004755 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004756 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004757 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004758 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004759 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004760 return false;
4761 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004762 return true;
4763 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004764 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004765 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4766 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004767 return false;
4768 }
4769 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004770 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004771 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004772 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004773 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004774 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004775 return false;
4776 }
4777 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004778 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004779 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004780 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004781 return false;
4782 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004783
Brian Carlstromf3632832014-05-20 15:36:53 -07004784 // Inherit kAccClassIsFinalizable from the superclass in case this
4785 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004786 if (super->IsFinalizable()) {
4787 klass->SetFinalizable();
4788 }
4789
Elliott Hughes2da50362011-10-10 16:57:08 -07004790 // Inherit reference flags (if any) from the superclass.
4791 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4792 if (reference_flags != 0) {
4793 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4794 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004795 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004796 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004797 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004798 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004799 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004800 return false;
4801 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004802
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004803 if (kIsDebugBuild) {
4804 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004805 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004806 CHECK(super->IsResolved());
4807 super = super->GetSuperClass();
4808 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004809 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004810 return true;
4811}
4812
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004813// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004814bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004815 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4816 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004817 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004818 if (klass->IsInterface()) {
4819 // No vtable.
4820 size_t count = klass->NumVirtualMethods();
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004821 if (!IsUint<16>(count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004822 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004823 return false;
4824 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004825 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004826 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004827 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004828 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4829 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004830 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004831 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004832}
4833
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004834// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4835// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4836// caches in the implementation below.
4837class MethodNameAndSignatureComparator FINAL : public ValueObject {
4838 public:
4839 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4840 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4841 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4842 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004843 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4844 }
4845
4846 const char* GetName() {
4847 if (name_ == nullptr) {
4848 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4849 }
4850 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004851 }
4852
4853 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4854 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4855 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4856 const DexFile* other_dex_file = other->GetDexFile();
4857 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4858 if (dex_file_ == other_dex_file) {
4859 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4860 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004861 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004862 uint32_t other_name_len;
4863 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4864 &other_name_len);
4865 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4866 return false;
4867 }
4868 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4869 }
4870
4871 private:
4872 // Dex file for the method to compare against.
4873 const DexFile* const dex_file_;
4874 // MethodId for the method to compare against.
4875 const DexFile::MethodId* const mid_;
4876 // Lazily computed name from the dex file's strings.
4877 const char* name_;
4878 // Lazily computed name length.
4879 uint32_t name_len_;
4880};
4881
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004882class LinkVirtualHashTable {
4883 public:
4884 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4885 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4886 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4887 }
4888 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4889 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4890 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004891 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004892 uint32_t index = hash % hash_size_;
4893 // Linear probe until we have an empty slot.
4894 while (hash_table_[index] != invalid_index_) {
4895 if (++index == hash_size_) {
4896 index = 0;
4897 }
4898 }
4899 hash_table_[index] = virtual_method_index;
4900 }
4901 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4902 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4903 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004904 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004905 size_t index = hash % hash_size_;
4906 while (true) {
4907 const uint32_t value = hash_table_[index];
4908 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4909 // the block and can safely assume not found.
4910 if (value == invalid_index_) {
4911 break;
4912 }
4913 if (value != removed_index_) { // This signifies not already overriden.
4914 mirror::ArtMethod* virtual_method =
4915 klass_->GetVirtualMethodDuringLinking(value);
4916 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4917 hash_table_[index] = removed_index_;
4918 return value;
4919 }
4920 }
4921 if (++index == hash_size_) {
4922 index = 0;
4923 }
4924 }
4925 return GetNotFoundIndex();
4926 }
4927 static uint32_t GetNotFoundIndex() {
4928 return invalid_index_;
4929 }
4930
4931 private:
4932 static const uint32_t invalid_index_;
4933 static const uint32_t removed_index_;
4934
4935 Handle<mirror::Class> klass_;
4936 const size_t hash_size_;
4937 uint32_t* const hash_table_;
4938};
4939
4940const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4941const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4942
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004943bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004944 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004945 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004946 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4947 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004948 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004949 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004950 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004951 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4952 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4953 if (UNLIKELY(vtable.Get() == nullptr)) {
4954 CHECK(self->IsExceptionPending()); // OOME.
4955 return false;
4956 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004957 for (size_t i = 0; i < super_vtable_length; i++) {
4958 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004959 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004960 if (num_virtual_methods == 0) {
4961 klass->SetVTable(vtable.Get());
4962 return true;
4963 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004964 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004965 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4966 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4967 if (num_virtual_methods == 0) {
4968 klass->SetVTable(super_vtable);
4969 return true;
4970 }
4971 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004972 if (UNLIKELY(vtable.Get() == nullptr)) {
4973 CHECK(self->IsExceptionPending()); // OOME.
4974 return false;
4975 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004976 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004977 // How the algorithm works:
4978 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4979 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4980 // method which has not been matched to a vtable method, and j if the virtual method at the
4981 // index overrode the super virtual method at index j.
4982 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4983 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4984 // the need for the initial vtable which we later shrink back down).
4985 // 3. Add non overridden methods to the end of the vtable.
4986 static constexpr size_t kMaxStackHash = 250;
4987 const size_t hash_table_size = num_virtual_methods * 3;
4988 uint32_t* hash_table_ptr;
4989 std::unique_ptr<uint32_t[]> hash_heap_storage;
4990 if (hash_table_size <= kMaxStackHash) {
4991 hash_table_ptr = reinterpret_cast<uint32_t*>(
4992 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4993 } else {
4994 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4995 hash_table_ptr = hash_heap_storage.get();
4996 }
4997 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4998 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004999 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005000 hash_table.Add(i);
5001 }
5002 // Loop through each super vtable method and see if they are overriden by a method we added to
5003 // the hash table.
5004 for (size_t j = 0; j < super_vtable_length; ++j) {
5005 // Search the hash table to see if we are overidden by any method.
5006 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
5007 MethodNameAndSignatureComparator super_method_name_comparator(
5008 super_method->GetInterfaceMethodIfProxy());
5009 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5010 if (hash_index != hash_table.GetNotFoundIndex()) {
5011 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
5012 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
5013 super_method->GetAccessFlags())) {
5014 if (super_method->IsFinal()) {
5015 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5016 PrettyMethod(virtual_method).c_str(),
5017 super_method->GetDeclaringClassDescriptor());
5018 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005019 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005020 vtable->SetWithoutChecks<false>(j, virtual_method);
5021 virtual_method->SetMethodIndex(j);
5022 } else {
5023 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005024 << " would have incorrectly overridden the package-private method in "
5025 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005026 }
5027 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005028 }
5029 // Add the non overridden methods at the end.
5030 size_t actual_count = super_vtable_length;
5031 for (size_t i = 0; i < num_virtual_methods; ++i) {
5032 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
5033 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5034 if (method_idx < super_vtable_length &&
5035 local_method == vtable->GetWithoutChecks(method_idx)) {
5036 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005037 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005038 vtable->SetWithoutChecks<false>(actual_count, local_method);
5039 local_method->SetMethodIndex(actual_count);
5040 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005041 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005042 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005043 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005044 return false;
5045 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005046 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005047 CHECK_LE(actual_count, max_count);
5048 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005049 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005050 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005051 CHECK(self->IsExceptionPending()); // OOME.
5052 return false;
5053 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005054 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005055 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005056 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005057 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08005058 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005059 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5060 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005061 return false;
5062 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005063 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
5064 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005065 CHECK(self->IsExceptionPending()); // OOME.
5066 return false;
5067 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005068 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005069 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005070 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005071 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005072 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005073 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005074 }
5075 return true;
5076}
5077
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005078bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
5079 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
5080 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07005081 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005082 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005083 const bool has_superclass = klass->HasSuperClass();
5084 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
5085 const bool have_interfaces = interfaces.Get() != nullptr;
5086 const size_t num_interfaces =
5087 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
5088 if (num_interfaces == 0) {
5089 if (super_ifcount == 0) {
5090 // Class implements no interfaces.
5091 DCHECK_EQ(klass->GetIfTableCount(), 0);
5092 DCHECK(klass->GetIfTable() == nullptr);
5093 return true;
5094 }
Ian Rogers9bc81912012-10-11 21:43:36 -07005095 // Class implements same interfaces as parent, are any of these not marker interfaces?
5096 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005097 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005098 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005099 if (super_iftable->GetMethodArrayCount(i) > 0) {
5100 has_non_marker_interface = true;
5101 break;
5102 }
5103 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005104 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07005105 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005106 klass->SetIfTable(super_iftable);
5107 return true;
5108 }
5109 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005110 size_t ifcount = super_ifcount + num_interfaces;
5111 for (size_t i = 0; i < num_interfaces; i++) {
5112 mirror::Class* interface = have_interfaces ?
5113 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
5114 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005115 if (UNLIKELY(!interface->IsInterface())) {
5116 std::string temp;
5117 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
5118 PrettyDescriptor(klass.Get()).c_str(),
5119 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
5120 return false;
5121 }
5122 ifcount += interface->GetIfTableCount();
5123 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005124 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005125 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005126 CHECK(self->IsExceptionPending()); // OOME.
5127 return false;
5128 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005129 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005130 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005131 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005132 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07005133 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005134 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005135 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005136 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005137 // Flatten the interface inheritance hierarchy.
5138 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005139 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07005140 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
5141 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005142 // Check if interface is already in iftable
5143 bool duplicate = false;
5144 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005145 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005146 if (existing_interface == interface) {
5147 duplicate = true;
5148 break;
5149 }
5150 }
5151 if (!duplicate) {
5152 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07005153 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005154 // Add this interface's non-duplicate super-interfaces.
5155 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005156 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005157 bool super_duplicate = false;
5158 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005159 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005160 if (existing_interface == super_interface) {
5161 super_duplicate = true;
5162 break;
5163 }
5164 }
5165 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005166 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005167 }
5168 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005169 }
5170 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005171 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08005172 // Shrink iftable in case duplicates were found
5173 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005174 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005175 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005176 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005177 CHECK(self->IsExceptionPending()); // OOME.
5178 return false;
5179 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08005180 ifcount = idx;
5181 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005182 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005183 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005184 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07005185 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07005186 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005187 return true;
5188 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005189 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005190 size_t max_miranda_methods = 0; // The max size of miranda_list.
5191 for (size_t i = 0; i < ifcount; ++i) {
5192 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
5193 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005194 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005195 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005196 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
5197 hs.NewHandle(klass->GetVTableDuringLinking()));
5198 // Copy the IMT from the super class if possible.
5199 bool extend_super_iftable = false;
5200 if (has_superclass) {
5201 mirror::Class* super_class = klass->GetSuperClass();
5202 extend_super_iftable = true;
5203 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5204 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5205 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
5206 }
5207 } else {
5208 // No imt in the super class, need to reconstruct from the iftable.
5209 mirror::IfTable* if_table = super_class->GetIfTable();
5210 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5211 const size_t length = super_class->GetIfTableCount();
5212 for (size_t i = 0; i < length; ++i) {
5213 mirror::Class* interface = iftable->GetInterface(i);
5214 const size_t num_virtuals = interface->NumVirtualMethods();
5215 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5216 DCHECK_EQ(num_virtuals, method_array_count);
5217 if (method_array_count == 0) {
5218 continue;
5219 }
5220 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5221 for (size_t j = 0; j < num_virtuals; ++j) {
5222 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5223 if (method->IsMiranda()) {
5224 continue;
5225 }
5226 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5227 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5228 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5229 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5230 out_imt->SetReference(imt_index, method);
5231 } else if (imt_ref != conflict_method) {
5232 out_imt->SetReference(imt_index, conflict_method);
5233 }
5234 }
5235 }
5236 }
5237 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005238 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005239 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005240 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005241 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005242 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005243 const bool is_super = i < super_ifcount;
5244 const bool super_interface = is_super && extend_super_iftable;
5245 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5246 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5247 if (super_interface) {
5248 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5249 DCHECK(if_table != nullptr);
5250 DCHECK(if_table->GetMethodArray(i) != nullptr);
5251 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005252 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005253 AsObjectArray<mirror::ArtMethod>());
5254 // We are overwriting a super class interface, try to only virtual methods instead of the
5255 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005256 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005257 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005258 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005259 // A new interface, we need the whole vtable incase a new interface method is implemented
5260 // in the whole superclass.
5261 input_array = vtable;
5262 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005263 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005264 CHECK(self->IsExceptionPending()); // OOME.
5265 return false;
5266 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005267 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005268 if (input_array.Get() == nullptr) {
5269 // If the added virtual methods is empty, do nothing.
5270 DCHECK(super_interface);
5271 continue;
5272 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005273 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005274 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005275 MethodNameAndSignatureComparator interface_name_comparator(
5276 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005277 int32_t k;
5278 // For each method listed in the interface's method list, find the
5279 // matching method in our class's method list. We want to favor the
5280 // subclass over the superclass, which just requires walking
5281 // back from the end of the vtable. (This only matters if the
5282 // superclass defines a private method and this class redefines
5283 // it -- otherwise it would use the same vtable slot. In .dex files
5284 // those don't end up in the virtual method table, so it shouldn't
5285 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005286 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5287 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005288 mirror::ArtMethod* vtable_method_for_name_comparison =
5289 vtable_method->GetInterfaceMethodIfProxy();
5290 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005291 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005292 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005293 ThrowIllegalAccessError(
5294 klass.Get(),
5295 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005296 PrettyMethod(vtable_method).c_str(),
5297 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005298 return false;
5299 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005300 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005301 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005302 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5303 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5304 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5305 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5306 out_imt->SetReference(imt_index, vtable_method);
5307 } else if (imt_ref != conflict_method) {
5308 // If we are not a conflict and we have the same signature and name as the imt entry,
5309 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005310 MethodNameAndSignatureComparator imt_ref_name_comparator(
5311 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005312 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005313 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005314 out_imt->SetReference(imt_index, vtable_method);
5315 } else {
5316 out_imt->SetReference(imt_index, conflict_method);
5317 }
Jeff Hao88474b42013-10-23 16:24:40 -07005318 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005319 break;
5320 }
5321 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005322 if (k < 0 && !super_interface) {
5323 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005324 for (size_t l = 0; l < miranda_list_size; ++l) {
5325 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005326 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005327 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005328 break;
5329 }
5330 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005331 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005332 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005333 miranda_method = interface_method->Clone(self)->AsArtMethod();
5334 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005335 CHECK(self->IsExceptionPending()); // OOME.
5336 return false;
5337 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005338 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005339 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005340 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005341 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005342 }
5343 }
5344 }
5345 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005346 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005347 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005348 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005349 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5350 if (old_method_count == 0) {
5351 virtuals = AllocArtMethodArray(self, new_method_count);
5352 } else {
5353 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5354 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005355 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005356 CHECK(self->IsExceptionPending()); // OOME.
5357 return false;
5358 }
5359 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005360
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005361 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005362 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005363 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005364 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005365 CHECK(self->IsExceptionPending()); // OOME.
5366 return false;
5367 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005368 for (size_t i = 0; i < miranda_list_size; ++i) {
5369 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005370 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005371 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5372 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5373 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005374 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005375 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005376 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005377 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005378 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005379
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005380 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005381 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5382 for (int i = 0; i < check_vtable->GetLength(); ++i) {
5383 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005384 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005385 }
5386
Ian Rogers7b078e82014-09-10 14:44:24 -07005387 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005388 return true;
5389}
5390
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005391bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005392 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005393 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005394}
5395
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005396bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005397 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005398 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005399}
5400
Brian Carlstromdbc05252011-09-09 01:59:59 -07005401struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005402 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5403 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005404 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005405 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005406 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005407 // 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 -07005408 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5409 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005410 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005411 if (type1 == Primitive::kPrimNot) {
5412 // Reference always goes first.
5413 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005414 }
Vladimir Markod5777482014-11-12 17:02:02 +00005415 if (type2 == Primitive::kPrimNot) {
5416 // Reference always goes first.
5417 return false;
5418 }
5419 size_t size1 = Primitive::ComponentSize(type1);
5420 size_t size2 = Primitive::ComponentSize(type2);
5421 if (size1 != size2) {
5422 // Larger primitive types go first.
5423 return size1 > size2;
5424 }
5425 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5426 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005427 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005428 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5429 // by name and for equal names by type id index.
5430 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5431 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005432 }
5433};
5434
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005435bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005436 size_t* class_size) {
5437 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005438 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005439 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005440
Brian Carlstromea46f952013-07-30 01:26:50 -07005441 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005442 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005443
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005444 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005445 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005446 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00005447 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005448 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005449 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005450 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005451 CHECK(super_class->IsResolved())
5452 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005453 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005454 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005455 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005456
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005457 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005458
Brian Carlstromdbc05252011-09-09 01:59:59 -07005459 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005460 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005461 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005462 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005463 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005464 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005465 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005466 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005467 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005468 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005469 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5470 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005471
Fred Shih381e4ca2014-08-25 17:24:27 -07005472 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005473 size_t current_field = 0;
5474 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005475 FieldGaps gaps;
5476
Brian Carlstromdbc05252011-09-09 01:59:59 -07005477 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005478 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005479 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005480 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005481 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005482 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005483 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005484 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5485 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005486 MemberOffset old_offset = field_offset;
5487 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5488 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5489 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005490 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005491 grouped_and_sorted_fields.pop_front();
5492 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005493 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005494 field_offset = MemberOffset(field_offset.Uint32Value() +
5495 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005496 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005497 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5498 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005499 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5500 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5501 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5502 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005503 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5504 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005505 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005506
Elliott Hughesadb460d2011-10-05 17:02:34 -07005507 // 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 -07005508 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005509 // We know there are no non-reference fields in the Reference classes, and we know
5510 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005511 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005512 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005513 --num_reference_fields;
5514 }
5515
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005516 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005517 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005518 if (is_static) {
5519 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005520 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005521 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005522 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005523 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08005524 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
Jeff Haoc7d11882015-02-03 15:08:39 -08005525 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
5526 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartier2d721012014-11-10 11:08:06 -08005527 } else {
5528 std::string temp;
5529 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5530 size_t previous_size = klass->GetObjectSize();
5531 if (previous_size != 0) {
5532 // Make sure that we didn't originally have an incorrect size.
5533 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5534 }
5535 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005536 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005537 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005538 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005539
5540 if (kIsDebugBuild) {
5541 // Make sure that the fields array is ordered by name but all reference
5542 // offsets are at the beginning as far as alignment allows.
5543 MemberOffset start_ref_offset = is_static
5544 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5545 : klass->GetFirstReferenceInstanceFieldOffset();
5546 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5547 num_reference_fields *
5548 sizeof(mirror::HeapReference<mirror::Object>));
5549 MemberOffset current_ref_offset = start_ref_offset;
5550 for (size_t i = 0; i < num_fields; i++) {
5551 mirror::ArtField* field = fields->Get(i);
5552 if ((false)) { // enable to debug field layout
5553 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5554 << " class=" << PrettyClass(klass.Get())
5555 << " field=" << PrettyField(field)
5556 << " offset="
5557 << field->GetField32(mirror::ArtField::OffsetOffset());
5558 }
5559 if (i != 0) {
5560 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005561 // NOTE: The field names can be the same. This is not possible in the Java language
5562 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5563 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005564 }
5565 Primitive::Type type = field->GetTypeAsPrimitiveType();
5566 bool is_primitive = type != Primitive::kPrimNot;
5567 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5568 strcmp("referent", field->GetName()) == 0) {
5569 is_primitive = true; // We lied above, so we have to expect a lie here.
5570 }
5571 MemberOffset offset = field->GetOffsetDuringLinking();
5572 if (is_primitive) {
5573 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5574 // Shuffled before references.
5575 size_t type_size = Primitive::ComponentSize(type);
5576 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5577 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5578 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5579 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5580 }
5581 } else {
5582 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5583 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5584 sizeof(mirror::HeapReference<mirror::Object>));
5585 }
5586 }
5587 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5588 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005589 return true;
5590}
5591
Vladimir Marko76649e82014-11-10 18:32:59 +00005592// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005593void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005594 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005595 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005596 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005597 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005598 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005599 // Compute reference offsets unless our superclass overflowed.
5600 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5601 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005602 if (num_reference_fields != 0u) {
5603 // All of the fields that contain object references are guaranteed be grouped in memory
5604 // starting at an appropriately aligned address after super class object data.
5605 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5606 sizeof(mirror::HeapReference<mirror::Object>));
5607 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005608 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005609 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005610 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005611 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005612 reference_offsets |= (0xffffffffu << start_bit) &
5613 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005614 }
5615 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005616 }
5617 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005618 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005619}
5620
Mathieu Chartier590fee92013-09-13 13:46:47 -07005621mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005622 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005623 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005624 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005625 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005626 return resolved;
5627 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005628 uint32_t utf16_length;
5629 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005630 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005631 dex_cache->SetResolvedString(string_idx, string);
5632 return string;
5633}
5634
Mathieu Chartier590fee92013-09-13 13:46:47 -07005635mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005636 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005637 StackHandleScope<2> hs(Thread::Current());
5638 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5639 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005640 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5641}
5642
5643mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005644 Handle<mirror::DexCache> dex_cache,
5645 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005646 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005647 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005648 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005649 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005650 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005651 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005652 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005653 // TODO: we used to throw here if resolved's class loader was not the
5654 // boot class loader. This was to permit different classes with the
5655 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005656 dex_cache->SetResolvedType(type_idx, resolved);
5657 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005658 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005659 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005660 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005661 StackHandleScope<1> hs(self);
5662 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005663 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005664 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005665 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005666 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005667 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005668 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005669 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005670 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005671 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005672 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005673 return resolved;
5674}
5675
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005676mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005677 Handle<mirror::DexCache> dex_cache,
5678 Handle<mirror::ClassLoader> class_loader,
5679 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005680 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005681 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005682 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005683 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005684 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005685 return resolved;
5686 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005687 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005688 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005689 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005690 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005691 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005692 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005693 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005694 // Scan using method_idx, this saves string compares but will only hit for matching dex
5695 // caches/files.
5696 switch (type) {
5697 case kDirect: // Fall-through.
5698 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005699 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005700 break;
5701 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005702 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005703 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005704 break;
5705 case kSuper: // Fall-through.
5706 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005707 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005708 break;
5709 default:
5710 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005711 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005712 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005713 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005714 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005715 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005716 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005717 switch (type) {
5718 case kDirect: // Fall-through.
5719 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005720 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005721 break;
5722 case kInterface:
5723 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005724 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005725 break;
5726 case kSuper: // Fall-through.
5727 case kVirtual:
5728 resolved = klass->FindVirtualMethod(name, signature);
5729 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005730 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005731 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005732 // If we found a method, check for incompatible class changes.
5733 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005734 // Be a good citizen and update the dex cache to speed subsequent calls.
5735 dex_cache->SetResolvedMethod(method_idx, resolved);
5736 return resolved;
5737 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005738 // If we had a method, it's an incompatible-class-change error.
5739 if (resolved != nullptr) {
5740 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5741 } else {
5742 // We failed to find the method which means either an access error, an incompatible class
5743 // change, or no such method. First try to find the method among direct and virtual methods.
5744 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5745 const Signature signature = dex_file.GetMethodSignature(method_id);
5746 switch (type) {
5747 case kDirect:
5748 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005749 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005750 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5751 // have had a resolved method before, which triggers the "true" branch above.
5752 break;
5753 case kInterface:
5754 case kVirtual:
5755 case kSuper:
5756 resolved = klass->FindDirectMethod(name, signature);
5757 break;
5758 }
5759
5760 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005761 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005762 if (resolved != nullptr && referrer.Get() != nullptr) {
5763 mirror::Class* methods_class = resolved->GetDeclaringClass();
5764 mirror::Class* referring_class = referrer->GetDeclaringClass();
5765 if (!referring_class->CanAccess(methods_class)) {
5766 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5767 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005768 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005769 } else if (!referring_class->CanAccessMember(methods_class,
5770 resolved->GetAccessFlags())) {
5771 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005772 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005773 }
5774 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005775 if (!exception_generated) {
5776 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5777 // interface methods and throw if we find the method there. If we find nothing, throw a
5778 // NoSuchMethodError.
5779 switch (type) {
5780 case kDirect:
5781 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005782 if (resolved != nullptr) {
5783 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5784 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005785 resolved = klass->FindInterfaceMethod(name, signature);
5786 if (resolved != nullptr) {
5787 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5788 } else {
5789 ThrowNoSuchMethodError(type, klass, name, signature);
5790 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005791 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005792 break;
5793 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005794 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005795 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5796 } else {
5797 resolved = klass->FindVirtualMethod(name, signature);
5798 if (resolved != nullptr) {
5799 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5800 } else {
5801 ThrowNoSuchMethodError(type, klass, name, signature);
5802 }
5803 }
5804 break;
5805 case kSuper:
5806 if (resolved != nullptr) {
5807 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005808 } else {
5809 ThrowNoSuchMethodError(type, klass, name, signature);
5810 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005811 break;
5812 case kVirtual:
5813 if (resolved != nullptr) {
5814 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5815 } else {
5816 resolved = klass->FindInterfaceMethod(name, signature);
5817 if (resolved != nullptr) {
5818 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5819 } else {
5820 ThrowNoSuchMethodError(type, klass, name, signature);
5821 }
5822 }
5823 break;
5824 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005825 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005826 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005827 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005828 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005829 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005830}
5831
Mathieu Chartier590fee92013-09-13 13:46:47 -07005832mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005833 Handle<mirror::DexCache> dex_cache,
5834 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005835 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005836 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005837 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005838 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005839 return resolved;
5840 }
5841 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005842 Thread* const self = Thread::Current();
5843 StackHandleScope<1> hs(self);
5844 Handle<mirror::Class> klass(
5845 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005846 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005847 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005848 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005849 }
5850
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005851 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005852 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005853 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005854 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005855 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005856
Andreas Gampe58a5af82014-07-31 16:23:49 -07005857 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005858 const char* name = dex_file.GetFieldName(field_id);
5859 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5860 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005861 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005862 } else {
5863 resolved = klass->FindInstanceField(name, type);
5864 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005865 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005866 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005867 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005868 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005869 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005870 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005871 return resolved;
5872}
5873
Brian Carlstromea46f952013-07-30 01:26:50 -07005874mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005875 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005876 Handle<mirror::DexCache> dex_cache,
5877 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005878 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005879 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005880 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005881 return resolved;
5882 }
5883 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005884 Thread* self = Thread::Current();
5885 StackHandleScope<1> hs(self);
5886 Handle<mirror::Class> klass(
5887 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005888 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005889 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005890 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005891 }
5892
Ian Rogersdfb325e2013-10-30 01:00:44 -07005893 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5894 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005895 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005896 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005897 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005898 dex_cache->SetResolvedField(field_idx, resolved);
5899 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005900 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005901 }
5902 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005903}
5904
Brian Carlstromea46f952013-07-30 01:26:50 -07005905const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005906 uint32_t* length) {
5907 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5908 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005909 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005910 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005911 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005912}
5913
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005914void ClassLinker::DumpAllClasses(int flags) {
5915 if (dex_cache_image_class_lookup_required_) {
5916 MoveImageClassesToClassTable();
5917 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005918 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5919 // 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 -08005920 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005921 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005922 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005923 for (GcRoot<mirror::Class>& it : class_table_) {
5924 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005925 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005926 }
5927
5928 for (size_t i = 0; i < all_classes.size(); ++i) {
5929 all_classes[i]->DumpClass(std::cerr, flags);
5930 }
5931}
5932
Elliott Hughes956af0f2014-12-11 14:34:28 -08005933static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005934 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005935 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5936 base -= sizeof(void*); // Move backward so that code_offset != 0.
5937 const uint32_t code_offset = sizeof(void*);
5938 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005939}
5940
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005941bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5942 return (entry_point == GetQuickResolutionStub()) ||
5943 (quick_resolution_trampoline_ == entry_point);
5944}
5945
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005946bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5947 return (entry_point == GetQuickToInterpreterBridge()) ||
5948 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5949}
5950
5951bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5952 return (entry_point == GetQuickGenericJniStub()) ||
5953 (quick_generic_jni_trampoline_ == entry_point);
5954}
5955
5956const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5957 return GetQuickGenericJniStub();
5958}
5959
Elliott Hughes956af0f2014-12-11 14:34:28 -08005960void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5961 const void* method_code) const {
5962 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005963 oat_method.LinkMethod(method);
5964 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005965}
5966
5967void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5968 if (!method->IsNative()) {
5969 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005970 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5971 } else {
5972 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005973 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005974 oat_method.LinkMethod(method);
5975 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005976 }
5977}
5978
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005979void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005980 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005981 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005982 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005983 MoveImageClassesToClassTable();
5984 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005985 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005986 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5987 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005988}
5989
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005990size_t ClassLinker::NumLoadedClasses() {
5991 if (dex_cache_image_class_lookup_required_) {
5992 MoveImageClassesToClassTable();
5993 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005994 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005995 // Only return non zygote classes since these are the ones which apps which care about.
5996 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005997}
5998
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005999pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07006000 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07006001}
6002
6003pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07006004 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07006005}
6006
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08006007void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006008 DCHECK(!init_done_);
6009
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006010 DCHECK(klass != nullptr);
6011 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006012
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07006013 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006014 DCHECK(class_roots != nullptr);
6015 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07006016 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006017}
6018
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006019const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
6020 static const char* class_roots_descriptors[] = {
6021 "Ljava/lang/Class;",
6022 "Ljava/lang/Object;",
6023 "[Ljava/lang/Class;",
6024 "[Ljava/lang/Object;",
6025 "Ljava/lang/String;",
6026 "Ljava/lang/DexCache;",
6027 "Ljava/lang/ref/Reference;",
6028 "Ljava/lang/reflect/ArtField;",
6029 "Ljava/lang/reflect/ArtMethod;",
6030 "Ljava/lang/reflect/Proxy;",
6031 "[Ljava/lang/String;",
6032 "[Ljava/lang/reflect/ArtField;",
6033 "[Ljava/lang/reflect/ArtMethod;",
6034 "Ljava/lang/ClassLoader;",
6035 "Ljava/lang/Throwable;",
6036 "Ljava/lang/ClassNotFoundException;",
6037 "Ljava/lang/StackTraceElement;",
6038 "Z",
6039 "B",
6040 "C",
6041 "D",
6042 "F",
6043 "I",
6044 "J",
6045 "S",
6046 "V",
6047 "[Z",
6048 "[B",
6049 "[C",
6050 "[D",
6051 "[F",
6052 "[I",
6053 "[J",
6054 "[S",
6055 "[Ljava/lang/StackTraceElement;",
6056 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08006057 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
6058 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006059
6060 const char* descriptor = class_roots_descriptors[class_root];
6061 CHECK(descriptor != nullptr);
6062 return descriptor;
6063}
6064
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006065std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
6066 const {
6067 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006068 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006069}
6070
6071bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
6072 const GcRoot<mirror::Class>& b) {
6073 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
6074 return false;
6075 }
6076 std::string temp;
6077 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
6078}
6079
6080std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
6081 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006082 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006083}
6084
6085bool ClassLinker::ClassDescriptorHashEquals::operator()(
6086 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
6087 if (a.Read()->GetClassLoader() != b.second) {
6088 return false;
6089 }
6090 return a.Read()->DescriptorEquals(b.first);
6091}
6092
6093bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
6094 const char* descriptor) {
6095 return a.Read()->DescriptorEquals(descriptor);
6096}
6097
6098std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006099 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006100}
6101
Sebastien Hertz6963e442014-11-26 22:11:27 +01006102bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
6103 // Non-image methods don't use direct code pointer.
6104 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
6105 return false;
6106 }
6107 if (m->IsPrivate()) {
6108 // The method can only be called inside its own oat file. Therefore it won't be called using
6109 // its direct code if the oat file has been compiled in PIC mode.
6110 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
6111 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
6112 const OatFile::OatDexFile* oat_dex_file = class_linker->FindOpenedOatDexFileForDexFile(dex_file);
6113 if (oat_dex_file == nullptr) {
6114 // No oat file: the method has not been compiled.
6115 return false;
6116 }
6117 const OatFile* oat_file = oat_dex_file->GetOatFile();
6118 return oat_file != nullptr && !oat_file->IsPic();
6119 } else {
6120 // The method can be called outside its own oat file. Therefore it won't be called using its
6121 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
6122 ReaderMutexLock mu(Thread::Current(), dex_lock_);
6123 for (const OatFile* oat_file : oat_files_) {
6124 if (!oat_file->IsPic()) {
6125 return true;
6126 }
6127 }
6128 return false;
6129 }
6130}
6131
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006132} // namespace art