blob: d8166e25df7e6a05c98c2625d9063cf2470879e2 [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 std::string error_msg;
1012 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1013 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1014 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001015 return false;
1016 }
1017
1018 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001019 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1020 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001021 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001022 if (success) {
1023 RegisterOatFile(open_oat_file.release());
1024 return true;
1025 } else {
1026 return false;
1027 }
1028}
1029
1030const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1031 uint32_t dex_location_checksum,
1032 const char* oat_location,
1033 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001034 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001035 !Runtime::Current()->IsCompiler(),
1036 error_msg));
1037 if (oat_file.get() == nullptr) {
1038 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1039 error_msg->c_str());
1040 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001041 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001042 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001043 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1044 if (image_space != nullptr) {
1045 const ImageHeader& image_header = image_space->GetImageHeader();
1046 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1047 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1048 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1049 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1050 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1051 actual_image_oat_checksum);
1052 return nullptr;
1053 }
1054
1055 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1056 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1057 if (expected_image_oat_offset != actual_image_oat_offset) {
1058 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1059 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1060 actual_image_oat_offset);
1061 return nullptr;
1062 }
1063 int32_t expected_patch_delta = image_header.GetPatchDelta();
1064 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1065 if (expected_patch_delta != actual_patch_delta) {
1066 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1067 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1068 return nullptr;
1069 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001070 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001071
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001072 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1073 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001074 if (oat_dex_file == nullptr) {
1075 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1076 dex_location);
1077 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001078 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001079 uint32_t expected_dex_checksum = dex_location_checksum;
1080 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1081 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001082 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1083 "found 0x%x", oat_location, expected_dex_checksum,
1084 actual_dex_checksum);
1085 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001086 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001087 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1088 if (dex_file.get() != nullptr) {
1089 return oat_file.release();
1090 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001091 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001092 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001093}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001094
Andreas Gampe833a4852014-05-21 18:46:59 -07001095const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1096 int fd, const char* oat_location,
1097 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001098 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001099 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001100 std::string error_msg;
1101 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001102 CHECK(!error_msg.empty());
1103 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001104 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001105 }
Igor Murashkin46774762014-10-22 11:37:02 -07001106 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001107 !Runtime::Current()->IsCompiler(),
1108 &error_msg));
1109 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001110 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1111 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001112 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001113 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001114 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001115
1116 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001117}
1118
Alex Light6e183f22014-07-18 14:57:04 -07001119bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1120 const InstructionSet instruction_set) {
1121 Runtime* runtime = Runtime::Current();
1122 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001123 if (image_space == nullptr) {
1124 return false;
1125 }
Alex Light6e183f22014-07-18 14:57:04 -07001126 uint32_t image_oat_checksum = 0;
1127 if (instruction_set == kRuntimeISA) {
1128 const ImageHeader& image_header = image_space->GetImageHeader();
1129 image_oat_checksum = image_header.GetOatChecksum();
1130 } else {
1131 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1132 image_space->GetImageLocation().c_str(), instruction_set));
1133 image_oat_checksum = image_header->GetOatChecksum();
1134 }
1135 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1136}
1137
1138bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1139 const InstructionSet instruction_set,
1140 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001141 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001142 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001143 if (image_space == nullptr) {
1144 *error_msg = "No image space for verification against";
1145 return false;
1146 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001147
1148 // If the requested instruction set is the same as the current runtime,
1149 // we can use the checksums directly. If it isn't, we'll have to read the
1150 // image header from the image for the right instruction set.
1151 uint32_t image_oat_checksum = 0;
1152 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001153 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001154 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001155 const ImageHeader& image_header = image_space->GetImageHeader();
1156 image_oat_checksum = image_header.GetOatChecksum();
1157 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001158 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001159 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001160 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001161 image_space->GetImageLocation().c_str(), instruction_set));
1162 image_oat_checksum = image_header->GetOatChecksum();
1163 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001164 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001165 }
1166 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin96e83932014-10-29 19:45:42 -07001167 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1168
1169 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1170 if (!oat_file->IsPic()) {
1171 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1172 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1173 }
Alex Light6e183f22014-07-18 14:57:04 -07001174 if (!ret) {
1175 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1176 oat_file->GetLocation().c_str(),
1177 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1178 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1179 oat_file->GetOatHeader().GetImagePatchDelta(),
1180 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1181 }
1182 return ret;
1183}
1184
1185bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1186 const char* dex_location,
1187 uint32_t dex_location_checksum,
1188 const InstructionSet instruction_set,
1189 std::string* error_msg) {
1190 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1191 return false;
1192 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001193
Brian Carlstromf3632832014-05-20 15:36:53 -07001194 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1195 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001196 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001197 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1198 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001199 for (const OatFile::OatDexFile* oat_dex_file_in : oat_file->GetOatDexFiles()) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001200 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001201 oat_file->GetLocation().c_str(),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001202 oat_dex_file_in->GetDexFileLocation().c_str(),
1203 oat_dex_file_in->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001204 }
1205 return false;
1206 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001207
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001208 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001209 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001210}
1211
Alex Lighta59dd802014-07-02 16:28:08 -07001212bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1213 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001214 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001215 std::string* error_msg) {
1216 CHECK(oat_file != nullptr);
1217 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001218 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001219 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001220 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1221 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1222 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001223 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001224 if (oat_dex_file == nullptr) {
1225 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001226 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001227 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001228 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001229 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001230 dex_file = oat_dex_file->OpenDexFile(error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001231 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001232 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001233 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001234 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001235 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001236 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001237 dex_file = oat_file->GetOatDexFile(dex_location,
1238 dex_location_checksum)->OpenDexFile(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001239 }
Alex Lighta59dd802014-07-02 16:28:08 -07001240 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001241}
1242
Andreas Gampe833a4852014-05-21 18:46:59 -07001243const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001244 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001245 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001246 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001247 std::vector<std::string>* error_msgs,
1248 bool* obsolete_file_cleanup_failed) {
1249 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001250 bool already_opened = false;
1251 std::string dex_location_str(dex_location);
1252 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1253 &already_opened,
1254 obsolete_file_cleanup_failed,
1255 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001256 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001257 if (oat_file.get() == nullptr) {
1258 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1259 dex_location));
1260 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001261 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001262 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1263 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001264 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1265 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001266 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001267 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001268 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001269 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001270 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1271 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1272 "dex location '%s'. Image checksum incorrect.",
1273 oat_file->GetLocation().c_str(), dex_location));
1274 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001275 } else {
1276 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001277 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001278}
1279
Brian Carlstromae826982011-11-09 01:33:42 -08001280const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001281 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001282 for (size_t i = 0; i < oat_files_.size(); i++) {
1283 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001284 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001285 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001286 return oat_file;
1287 }
1288 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001289 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001290}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001291
Alex Lighta59dd802014-07-02 16:28:08 -07001292const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1293 InstructionSet isa,
1294 bool *already_opened,
1295 bool *obsolete_file_cleanup_failed,
1296 std::vector<std::string>* error_msgs) {
1297 // Find out if we've already opened the file
1298 const OatFile* ret = nullptr;
1299 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1300 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1301 if (ret != nullptr) {
1302 *already_opened = true;
1303 return ret;
1304 }
1305
1306 std::string dalvik_cache;
1307 bool have_android_data = false;
1308 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001309 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001310 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001311 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001312 std::string cache_filename;
1313 if (have_dalvik_cache) {
1314 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1315 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1316 if (ret != nullptr) {
1317 *already_opened = true;
1318 return ret;
1319 }
1320 } else {
1321 // If we need to relocate we should just place odex back where it started.
1322 cache_filename = odex_filename;
1323 }
1324
1325 ret = nullptr;
1326
1327 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1328 //
1329 // Now we do the following:
1330 // 1) Try and open the odex version
1331 // 2) If present, checksum-verified & relocated correctly return it
1332 // 3) Close the odex version to free up its address space.
1333 // 4) Try and open the cache version
1334 // 5) If present, checksum-verified & relocated correctly return it
1335 // 6) Close the cache version to free up its address space.
1336 // 7) If we should relocate:
1337 // a) If we have opened and checksum-verified the odex version relocate it to
1338 // 'cache_filename' and return it
1339 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1340 // it. This should not happen often (I think only the run-test's will hit this case).
1341 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1342 // this point.
1343 // 9) Return nullptr
1344
1345 *already_opened = false;
1346 const Runtime* runtime = Runtime::Current();
1347 CHECK(runtime != nullptr);
1348 bool executable = !runtime->IsCompiler();
1349
1350 std::string odex_error_msg;
1351 bool should_patch_system = false;
1352 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001353 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001354 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001355 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001356 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001357 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001358 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001359 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001360 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001361 &odex_checksum_verified,
1362 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001363 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001364 } else {
1365 if (odex_checksum_verified) {
1366 // We can just relocate
1367 should_patch_system = true;
1368 odex_error_msg = "Image Patches are incorrect";
1369 }
1370 if (odex_oat_file.get() != nullptr) {
1371 have_system_odex = true;
1372 }
Alex Lighta59dd802014-07-02 16:28:08 -07001373 }
1374 }
1375
Alex Lighta59dd802014-07-02 16:28:08 -07001376 std::string cache_error_msg;
1377 bool should_patch_cache = false;
1378 bool cache_checksum_verified = false;
1379 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001380 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001381 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001382 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001383 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001384 &cache_checksum_verified,
1385 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001386 return cache_oat_file.release();
1387 } else if (cache_checksum_verified) {
1388 // We can just relocate
1389 should_patch_cache = true;
1390 cache_error_msg = "Image Patches are incorrect";
1391 }
1392 } else if (have_android_data) {
1393 // dalvik_cache does not exist but android data does. This means we should be able to create
1394 // it, so we should try.
1395 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1396 }
1397
1398 ret = nullptr;
1399 std::string error_msg;
1400 if (runtime->CanRelocate()) {
1401 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001402 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1403 if (space != nullptr) {
1404 const std::string& image_location = space->GetImageLocation();
1405 if (odex_checksum_verified && should_patch_system) {
1406 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1407 } else if (cache_checksum_verified && should_patch_cache) {
1408 CHECK(have_dalvik_cache);
1409 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1410 }
Alex Light84d76052014-08-22 17:49:35 -07001411 } else if (have_system_odex) {
1412 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001413 }
1414 }
1415 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1416 // implicitly: were able to fine where the cached version is but we were unable to use it,
1417 // either as a destination for relocation or to open a file. We should delete it if it is
1418 // there.
1419 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1420 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1421 "searching for dex file %s: %s",
1422 cache_filename.c_str(), dex_location.c_str(),
1423 strerror(errno));
1424 error_msgs->push_back(rm_error_msg);
1425 VLOG(class_linker) << rm_error_msg;
1426 // Let the caller know that we couldn't remove the obsolete file.
1427 // This is a good indication that further writes may fail as well.
1428 *obsolete_file_cleanup_failed = true;
1429 }
1430 }
1431 if (ret == nullptr) {
1432 VLOG(class_linker) << error_msg;
1433 error_msgs->push_back(error_msg);
1434 std::string relocation_msg;
1435 if (runtime->CanRelocate()) {
1436 relocation_msg = StringPrintf(" and relocation failed");
1437 }
1438 if (have_dalvik_cache && cache_checksum_verified) {
1439 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1440 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1441 cache_filename.c_str(), cache_error_msg.c_str(),
1442 relocation_msg.c_str());
1443 } else {
1444 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1445 "dalvik_cache availible)%s.", odex_filename.c_str(),
1446 odex_error_msg.c_str(), relocation_msg.c_str());
1447 }
1448 VLOG(class_linker) << error_msg;
1449 error_msgs->push_back(error_msg);
1450 }
1451 return ret;
1452}
1453
Alex Light9dcc4572014-08-14 14:16:26 -07001454const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1455 InstructionSet isa,
1456 std::string* error_msg) {
1457 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001458 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001459 if (output.get() == nullptr) {
1460 return nullptr;
1461 }
Alex Light84d76052014-08-22 17:49:35 -07001462 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1463 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001464 return output.release();
1465 } else {
1466 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1467 oat_path.c_str());
1468 return nullptr;
1469 }
1470}
1471
Alex Lighta59dd802014-07-02 16:28:08 -07001472const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1473 const std::string& output_oat,
1474 const std::string& image_location,
1475 InstructionSet isa,
1476 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001477 Runtime* runtime = Runtime::Current();
1478 DCHECK(runtime != nullptr);
1479 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001480 // We don't have an image space so there is no point in trying to patchoat.
1481 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1482 << "running without an image. Attempting to use oat file for interpretation.";
1483 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1484 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001485 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001486 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1487 // input_oat but make sure we only do interpretation on it's dex files.
1488 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1489 << "disabled. Attempting to use oat file for interpretation";
1490 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1491 }
Alex Lighta59dd802014-07-02 16:28:08 -07001492 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001493 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001494
1495 std::string isa_arg("--instruction-set=");
1496 isa_arg += GetInstructionSetString(isa);
1497 std::string input_oat_filename_arg("--input-oat-file=");
1498 input_oat_filename_arg += input_oat;
1499 std::string output_oat_filename_arg("--output-oat-file=");
1500 output_oat_filename_arg += output_oat;
1501 std::string patched_image_arg("--patched-image-location=");
1502 patched_image_arg += image_location;
1503
1504 std::vector<std::string> argv;
1505 argv.push_back(patchoat);
1506 argv.push_back(isa_arg);
1507 argv.push_back(input_oat_filename_arg);
1508 argv.push_back(output_oat_filename_arg);
1509 argv.push_back(patched_image_arg);
1510
1511 std::string command_line(Join(argv, ' '));
1512 LOG(INFO) << "Relocate Oat File: " << command_line;
1513 bool success = Exec(argv, error_msg);
1514 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001515 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gampe7ba64962014-10-23 11:37:40 -07001516 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001517 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001518 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1519 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001520 return output.release();
1521 } else if (output.get() != nullptr) {
1522 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1523 "but output file '%s' failed verifcation: %s",
1524 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1525 } else {
1526 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1527 "but was unable to open output file '%s': %s",
1528 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1529 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001530 } else if (!runtime->IsCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001531 // patchoat failed which means we probably don't have enough room to place the output oat file,
1532 // instead of failing we should just run the interpreter from the dex files in the input oat.
1533 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1534 << "for interpretation. patchoat failure was: " << *error_msg;
1535 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001536 } else {
1537 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1538 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1539 error_msg->c_str());
1540 }
1541 return nullptr;
1542}
1543
Andreas Gampe7ba64962014-10-23 11:37:40 -07001544bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001545 bool* checksum_verified,
1546 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001547 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001548 if (image_space == nullptr) {
1549 *error_msg = "No image space present";
1550 return false;
1551 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001552 uint32_t real_image_checksum;
1553 void* real_image_oat_offset;
1554 int32_t real_patch_delta;
1555 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001556 const ImageHeader& image_header = image_space->GetImageHeader();
1557 real_image_checksum = image_header.GetOatChecksum();
1558 real_image_oat_offset = image_header.GetOatDataBegin();
1559 real_patch_delta = image_header.GetPatchDelta();
1560 } else {
1561 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1562 image_space->GetImageLocation().c_str(), isa));
1563 real_image_checksum = image_header->GetOatChecksum();
1564 real_image_oat_offset = image_header->GetOatDataBegin();
1565 real_patch_delta = image_header->GetPatchDelta();
1566 }
1567
1568 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001569 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001570
1571 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1572 *checksum_verified = oat_image_checksum == real_image_checksum;
1573 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001574 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1575 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001576 }
1577
Andreas Gampe7ba64962014-10-23 11:37:40 -07001578 bool offset_verified;
1579 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001580
Andreas Gampe7ba64962014-10-23 11:37:40 -07001581 if (!oat_file->IsPic()) {
1582 // If an oat file is not PIC, we need to check that the image is at the expected location and
1583 // patched in the same way.
1584 void* oat_image_oat_offset =
1585 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1586 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1587 if (!offset_verified) {
1588 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1589 real_image_oat_offset, oat_image_oat_offset);
1590 }
1591
1592 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1593 patch_delta_verified = oat_patch_delta == real_patch_delta;
1594 if (!patch_delta_verified) {
1595 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1596 "received 0x%x)", real_patch_delta, oat_patch_delta);
1597 }
1598 } else {
1599 // If an oat file is PIC, we ignore offset and patching delta.
1600 offset_verified = true;
1601 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001602 }
1603
1604 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001605 if (!ret) {
1606 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001607 }
1608 return ret;
1609}
1610
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001611const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1612 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001613 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001614 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001615 return oat_file;
1616 }
1617
Igor Murashkin46774762014-10-22 11:37:02 -07001618 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001619 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001620}
1621
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001622void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001623 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001624 DCHECK(obj != nullptr);
1625 DCHECK(class_linker != nullptr);
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001626 size_t pointer_size = class_linker->image_pointer_size_;
Ian Rogers848871b2013-08-05 10:56:33 -07001627
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001628 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001629 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001630 if (!method->IsNative()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001631 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001632 if (method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001633 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1634 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001635 }
1636 }
1637 }
1638}
1639
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001640void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001641 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001642 CHECK(!init_done_);
1643
Mathieu Chartier590fee92013-09-13 13:46:47 -07001644 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001645 gc::Heap* heap = Runtime::Current()->GetHeap();
1646 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001647 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001648 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001649 OatFile& oat_file = GetImageOatFile(space);
1650 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1651 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001652 const char* image_file_location = oat_file.GetOatHeader().
1653 GetStoreValueByKey(OatHeader::kImageLocationKey);
1654 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001655 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001656 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001657 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001658 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001659 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1660 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1661 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001662
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001663 StackHandleScope<1> hs(self);
1664 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1665 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1666 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001667 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001668
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001669 // Special case of setting up the String class early so that we can test arbitrary objects
1670 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001671 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001672
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001673 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001674 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001675 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001676 StackHandleScope<1> hs2(self);
1677 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001678 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001679 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1680 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001681 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001682 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001683 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
1684 if (dex_file.get() == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001685 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001686 << " from within oat file " << oat_file.GetLocation()
1687 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -08001688 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001689 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001690
1691 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1692
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001693 AppendToBootClassPath(*dex_file.get(), dex_cache);
1694 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001695 }
1696
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001697 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1698 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001699 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001700 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
1701 if (!Runtime::Current()->IsCompiler()) {
1702 // Compiler supports having an image with a different pointer size than the runtime. This
1703 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
1704 // also use 32 bit dex2oat on a system with 64 bit apps.
1705 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
1706 << sizeof(void*);
1707 }
1708 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
1709 image_pointer_size_ = 4;
1710 } else {
1711 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
1712 image_pointer_size_ = 8;
1713 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001714
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001715 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001716 Runtime* runtime = Runtime::Current();
1717 if (!runtime->IsCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001718 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001719 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001720
1721 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001722 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001723 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001724
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001725 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001726 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001727 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001728 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001729 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001730 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001731 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1732 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1733 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1734 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1735 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1736 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1737 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1738 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1739 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1740 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001741
Ian Rogers98379392014-02-24 16:53:16 -08001742 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001743
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001744 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001745}
1746
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001747void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1748 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1749 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001750 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001751 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001752 }
1753 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001754 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001755 }
1756 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001757 for (auto& root : new_class_roots_) {
1758 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001759 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001760 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001761 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001762 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1763 // corresponding object. This is slow, but luckily for us, this may only happen with a
1764 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001765 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001766 DCHECK(it != class_table_.end());
1767 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001768 }
1769 }
1770 }
1771 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1772 new_class_roots_.clear();
1773 }
1774 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1775 log_new_class_table_roots_ = true;
1776 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1777 log_new_class_table_roots_ = false;
1778 }
1779 // We deliberately ignore the class roots in the image since we
1780 // handle image roots by using the MS/CMS rescanning of dirty cards.
1781}
1782
Brian Carlstroma663ea52011-08-19 23:33:41 -07001783// Keep in sync with InitCallback. Anything we visit, we need to
1784// reinit references to when reinitializing a ClassLinker from a
1785// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001786void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001787 class_roots_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers50b35e22012-10-04 10:09:15 -07001788 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001789 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001790 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001791 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001792 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001793 dex_cache.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001794 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001795 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1796 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001797 dex_caches_[index].VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001798 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001799 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001800 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1801 new_dex_cache_roots_.clear();
1802 }
1803 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1804 log_new_dex_caches_roots_ = true;
1805 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1806 log_new_dex_caches_roots_ = false;
1807 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001808 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001809 VisitClassRoots(callback, arg, flags);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001810 array_iftable_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001811 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001812 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001813 find_array_class_cache_[i].VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001814 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001815}
1816
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001817void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1818 if (dex_cache_image_class_lookup_required_) {
1819 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001820 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001821 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001822 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001823 for (GcRoot<mirror::Class>& root : class_table_) {
1824 if (!visitor(root.Read(), arg)) {
1825 return;
1826 }
1827 }
1828 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1829 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001830 return;
1831 }
1832 }
1833}
1834
Ian Rogersdbf3be02014-08-29 15:40:08 -07001835static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001836 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001837 classes->insert(c);
1838 return true;
1839}
1840
Ian Rogersdbf3be02014-08-29 15:40:08 -07001841struct GetClassesVisitorArrayArg {
1842 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1843 int32_t index;
1844 bool success;
1845};
1846
1847static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1848 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1849 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1850 if (arg->index < (*arg->classes)->GetLength()) {
1851 (*arg->classes)->Set(arg->index, c);
1852 arg->index++;
1853 return true;
1854 } else {
1855 arg->success = false;
1856 return false;
1857 }
1858}
1859
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001860void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001861 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1862 // is avoiding duplicates.
1863 if (!kMovingClasses) {
1864 std::set<mirror::Class*> classes;
1865 VisitClasses(GetClassesVisitorSet, &classes);
1866 for (mirror::Class* klass : classes) {
1867 if (!visitor(klass, arg)) {
1868 return;
1869 }
1870 }
1871 } else {
1872 Thread* self = Thread::Current();
1873 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001874 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001875 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1876 GetClassesVisitorArrayArg local_arg;
1877 local_arg.classes = &classes;
1878 local_arg.success = false;
1879 // We size the array assuming classes won't be added to the class table during the visit.
1880 // If this assumption fails we iterate again.
1881 while (!local_arg.success) {
1882 size_t class_table_size;
1883 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001884 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001885 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001886 }
1887 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1888 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1889 classes.Assign(
1890 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1891 CHECK(classes.Get() != nullptr); // OOME.
1892 local_arg.index = 0;
1893 local_arg.success = true;
1894 VisitClasses(GetClassesVisitorArray, &local_arg);
1895 }
1896 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1897 // If the class table shrank during creation of the clases array we expect null elements. If
1898 // the class table grew then the loop repeats. If classes are created after the loop has
1899 // finished then we don't visit.
1900 mirror::Class* klass = classes->Get(i);
1901 if (klass != nullptr && !visitor(klass, arg)) {
1902 return;
1903 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001904 }
1905 }
1906}
1907
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001908ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001909 mirror::Class::ResetClass();
1910 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001911 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001912 mirror::ArtField::ResetClass();
1913 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001914 mirror::BooleanArray::ResetArrayClass();
1915 mirror::ByteArray::ResetArrayClass();
1916 mirror::CharArray::ResetArrayClass();
1917 mirror::DoubleArray::ResetArrayClass();
1918 mirror::FloatArray::ResetArrayClass();
1919 mirror::IntArray::ResetArrayClass();
1920 mirror::LongArray::ResetArrayClass();
1921 mirror::ShortArray::ResetArrayClass();
1922 mirror::Throwable::ResetClass();
1923 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001924 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001925}
1926
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001927mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001928 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001929 StackHandleScope<16> hs(self);
1930 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1931 Handle<mirror::DexCache> dex_cache(
1932 hs.NewHandle(down_cast<mirror::DexCache*>(
1933 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1934 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001935 if (dex_cache.Get() == nullptr) {
1936 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001937 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001938 Handle<mirror::String>
1939 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001940 if (location.Get() == nullptr) {
1941 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001942 }
Ian Rogers700a4022014-05-19 16:49:03 -07001943 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001944 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001945 if (strings.Get() == nullptr) {
1946 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001947 }
Ian Rogers700a4022014-05-19 16:49:03 -07001948 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001949 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001950 if (types.Get() == nullptr) {
1951 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001952 }
Ian Rogers700a4022014-05-19 16:49:03 -07001953 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001954 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001955 if (methods.Get() == nullptr) {
1956 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001957 }
Ian Rogers700a4022014-05-19 16:49:03 -07001958 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001959 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001960 if (fields.Get() == nullptr) {
1961 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001962 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001963 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1964 fields.Get());
1965 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001966}
1967
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001968mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001969 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001970 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001971 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001972 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001973 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001974 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1975 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001976 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001977 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001978 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001979 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001980 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001981}
1982
Ian Rogers6fac4472014-02-25 17:01:10 -08001983mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001984 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001985}
1986
Brian Carlstromea46f952013-07-30 01:26:50 -07001987mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001988 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001989 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001990}
1991
Brian Carlstromea46f952013-07-30 01:26:50 -07001992mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001993 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001994 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001995}
1996
Mathieu Chartier590fee92013-09-13 13:46:47 -07001997mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1998 Thread* self, size_t length) {
1999 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2000 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002001}
2002
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002003mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
2004 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002005 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002006
2007 // For temporary classes we must wait for them to be retired.
2008 if (init_done_ && klass->IsTemp()) {
2009 CHECK(!klass->IsResolved());
2010 if (klass->IsErroneous()) {
2011 ThrowEarlierClassFailure(klass);
2012 return nullptr;
2013 }
2014 StackHandleScope<1> hs(self);
2015 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2016 ObjectLock<mirror::Class> lock(self, h_class);
2017 // Loop and wait for the resolving thread to retire this class.
2018 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2019 lock.WaitIgnoringInterrupts();
2020 }
2021 if (h_class->IsErroneous()) {
2022 ThrowEarlierClassFailure(h_class.Get());
2023 return nullptr;
2024 }
2025 CHECK(h_class->IsRetired());
2026 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002027 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2028 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002029 }
2030
Brian Carlstromaded5f72011-10-07 17:15:04 -07002031 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002032 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002033 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002034 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2035 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002036 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002037 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2038 ThrowClassCircularityError(h_class.Get());
2039 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002040 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002041 }
2042 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002043 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002044 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002045 }
2046 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002047
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002048 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002049 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002050 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002051 }
2052 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002053 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002054 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002055 return klass;
2056}
2057
Ian Rogers68b56852014-08-29 20:19:11 -07002058typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2059
2060// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002061ClassPathEntry FindInClassPath(const char* descriptor,
2062 size_t hash, const std::vector<const DexFile*>& class_path) {
2063 for (const DexFile* dex_file : class_path) {
2064 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002065 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002066 return ClassPathEntry(dex_file, dex_class_def);
2067 }
2068 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002069 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002070}
2071
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002072mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2073 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002074 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002075 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08002076 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002077 if (class_loader->GetClass() !=
2078 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2079 class_loader->GetParent()->GetClass() !=
2080 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2081 return nullptr;
2082 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002083 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002084 // Check if this would be found in the parent boot class loader.
2085 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002086 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002087 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08002088 // May return null if resolution on another thread fails.
2089 klass = EnsureResolved(self, descriptor, klass);
2090 } else {
2091 // May OOME.
2092 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2093 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002094 }
Ian Rogers32427292014-11-19 14:05:21 -08002095 if (klass == nullptr) {
2096 CHECK(self->IsExceptionPending()) << descriptor;
2097 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002098 }
Ian Rogers32427292014-11-19 14:05:21 -08002099 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002100 } else {
Ian Rogers32427292014-11-19 14:05:21 -08002101 // Handle as if this is the child PathClassLoader.
2102 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002103 StackHandleScope<3> hs(self);
2104 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2105 // We need to get the DexPathList and loop through it.
2106 Handle<mirror::ArtField> cookie_field =
2107 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2108 Handle<mirror::ArtField> dex_file_field =
2109 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002110 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002111 mirror::Object* dex_path_list =
2112 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2113 GetObject(class_loader.Get());
2114 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2115 cookie_field.Get() != nullptr) {
2116 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2117 mirror::Object* dex_elements_obj =
2118 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2119 GetObject(dex_path_list);
2120 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2121 // at the mCookie which is a DexFile vector.
2122 if (dex_elements_obj != nullptr) {
2123 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2124 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2125 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2126 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2127 if (element == nullptr) {
2128 // Should never happen, fall back to java code to throw a NPE.
2129 break;
2130 }
2131 mirror::Object* dex_file = dex_file_field->GetObject(element);
2132 if (dex_file != nullptr) {
2133 const uint64_t cookie = cookie_field->GetLong(dex_file);
2134 auto* dex_files =
2135 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2136 if (dex_files == nullptr) {
2137 // This should never happen so log a warning.
2138 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2139 break;
2140 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002141 for (const DexFile* cp_dex_file : *dex_files) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002142 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002143 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002144 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002145 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2146 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002147 if (klass == nullptr) {
2148 CHECK(self->IsExceptionPending()) << descriptor;
2149 self->ClearException();
2150 return nullptr;
2151 }
2152 return klass;
2153 }
2154 }
2155 }
2156 }
2157 }
2158 }
Ian Rogers32427292014-11-19 14:05:21 -08002159 self->AssertNoPendingException();
2160 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002161 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002162}
2163
Ian Rogers98379392014-02-24 16:53:16 -08002164mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002165 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002166 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002167 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002168 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002169 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002170 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2171 // for primitive classes that aren't backed by dex files.
2172 return FindPrimitiveClass(descriptor[0]);
2173 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002174 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002175 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002176 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002177 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002178 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002179 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002180 // Class is not yet loaded.
2181 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002182 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002183 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002184 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002185 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002186 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002187 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002188 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002189 } else {
2190 // The boot class loader is searched ahead of the application class loader, failures are
2191 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2192 // trigger the chaining with a proper stack trace.
2193 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2194 self->SetException(ThrowLocation(), pre_allocated);
2195 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002196 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002197 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002198 // First try with the bootstrap class loader.
2199 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002200 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002201 if (klass != nullptr) {
2202 return EnsureResolved(self, descriptor, klass);
2203 }
2204 }
Ian Rogers63557452014-06-04 16:57:15 -07002205 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2206 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002207 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002208 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002209 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002210 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002211 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002212 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002213 const std::vector<const DexFile*>* class_path;
2214 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002215 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002216 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002217 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002218 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2219 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002220 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07002221 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002222 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07002223 } else {
2224 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2225 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2226 self->SetException(ThrowLocation(), pre_allocated);
2227 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002228 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002229 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002230 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002231 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2232 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002233 if (cp_klass != nullptr) {
2234 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002235 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002236 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002237 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002238 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002239 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002240 {
2241 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002242 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2243 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002244 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002245 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002246 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002247 }
Ian Rogers68b56852014-08-29 20:19:11 -07002248 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002249 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2250 WellKnownClasses::java_lang_ClassLoader_loadClass,
2251 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002252 }
Ian Rogers98379392014-02-24 16:53:16 -08002253 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002254 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002255 return nullptr;
2256 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002257 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002258 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002259 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002260 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002261 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002262 // success, return mirror::Class*
2263 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002264 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002265 }
Ian Rogers07140832014-09-30 15:43:59 -07002266 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002267}
2268
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002269mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002270 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002271 const DexFile& dex_file,
2272 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002273 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002274 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002275
Brian Carlstromaded5f72011-10-07 17:15:04 -07002276 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002277 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002278 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002279 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002280 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002281 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002282 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002283 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002284 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002285 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2286 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002287 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002288 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002289 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002290 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002291 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002292 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002293 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002294 }
2295
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002296 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002297 // Allocate a class with the status of not ready.
2298 // Interface object should get the right size here. Regular class will
2299 // figure out the right size later and be replaced with one of the right
2300 // size when the class becomes resolved.
2301 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002302 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002303 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002304 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002305 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002306 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002307 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002308 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002309 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002310 if (self->IsExceptionPending()) {
2311 // An exception occured during load, set status to erroneous while holding klass' lock in case
2312 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002313 if (!klass->IsErroneous()) {
2314 klass->SetStatus(mirror::Class::kStatusError, self);
2315 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002316 return nullptr;
2317 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002318 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002319
Mathieu Chartier590fee92013-09-13 13:46:47 -07002320 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002321 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002322 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002323 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2324 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002325 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002326 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002327
Brian Carlstromaded5f72011-10-07 17:15:04 -07002328 // Finish loading (if necessary) by finding parents
2329 CHECK(!klass->IsLoaded());
2330 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2331 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002332 if (!klass->IsErroneous()) {
2333 klass->SetStatus(mirror::Class::kStatusError, self);
2334 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002335 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002336 }
2337 CHECK(klass->IsLoaded());
2338 // Link the class (if necessary)
2339 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002340 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002341 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002342
2343 mirror::Class* new_class = nullptr;
2344 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002345 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002346 if (!klass->IsErroneous()) {
2347 klass->SetStatus(mirror::Class::kStatusError, self);
2348 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002349 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002350 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002351 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002352 CHECK(new_class != nullptr) << descriptor;
2353 CHECK(new_class->IsResolved()) << descriptor;
2354
2355 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002356
Sebastien Hertza8a697f2015-01-15 12:28:47 +01002357 // Instrumentation may have updated entrypoints for all methods of all
2358 // classes. However it could not update methods of this class while we
2359 // were loading it. Now the class is resolved, we can update entrypoints
2360 // as required by instrumentation.
2361 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2362 // We must be in the kRunnable state to prevent instrumentation from
2363 // suspending all threads to update entrypoints while we are doing it
2364 // for this class.
2365 DCHECK_EQ(self->GetState(), kRunnable);
2366 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(new_class_h.Get());
2367 }
2368
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002369 /*
2370 * We send CLASS_PREPARE events to the debugger from here. The
2371 * definition of "preparation" is creating the static fields for a
2372 * class and initializing them to the standard default values, but not
2373 * executing any code (that comes later, during "initialization").
2374 *
2375 * We did the static preparation in LinkClass.
2376 *
2377 * The class has been prepared and resolved but possibly not yet verified
2378 * at this point.
2379 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002380 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002381
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002382 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002383}
2384
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002385uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2386 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002387 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002388 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002389 size_t num_8 = 0;
2390 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002391 size_t num_32 = 0;
2392 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002393 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002394 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2395 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002396 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002397 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002398 switch (c) {
2399 case 'L':
2400 case '[':
2401 num_ref++;
2402 break;
2403 case 'J':
2404 case 'D':
2405 num_64++;
2406 break;
2407 case 'I':
2408 case 'F':
2409 num_32++;
2410 break;
2411 case 'S':
2412 case 'C':
2413 num_16++;
2414 break;
2415 case 'B':
2416 case 'Z':
2417 num_8++;
2418 break;
2419 default:
2420 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002421 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002422 }
2423 }
2424 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002425 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002426}
2427
Ian Rogers97b52f82014-08-14 11:34:07 -07002428OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2429 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002430 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002431 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2432 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002433 *found = false;
2434 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002435 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002436 *found = true;
2437 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002438}
2439
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002440static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2441 uint32_t method_idx) {
2442 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002443 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002444 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002445 ClassDataItemIterator it(dex_file, class_data);
2446 // Skip fields
2447 while (it.HasNextStaticField()) {
2448 it.Next();
2449 }
2450 while (it.HasNextInstanceField()) {
2451 it.Next();
2452 }
2453 // Process methods
2454 size_t class_def_method_index = 0;
2455 while (it.HasNextDirectMethod()) {
2456 if (it.GetMemberIndex() == method_idx) {
2457 return class_def_method_index;
2458 }
2459 class_def_method_index++;
2460 it.Next();
2461 }
2462 while (it.HasNextVirtualMethod()) {
2463 if (it.GetMemberIndex() == method_idx) {
2464 return class_def_method_index;
2465 }
2466 class_def_method_index++;
2467 it.Next();
2468 }
2469 DCHECK(!it.HasNext());
2470 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08002471 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002472}
2473
Ian Rogers97b52f82014-08-14 11:34:07 -07002474const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002475 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002476 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002477 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002478 size_t oat_method_index;
2479 if (method->IsStatic() || method->IsDirect()) {
2480 // Simple case where the oat method index was stashed at load time.
2481 oat_method_index = method->GetMethodIndex();
2482 } else {
2483 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2484 // by search for its position in the declared virtual methods.
2485 oat_method_index = declaring_class->NumDirectMethods();
2486 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002487 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002488 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002489 // Check method index instead of identity in case of duplicate method definitions.
2490 if (method->GetDexMethodIndex() ==
2491 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002492 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002493 break;
2494 }
Ian Rogersf320b632012-03-13 18:47:47 -07002495 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002496 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002497 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2498 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002499 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002500 DCHECK_EQ(oat_method_index,
2501 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002502 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002503 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002504 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2505 declaring_class->GetDexClassDefIndex(),
2506 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002507 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002508 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002509 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002510 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002511}
2512
2513// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002514const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002515 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002516 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002517 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002518 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002519 bool found;
2520 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002521 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002522 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002523 result = oat_method.GetQuickCode();
2524 }
2525
Ian Rogersef7d42f2014-01-06 12:55:46 -08002526 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002527 if (method->IsNative()) {
2528 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002529 result = GetQuickGenericJniStub();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002530 } else {
2531 // No code? You must mean to go into the interpreter.
2532 result = GetQuickToInterpreterBridge();
2533 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002534 }
2535 return result;
TDYa12785321912012-04-01 15:24:56 -07002536}
2537
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002538const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2539 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2540 return nullptr;
2541 }
2542 bool found;
2543 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2544 return found ? oat_method.GetQuickCode() : nullptr;
2545}
2546
Ian Rogersef7d42f2014-01-06 12:55:46 -08002547const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2548 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002549 bool found;
2550 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2551 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002552 return nullptr;
2553 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002554 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002555 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002556}
2557
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002558// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08002559static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07002560 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08002561 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002562 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002563 // May return true for native code, in the case of generic JNI
2564 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002565 return true;
2566 }
2567 // If interpreter mode is enabled, every method (except native and proxy) must
2568 // be run with interpreter.
2569 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2570 !method->IsNative() && !method->IsProxyMethod();
2571}
2572
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002573void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002574 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002575 if (klass->NumDirectMethods() == 0) {
2576 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002577 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002578 Runtime* runtime = Runtime::Current();
2579 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002580 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2581 return; // OAT file unavailable.
2582 }
Ian Rogers19846512012-02-24 11:42:47 -08002583 }
Alex Light64ad14d2014-08-19 14:23:13 -07002584
Mathieu Chartierf8322842014-05-16 10:59:25 -07002585 const DexFile& dex_file = klass->GetDexFile();
2586 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002587 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002588 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002589 // There should always be class data if there were direct methods.
2590 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002591 ClassDataItemIterator it(dex_file, class_data);
2592 // Skip fields
2593 while (it.HasNextStaticField()) {
2594 it.Next();
2595 }
2596 while (it.HasNextInstanceField()) {
2597 it.Next();
2598 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002599 bool has_oat_class;
2600 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2601 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002602 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002603 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002604 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002605 if (!method->IsStatic()) {
2606 // Only update static methods.
2607 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002608 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002609 const void* quick_code = nullptr;
2610 if (has_oat_class) {
2611 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002612 quick_code = oat_method.GetQuickCode();
2613 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002614 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002615 if (enter_interpreter) {
2616 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002617 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08002618 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002619 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08002620 } else {
2621 quick_code = GetQuickToInterpreterBridge();
2622 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002623 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002624 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08002625 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002626 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002627}
2628
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002629void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002630 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002631 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002632 Runtime* runtime = Runtime::Current();
2633 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002634 // The following code only applies to a non-compiler runtime.
2635 return;
2636 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002637 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002638 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002639 if (oat_class != nullptr) {
2640 // Every kind of method should at least get an invoke stub from the oat_method.
2641 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002642 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002643 oat_method.LinkMethod(method.Get());
2644 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002645
Jeff Hao16743632013-05-08 10:59:04 -07002646 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002647 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08002648 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002649 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002650 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002651 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002652 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002653 }
2654
Brian Carlstrom92827a52011-10-10 15:50:01 -07002655 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002656 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002657 return;
2658 }
Ian Rogers19846512012-02-24 11:42:47 -08002659
2660 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002661 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002662 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2663 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002664 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002665 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002666 if (!method->IsNative()) {
2667 // Set entry point from compiled code if there's no code or in interpreter only mode.
2668 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002669 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002670 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002671 }
Ian Rogers0d6de042012-02-29 08:50:26 -08002672 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002673
Ian Rogers62d6c772013-02-27 08:32:07 -08002674 if (method->IsNative()) {
2675 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002676 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002677
2678 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002679 // We have a native method here without code. Then it should have either the generic JNI
2680 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2681 // TODO: this doesn't handle all the cases where trampolines may be installed.
2682 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2683 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002684 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002685 }
2686}
2687
Fred Shih37f05ef2014-07-16 18:38:08 -07002688
Fred Shih37f05ef2014-07-16 18:38:08 -07002689
Ian Rogers7b078e82014-09-10 14:44:24 -07002690void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002691 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002692 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002693 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002694 CHECK(klass.Get() != nullptr);
2695 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002696 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002697 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002698 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002699
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002700 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07002701 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002702 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002703 klass->SetAccessFlags(access_flags);
2704 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002705 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002706 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002707
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002708 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002709 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002710 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002711
Ian Rogers13735952014-10-08 12:43:28 -07002712 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002713 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002714 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002715 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002716
Ian Rogers97b52f82014-08-14 11:34:07 -07002717
2718 bool has_oat_class = false;
2719 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2720 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2721 &has_oat_class);
2722 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002723 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002724 }
2725 }
2726 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002727 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002728 }
2729}
2730
Ian Rogers7b078e82014-09-10 14:44:24 -07002731void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002732 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002733 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002734 const OatFile::OatClass* oat_class) {
2735 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002736 ClassDataItemIterator it(dex_file, class_data);
2737 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002738 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002739 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002740 CHECK(self->IsExceptionPending()); // OOME.
2741 return;
2742 }
2743 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002744 }
2745 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002746 mirror::ObjectArray<mirror::ArtField>* fields =
2747 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002748 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002749 CHECK(self->IsExceptionPending()); // OOME.
2750 return;
2751 }
2752 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002753 }
2754 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002755 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002756 StackHandleScope<1> hs(self);
2757 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002758 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002759 CHECK(self->IsExceptionPending()); // OOME.
2760 return;
2761 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002762 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002763 LoadField(dex_file, it, klass, sfield);
2764 }
2765 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002766 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002767 StackHandleScope<1> hs(self);
2768 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002769 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002770 CHECK(self->IsExceptionPending()); // OOME.
2771 return;
2772 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002773 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002774 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002775 }
2776
Ian Rogers0571d352011-11-03 19:51:38 -07002777 // Load methods.
2778 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002779 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002780 mirror::ObjectArray<mirror::ArtMethod>* directs =
2781 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002782 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002783 CHECK(self->IsExceptionPending()); // OOME.
2784 return;
2785 }
2786 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002787 }
Ian Rogers0571d352011-11-03 19:51:38 -07002788 if (it.NumVirtualMethods() != 0) {
2789 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002790 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2791 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002792 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002793 CHECK(self->IsExceptionPending()); // OOME.
2794 return;
2795 }
2796 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002797 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002798 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002799 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2800 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002801 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002802 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002803 StackHandleScope<1> hs(self);
2804 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002805 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002806 CHECK(self->IsExceptionPending()); // OOME.
2807 return;
2808 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002809 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002810 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002811 uint32_t it_method_index = it.GetMemberIndex();
2812 if (last_dex_method_index == it_method_index) {
2813 // duplicate case
2814 method->SetMethodIndex(last_class_def_method_index);
2815 } else {
2816 method->SetMethodIndex(class_def_method_index);
2817 last_dex_method_index = it_method_index;
2818 last_class_def_method_index = class_def_method_index;
2819 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002820 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002821 }
2822 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002823 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002824 StackHandleScope<1> hs(self);
2825 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002826 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002827 CHECK(self->IsExceptionPending()); // OOME.
2828 return;
2829 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002830 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002831 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002832 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002833 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002834 }
2835 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002836}
2837
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002838void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002839 Handle<mirror::Class> klass,
2840 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002841 uint32_t field_idx = it.GetMemberIndex();
2842 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002843 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002844 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002845}
2846
Brian Carlstromea46f952013-07-30 01:26:50 -07002847mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002848 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002849 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002850 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002851 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002852 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002853
Brian Carlstromea46f952013-07-30 01:26:50 -07002854 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002855 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002856 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002857 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002858 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002859 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002860
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002861 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002862 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002863 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002864 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002865
Ian Rogers19846512012-02-24 11:42:47 -08002866 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002867 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002868
Andreas Gampe51829322014-08-25 15:05:04 -07002869 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002870
Ian Rogersdfb325e2013-10-30 01:00:44 -07002871 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002872 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002873 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2874 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002875 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002876 klass->SetFinalizable();
2877 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002878 std::string temp;
2879 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002880 // The Enum class declares a "final" finalize() method to prevent subclasses from
2881 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2882 // subclasses, so we exclude it here.
2883 // We also want to avoid setting the flag on Object, where we know that finalize() is
2884 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002885 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2886 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002887 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002888 }
2889 }
2890 }
2891 } else if (method_name[0] == '<') {
2892 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002893 bool is_init = (strcmp("<init>", method_name) == 0);
2894 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002895 if (UNLIKELY(!is_init && !is_clinit)) {
2896 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2897 } else {
2898 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2899 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002900 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002901 access_flags |= kAccConstructor;
2902 }
2903 }
2904 }
2905 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002906
Mathieu Chartier66f19252012-09-18 08:57:04 -07002907 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002908}
2909
Ian Rogers7b078e82014-09-10 14:44:24 -07002910void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002911 StackHandleScope<1> hs(self);
2912 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002913 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2914 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002915 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002916}
2917
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002918void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002919 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002920 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002921 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002922 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002923}
2924
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002925bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002926 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002927 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002928 mirror::DexCache* dex_cache = GetDexCache(i);
2929 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002930 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002931 }
2932 }
2933 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002934}
2935
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002936bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002937 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002938 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002939}
2940
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002941void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002942 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002943 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002944 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002945 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2946 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002947 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002948 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002949 if (log_new_dex_caches_roots_) {
2950 // TODO: This is not safe if we can remove dex caches.
2951 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2952 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002953}
2954
Brian Carlstromaded5f72011-10-07 17:15:04 -07002955void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002956 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002957 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002958 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002959 if (IsDexFileRegisteredLocked(dex_file)) {
2960 return;
2961 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002962 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002963 // Don't alloc while holding the lock, since allocation may need to
2964 // suspend all threads and another thread may need the dex_lock_ to
2965 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002966 StackHandleScope<1> hs(self);
2967 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002968 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2969 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002970 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002971 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002972 if (IsDexFileRegisteredLocked(dex_file)) {
2973 return;
2974 }
2975 RegisterDexFileLocked(dex_file, dex_cache);
2976 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002977}
2978
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002979void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002980 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002981 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002982 RegisterDexFileLocked(dex_file, dex_cache);
2983}
2984
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002985mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002986 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002987 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002988 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002989 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002990 if (dex_cache->GetDexFile() == &dex_file) {
2991 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002992 }
2993 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002994 // Search matching by location name.
2995 std::string location(dex_file.GetLocation());
2996 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002997 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002998 if (dex_cache->GetDexFile()->GetLocation() == location) {
2999 return dex_cache;
3000 }
3001 }
3002 // Failure, dump diagnostic and abort.
3003 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003004 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003005 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3006 }
3007 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003008 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003009}
3010
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003011void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003012 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003013 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003014 mirror::DexCache* dex_cache = GetDexCache(i);
3015 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003016 }
3017}
3018
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003019mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003020 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003021 if (UNLIKELY(klass == nullptr)) {
3022 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003023 }
3024 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003025}
3026
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003027mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3028 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003029 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003030 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003031 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003032 StackHandleScope<1> hs(self);
3033 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003034 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003035 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003036 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003037 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3038 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003039 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3040 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003041 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003042 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003043}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003044
Brian Carlstrombe977852011-07-19 14:54:54 -07003045// Create an array class (i.e. the class object for the array, not the
3046// array itself). "descriptor" looks like "[C" or "[[[[B" or
3047// "[Ljava/lang/String;".
3048//
3049// If "descriptor" refers to an array of primitives, look up the
3050// primitive type's internally-generated class object.
3051//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003052// "class_loader" is the class loader of the class that's referring to
3053// us. It's used to ensure that we're looking for the element type in
3054// the right context. It does NOT become the class loader for the
3055// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003056//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003057// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003058mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003059 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003060 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003061 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003062 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003063 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3064 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003065 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003066 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003067 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003068 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3069 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003070 if (component_type.Get() == nullptr) {
3071 DCHECK(self->IsExceptionPending());
3072 return nullptr;
3073 } else {
3074 self->ClearException();
3075 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003076 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003077 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3078 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3079 return nullptr;
3080 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003081 // See if the component type is already loaded. Array classes are
3082 // always associated with the class loader of their underlying
3083 // element type -- an array of Strings goes with the loader for
3084 // java/lang/String -- so we need to look for it there. (The
3085 // caller should have checked for the existence of the class
3086 // before calling here, but they did so with *their* class loader,
3087 // not the component type's loader.)
3088 //
3089 // If we find it, the caller adds "loader" to the class' initiating
3090 // loader list, which should prevent us from going through this again.
3091 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003092 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003093 // are the same, because our caller (FindClass) just did the
3094 // lookup. (Even if we get this wrong we still have correct behavior,
3095 // because we effectively do this lookup again when we add the new
3096 // class to the hash table --- necessary because of possible races with
3097 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003098 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003099 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003100 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003101 return new_class;
3102 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003103 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003104
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003105 // Fill out the fields in the Class.
3106 //
3107 // It is possible to execute some methods against arrays, because
3108 // all arrays are subclasses of java_lang_Object_, so we need to set
3109 // up a vtable. We can just point at the one in java_lang_Object_.
3110 //
3111 // Array classes are simple enough that we don't need to do a full
3112 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003113 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003114 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003115 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003116 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003117 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003118 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003119 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003120 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003121 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003122 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003123 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003124 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003125 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003126 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003127 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003128 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003129 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003130 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003131 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003132 }
3133 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003134 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003135 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003136 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003137 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003138 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003139 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003140 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003141 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003142 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003143 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003144 new_class->SetSuperClass(java_lang_Object);
3145 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003146 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003147 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003148 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003149 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003150 StackHandleScope<mirror::Class::kImtSize> hs2(self,
3151 Runtime::Current()->GetImtUnimplementedMethod());
3152 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003153 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003154 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003155 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003156 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003157
3158
3159 // All arrays have java/lang/Cloneable and java/io/Serializable as
3160 // interfaces. We need to set that up here, so that stuff like
3161 // "instanceof" works right.
3162 //
3163 // Note: The GC could run during the call to FindSystemClass,
3164 // so we need to make sure the class object is GC-valid while we're in
3165 // there. Do this by clearing the interface list so the GC will just
3166 // think that the entries are null.
3167
3168
3169 // Use the single, global copies of "interfaces" and "iftable"
3170 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003171 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003172 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003173 CHECK(array_iftable != nullptr);
3174 new_class->SetIfTable(array_iftable);
3175 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003176
Elliott Hughes00626c22013-06-14 15:04:14 -07003177 // Inherit access flags from the component type.
3178 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3179 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3180 access_flags &= kAccJavaFlagsMask;
3181 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003182 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003183 access_flags |= kAccAbstract | kAccFinal;
3184 access_flags &= ~kAccInterface;
3185
3186 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003187
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003188 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003189 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003190 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003191 }
3192 // Another thread must have loaded the class after we
3193 // started but before we finished. Abandon what we've
3194 // done.
3195 //
3196 // (Yes, this happens.)
3197
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003198 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003199}
3200
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003201mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003202 switch (type) {
3203 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003204 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003205 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003206 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003207 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003208 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003209 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003210 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003211 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003212 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003213 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003214 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003215 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003216 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003217 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003218 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003219 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003220 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003221 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003222 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003223 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003224 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003225 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003226 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003227}
3228
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003229mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3230 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003231 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003232 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003233 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003234 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003235 source += " from ";
3236 source += dex_cache->GetLocation()->ToModifiedUtf8();
3237 }
3238 LOG(INFO) << "Loaded class " << descriptor << source;
3239 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003240 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003241 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003242 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003243 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003244 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003245 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003246 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003247 // Check a class loaded with the system class loader matches one in the image if the class
3248 // is in the image.
3249 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003250 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003251 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003252 }
3253 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003254 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003255 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003256 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003257 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003258 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003259 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003260}
3261
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003262mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3263 size_t hash) {
3264 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003265 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3266 hash);
3267 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003268 CHECK(klass->IsProxyClass());
3269 return nullptr;
3270 }
3271
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003272 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003273 CHECK_NE(existing, klass) << descriptor;
3274 CHECK(!existing->IsResolved()) << descriptor;
3275 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3276
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003277 CHECK(!klass->IsTemp()) << descriptor;
3278 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3279 dex_cache_image_class_lookup_required_) {
3280 // Check a class loaded with the system class loader matches one in the image if the class
3281 // is in the image.
3282 existing = LookupClassFromImage(descriptor);
3283 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003284 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003285 }
3286 }
3287 VerifyObject(klass);
3288
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003289 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003290 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003291 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003292 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003293 }
3294
3295 return existing;
3296}
3297
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003298bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003299 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003300 auto pair = std::make_pair(descriptor, class_loader);
3301 auto it = class_table_.Find(pair);
3302 if (it != class_table_.end()) {
3303 class_table_.Erase(it);
3304 return true;
3305 }
3306 it = pre_zygote_class_table_.Find(pair);
3307 if (it != pre_zygote_class_table_.end()) {
3308 pre_zygote_class_table_.Erase(it);
3309 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003310 }
3311 return false;
3312}
3313
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003314mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003315 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003316 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003317 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003318 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003319 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003320 return result;
3321 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003322 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003323 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3324 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003325 } else {
3326 // Lookup failed but need to search dex_caches_.
3327 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003328 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003329 InsertClass(descriptor, result, hash);
3330 } else {
3331 // Searching the image dex files/caches failed, we don't want to get into this situation
3332 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3333 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003334 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003335 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3336 MoveImageClassesToClassTable();
3337 }
3338 }
3339 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003340 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003341}
3342
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003343mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003344 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003345 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003346 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3347 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3348 if (it == pre_zygote_class_table_.end()) {
3349 it = class_table_.FindWithHash(descriptor_pair, hash);
3350 if (it == class_table_.end()) {
3351 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003352 }
3353 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003354 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003355}
3356
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003357static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3358 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3359 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003360 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003361 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3362 return root->AsObjectArray<mirror::DexCache>();
3363}
3364
3365void ClassLinker::MoveImageClassesToClassTable() {
3366 Thread* self = Thread::Current();
3367 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3368 if (!dex_cache_image_class_lookup_required_) {
3369 return; // All dex cache classes are already in the class table.
3370 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003371 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003372 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003373 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003374 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3375 mirror::DexCache* dex_cache = dex_caches->Get(i);
3376 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3377 for (int32_t j = 0; j < types->GetLength(); j++) {
3378 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003379 if (klass != nullptr) {
3380 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003381 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003382 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003383 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3384 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003385 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003386 << PrettyClassAndClassLoader(klass);
3387 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003388 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003389 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003390 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003391 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003392 }
3393 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003394 }
3395 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003396 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003397}
3398
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003399void ClassLinker::MoveClassTableToPreZygote() {
3400 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3401 DCHECK(pre_zygote_class_table_.Empty());
3402 pre_zygote_class_table_ = std::move(class_table_);
3403 class_table_.Clear();
3404}
3405
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003406mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003407 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003408 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3409 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3410 mirror::DexCache* dex_cache = dex_caches->Get(i);
3411 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003412 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003413 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003414 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003415 const DexFile::TypeId* type_id =
3416 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003417 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003418 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3419 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003420 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003421 return klass;
3422 }
3423 }
3424 }
3425 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003426 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003427}
3428
3429void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3430 result.clear();
3431 if (dex_cache_image_class_lookup_required_) {
3432 MoveImageClassesToClassTable();
3433 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003434 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3435 while (true) {
3436 auto it = class_table_.Find(descriptor);
3437 if (it == class_table_.end()) {
3438 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003439 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003440 result.push_back(it->Read());
3441 class_table_.Erase(it);
3442 }
3443 for (mirror::Class* k : result) {
3444 class_table_.Insert(GcRoot<mirror::Class>(k));
3445 }
3446 size_t pre_zygote_start = result.size();
3447 // Now handle the pre zygote table.
3448 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3449 // called from the debugger.
3450 while (true) {
3451 auto it = pre_zygote_class_table_.Find(descriptor);
3452 if (it == pre_zygote_class_table_.end()) {
3453 break;
3454 }
3455 result.push_back(it->Read());
3456 pre_zygote_class_table_.Erase(it);
3457 }
3458 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3459 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003460 }
3461}
3462
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003463void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003464 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003465 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003466
Ian Rogers9ffb0392012-09-10 11:56:50 -07003467 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003468 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003469 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003470 return;
3471 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003472 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3473 return;
3474 }
jeffhao98eacac2011-09-14 16:11:53 -07003475
Ian Rogers9ffb0392012-09-10 11:56:50 -07003476 // The class might already be erroneous, for example at compile time if we attempted to verify
3477 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003478 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003479 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003480 return;
3481 }
3482
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003483 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003484 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003485 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003486 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003487 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003488 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003489 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003490 }
jeffhao98eacac2011-09-14 16:11:53 -07003491
Jeff Hao4a200f52014-04-01 14:58:49 -07003492 // Skip verification if disabled.
3493 if (!Runtime::Current()->IsVerificationEnabled()) {
3494 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003495 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003496 return;
3497 }
3498
Ian Rogers9ffb0392012-09-10 11:56:50 -07003499 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003500 StackHandleScope<2> hs(self);
3501 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003502 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003503 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003504 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003505
3506 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003507 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003508 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003509 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003510 std::string error_msg(
3511 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3512 PrettyDescriptor(klass.Get()).c_str(),
3513 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08003514 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003515 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3516 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003517 self->ClearException();
3518 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003519 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3520 if (cause.Get() != nullptr) {
3521 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003522 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003523 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003524 if (Runtime::Current()->IsCompiler()) {
3525 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3526 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003527 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003528 return;
3529 }
3530 }
3531
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003532 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003533 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003534 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003535 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003536 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003537 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003538 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003539 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003540 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3541 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003542 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003543 return;
3544 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003545 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003546 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003547 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003548 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003549 Runtime::Current()->IsCompiler(),
3550 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003551 }
3552 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003553 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003554 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003555 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3556 << " because: " << error_msg;
3557 }
Ian Rogers1f539342012-10-03 21:09:42 -07003558 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003559 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003560 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003561 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003562 // Even though there were no verifier failures we need to respect whether the super-class
3563 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003564 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003565 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003566 } else {
3567 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003568 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003569 // Pretend a soft failure occured so that we don't consider the class verified below.
3570 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003571 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003572 } else {
3573 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3574 // Soft failures at compile time should be retried at runtime. Soft
3575 // failures at runtime will be handled by slow paths in the generated
3576 // code. Set status accordingly.
3577 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003578 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003579 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003580 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003581 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3582 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003583 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003584 }
3585 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003586 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08003587 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003588 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3589 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003590 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003591 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003592 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003593 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003594 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003595 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003596 // Let the interpreter know it by setting the kAccPreverified flag onto each
3597 // method.
3598 // Note: we're going here during compilation and at runtime. When we set the
3599 // kAccPreverified flag when compiling image classes, the flag is recorded
3600 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003601 EnsurePreverifiedMethods(klass);
3602 }
3603}
3604
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003605void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003606 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003607 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003608 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003609 }
jeffhao98eacac2011-09-14 16:11:53 -07003610}
3611
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003612bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3613 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003614 // If we're compiling, we can only verify the class using the oat file if
3615 // we are not compiling the image or if the class we're verifying is not part of
3616 // the app. In other words, we will only check for preverification of bootclasspath
3617 // classes.
3618 if (Runtime::Current()->IsCompiler()) {
3619 // Are we compiling the bootclasspath?
3620 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3621 return false;
3622 }
3623 // We are compiling an app (not the image).
3624
3625 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003626 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003627 return false;
3628 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003629 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003630
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003631 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003632 // In case we run without an image there won't be a backing oat file.
3633 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003634 return false;
3635 }
3636
Andreas Gampe76bd8802014-12-10 16:43:58 -08003637 // We may be running with a preopted oat file but without image. In this case,
3638 // we don't skip verification of preverified classes to ensure we initialize
3639 // dex caches with all types resolved during verification.
3640 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
3641 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
3642 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
3643 // already pre-opted, as then the runtime is started.
3644 if (!Runtime::Current()->IsCompiler() &&
3645 !Runtime::Current()->GetHeap()->HasImageSpace() &&
3646 klass->GetClassLoader() != nullptr) {
3647 return false;
3648 }
3649
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003650 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003651 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003652 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3653 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003654 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003655 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003656 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003657 // Compile time verification failed with a soft error. Compile time verification can fail
3658 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003659 // class ... {
3660 // Foo x;
3661 // .... () {
3662 // if (...) {
3663 // v1 gets assigned a type of resolved class Foo
3664 // } else {
3665 // v1 gets assigned a type of unresolved class Bar
3666 // }
3667 // iput x = v1
3668 // } }
3669 // when we merge v1 following the if-the-else it results in Conflict
3670 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3671 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3672 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3673 // at compile time).
3674 return false;
3675 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003676 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003677 // Compile time verification failed with a hard error. This is caused by invalid instructions
3678 // in the class. These errors are unrecoverable.
3679 return false;
3680 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003681 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003682 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3683 // not loading the class.
3684 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3685 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003686 return false;
3687 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003688 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003689 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003690 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003691 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003692 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003693}
3694
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003695void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003696 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003697 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3698 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3699 }
3700 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3701 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3702 }
3703}
3704
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003705void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003706 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003707 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3708 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003709 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003710 return; // native or abstract method
3711 }
3712 if (code_item->tries_size_ == 0) {
3713 return; // nothing to process
3714 }
Ian Rogers13735952014-10-08 12:43:28 -07003715 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003716 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3717 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3718 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3719 CatchHandlerIterator iterator(handlers_ptr);
3720 for (; iterator.HasNext(); iterator.Next()) {
3721 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3722 // unresolved exception types will be ignored by exception delivery
3723 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003724 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003725 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003726 DCHECK(Thread::Current()->IsExceptionPending());
3727 Thread::Current()->ClearException();
3728 }
3729 }
3730 }
3731 handlers_ptr = iterator.EndDataPointer();
3732 }
3733}
3734
Brian Carlstromea46f952013-07-30 01:26:50 -07003735static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003736static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3737 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003738
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003739mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003740 jobjectArray interfaces, jobject loader,
3741 jobjectArray methods, jobjectArray throws) {
3742 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003743 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003744 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003745 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003746 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003747 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003748 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003749 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003750 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003751 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003752 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3753 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003754 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003755 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003756 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003757 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003758 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003759 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003760
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003761 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003762 {
3763 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003764 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003765 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003766 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003767 }
3768 klass->SetSFields(sfields);
3769 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003770 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3771 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003772 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3773 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003774 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003775 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003776 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003777 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003778 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003779 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003780 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3781 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003782 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3783 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003784 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003785 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003786 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003787 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003788 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003789 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003790 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003791
Ian Rogers466bb252011-10-14 03:29:56 -07003792 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003793 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003794 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003795 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003796 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003797 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003798 }
3799 klass->SetDirectMethods(directs);
3800 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003801 if (UNLIKELY(constructor == 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->SetDirectMethod(0, constructor);
3806 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003807
Mathieu Chartier590fee92013-09-13 13:46:47 -07003808 // Create virtual method using specified prototypes.
3809 size_t num_virtual_methods =
3810 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003811 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003812 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3813 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003814 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003815 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003816 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003817 }
3818 klass->SetVirtualMethods(virtuals);
3819 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003820 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003821 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003822 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3823 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003824 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003825 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003826 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003827 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003828 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003829 }
3830 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003831 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003832
3833 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003834 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003835 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003836
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003837 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3838 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003839 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003840 // Must hold lock on object when resolved.
3841 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003842 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003843 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003844 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003845 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003846 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003847 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003848 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003849 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003850
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003851 CHECK(klass->IsRetired());
3852 CHECK_NE(klass.Get(), new_class);
3853 klass.Assign(new_class);
3854
3855 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003856 interfaces_sfield->SetObject<false>(klass.Get(),
3857 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003858 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003859 throws_sfield->SetObject<false>(klass.Get(),
3860 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003861
3862 {
3863 // Lock on klass is released. Lock new class object.
3864 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003865 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003866 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003867
3868 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003869 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003870 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003871 CheckProxyConstructor(klass->GetDirectMethod(0));
3872 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003873 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003874 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3875 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003876 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3877 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003878 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003879 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003880
Mathieu Chartier590fee92013-09-13 13:46:47 -07003881 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003882 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003883 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003884 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3885
3886 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003887 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003888 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003889
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003890 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003891 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003892 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003893 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003894 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003895 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3896 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003897 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003898 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003899}
3900
Ian Rogersef7d42f2014-01-06 12:55:46 -08003901std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003902 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003903 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003904 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003905 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3906}
3907
Ian Rogersef7d42f2014-01-06 12:55:46 -08003908mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3909 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003910 DCHECK(proxy_class->IsProxyClass());
3911 DCHECK(proxy_method->IsProxyMethod());
3912 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003913 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003914 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003915 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003916 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003917 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003918 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003919 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003920 break;
3921 }
3922 }
3923 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003924 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003925 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003926 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003927 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003928 return resolved_method;
3929}
3930
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003931
Brian Carlstromea46f952013-07-30 01:26:50 -07003932mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003933 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003934 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003935 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003936 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003937 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003938 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3939 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003940 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3941 // constructor method.
3942 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3943 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003944 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3945 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003946 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3947 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003948 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003949 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003950 }
Ian Rogers466bb252011-10-14 03:29:56 -07003951 // Make this constructor public and fix the class to be our Proxy version
3952 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003953 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003954 return constructor;
3955}
3956
Brian Carlstromea46f952013-07-30 01:26:50 -07003957static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003958 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003959 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003960 CHECK_STREQ(constructor->GetName(), "<init>");
3961 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3962 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003963 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003964}
3965
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003966mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003967 Handle<mirror::Class> klass,
3968 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003969 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3970 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003971 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003972 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003973 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003974 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003975 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003976 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003977 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003978 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003979 }
Ian Rogers466bb252011-10-14 03:29:56 -07003980
3981 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3982 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003983 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003984 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003985
Ian Rogers466bb252011-10-14 03:29:56 -07003986 // At runtime the method looks like a reference and argument saving method, clone the code
3987 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003988 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003989 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003990
Ian Rogersc2b44472011-12-14 21:17:17 -08003991 return method;
3992}
Jesse Wilson95caa792011-10-12 18:14:17 -04003993
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003994static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3995 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003996 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003997 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003998 CHECK(!prototype->IsFinal());
3999 CHECK(method->IsFinal());
4000 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004001
4002 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4003 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07004004 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4005 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004006 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4007
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004008 CHECK_STREQ(method->GetName(), prototype->GetName());
4009 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004010 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004011 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004012}
4013
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004014static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4015 bool can_init_parents)
4016 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004017 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004018 return true;
4019 }
4020 if (!can_init_statics) {
4021 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004022 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004023 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004024 return false;
4025 }
4026 // Check if there are encoded static values needing initialization.
4027 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004028 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004029 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004030 if (dex_class_def->static_values_off_ != 0) {
4031 return false;
4032 }
4033 }
4034 }
4035 if (!klass->IsInterface() && klass->HasSuperClass()) {
4036 mirror::Class* super_class = klass->GetSuperClass();
4037 if (!can_init_parents && !super_class->IsInitialized()) {
4038 return false;
4039 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004040 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004041 return false;
4042 }
4043 }
4044 }
4045 return true;
4046}
4047
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004048bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004049 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004050 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4051
4052 // Are we already initialized and therefore done?
4053 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4054 // an initialized class will never change its state.
4055 if (klass->IsInitialized()) {
4056 return true;
4057 }
4058
4059 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004060 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004061 return false;
4062 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004063
Ian Rogers7b078e82014-09-10 14:44:24 -07004064 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004065 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004066 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004067 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004068
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004069 // Re-check under the lock in case another thread initialized ahead of us.
4070 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004071 return true;
4072 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004073
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004074 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004075 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004076 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004077 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004078 return false;
4079 }
4080
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004081 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004082
4083 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004084 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004085 if (!klass->IsVerified()) {
4086 // We failed to verify, expect either the klass to be erroneous or verification failed at
4087 // compile time.
4088 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004089 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004090 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004091 } else {
4092 CHECK(Runtime::Current()->IsCompiler());
4093 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004094 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004095 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004096 } else {
4097 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004098 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004099 }
4100
Brian Carlstromd1422f82011-09-28 11:37:09 -07004101 // If the class is kStatusInitializing, either this thread is
4102 // initializing higher up the stack or another thread has beat us
4103 // to initializing and we need to wait. Either way, this
4104 // invocation of InitializeClass will not be responsible for
4105 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004106 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004107 // Could have got an exception during verification.
4108 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004109 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004110 return false;
4111 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004112 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004113 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004114 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004115 return true;
4116 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004117 // No. That's fine. Wait for another thread to finish initializing.
4118 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004119 }
4120
4121 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004122 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004123 return false;
4124 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004125 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004126
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004127 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004128
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004129 // From here out other threads may observe that we're initializing and so changes of state
4130 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004131 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004132 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004133
4134 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004135 }
4136
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004137 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004138 if (!klass->IsInterface() && klass->HasSuperClass()) {
4139 mirror::Class* super_class = klass->GetSuperClass();
4140 if (!super_class->IsInitialized()) {
4141 CHECK(!super_class->IsInterface());
4142 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004143 StackHandleScope<1> hs(self);
4144 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004145 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004146 if (!super_initialized) {
4147 // The super class was verified ahead of entering initializing, we should only be here if
4148 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004149 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004150 << "Super class initialization failed for "
4151 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004152 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004153 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004154 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004155 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004156 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004157 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004158 return false;
4159 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004160 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004161 }
4162
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004163 const size_t num_static_fields = klass->NumStaticFields();
4164 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004165 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004166 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004167 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004168 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004169 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004170 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004171
4172 // Eagerly fill in static fields so that the we don't have to do as many expensive
4173 // Class::FindStaticField in ResolveField.
4174 for (size_t i = 0; i < num_static_fields; ++i) {
4175 mirror::ArtField* field = klass->GetStaticField(i);
4176 const uint32_t field_idx = field->GetDexFieldIndex();
4177 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4178 if (resolved_field == nullptr) {
4179 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004180 } else {
4181 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004182 }
4183 }
4184
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004185 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4186 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004187 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004188 ClassDataItemIterator field_it(dex_file, class_data);
4189 if (value_it.HasNext()) {
4190 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004191 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004192 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004193 StackHandleScope<1> hs2(self);
4194 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004195 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004196 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004197 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004198 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004199 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004200 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004201 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004202 }
4203 }
4204 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004205
Ian Rogersd91d6d62013-09-25 20:26:14 -07004206 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004207 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004208 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004209 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004210 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004211 }
4212
Ian Rogers7b078e82014-09-10 14:44:24 -07004213 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004214 uint64_t t1 = NanoTime();
4215
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004216 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004217 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004218 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004219
4220 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004221 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004222 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004223 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01004224 } else if (Runtime::Current()->IsTransactionAborted()) {
4225 // The exception thrown when the transaction aborted has been caught and cleared
4226 // so we need to throw it again now.
4227 LOG(WARNING) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
4228 << " without exception while transaction was aborted: re-throw it now.";
4229 Runtime::Current()->ThrowInternalErrorForAbortedTransaction(self);
4230 klass->SetStatus(mirror::Class::kStatusError, self);
4231 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004232 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004233 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4234 RuntimeStats* thread_stats = self->GetStats();
4235 ++global_stats->class_init_count;
4236 ++thread_stats->class_init_count;
4237 global_stats->class_init_time_ns += (t1 - t0);
4238 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004239 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004240 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004241 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004242 std::string temp;
4243 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004244 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004245 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004246 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004247 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004248 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004249 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004250 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004251}
4252
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004253bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004254 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004255 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004256 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004257 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004258 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004259 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004260
4261 // When we wake up, repeat the test for init-in-progress. If
4262 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004263 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004264 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004265 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004266 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004267 return false;
4268 }
4269 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004270 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004271 continue;
4272 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004273 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004274 // Compile time initialization failed.
4275 return false;
4276 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004277 if (klass->IsErroneous()) {
4278 // The caller wants an exception, but it was thrown in a
4279 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004280 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004281 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004282 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004283 return false;
4284 }
4285 if (klass->IsInitialized()) {
4286 return true;
4287 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004288 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004289 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004290 }
Ian Rogers07140832014-09-30 15:43:59 -07004291 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004292}
4293
Ian Rogersb5fb2072014-12-02 17:22:02 -08004294static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
4295 Handle<mirror::ArtMethod> method1,
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004296 Handle<mirror::ArtMethod> method2,
4297 std::string* error_msg)
Ian Rogersb5fb2072014-12-02 17:22:02 -08004298 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4299 {
4300 StackHandleScope<1> hs(self);
4301 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
Vladimir Marko862f43c2015-02-10 18:22:57 +00004302 mirror::Class* other_return_type = method2->GetReturnType();
4303 // NOTE: return_type.Get() must be sequenced after method2->GetReturnType().
4304 if (UNLIKELY(other_return_type != return_type.Get())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004305 *error_msg = StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
4306 PrettyClassAndClassLoader(return_type.Get()).c_str(),
4307 return_type.Get(),
4308 PrettyClassAndClassLoader(other_return_type).c_str(),
4309 other_return_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004310 return false;
4311 }
4312 }
4313 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4314 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4315 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004316 if (types2 != nullptr && types2->Size() != 0) {
4317 *error_msg = StringPrintf("Type list mismatch with %s",
4318 PrettyMethod(method2.Get(), true).c_str());
4319 return false;
4320 }
4321 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08004322 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004323 if (types1->Size() != 0) {
4324 *error_msg = StringPrintf("Type list mismatch with %s",
4325 PrettyMethod(method2.Get(), true).c_str());
4326 return false;
4327 }
4328 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08004329 }
4330 uint32_t num_types = types1->Size();
4331 if (UNLIKELY(num_types != types2->Size())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004332 *error_msg = StringPrintf("Type list mismatch with %s",
4333 PrettyMethod(method2.Get(), true).c_str());
Ian Rogersb5fb2072014-12-02 17:22:02 -08004334 return false;
4335 }
4336 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00004337 StackHandleScope<1> hs(self);
4338 Handle<mirror::Class> param_type(hs.NewHandle(
4339 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true)));
Ian Rogersb5fb2072014-12-02 17:22:02 -08004340 mirror::Class* other_param_type =
4341 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
Vladimir Marko862f43c2015-02-10 18:22:57 +00004342 // NOTE: param_type.Get() must be sequenced after method2->GetClassFromTypeIndex(...).
4343 if (UNLIKELY(param_type.Get() != other_param_type)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004344 *error_msg = StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
4345 i,
4346 PrettyClassAndClassLoader(param_type.Get()).c_str(),
4347 param_type.Get(),
4348 PrettyClassAndClassLoader(other_param_type).c_str(),
4349 other_param_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004350 return false;
4351 }
4352 }
4353 return true;
4354}
4355
4356
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004357bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004358 if (klass->IsInterface()) {
4359 return true;
4360 }
Ian Rogers151f2212014-05-06 11:27:27 -07004361 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004362 Thread* self = Thread::Current();
4363 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004364 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
4365 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004366 if (klass->HasSuperClass() &&
4367 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004368 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004369 h_m.Assign(klass->GetVTableEntry(i));
4370 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004371 if (h_m.Get() != super_h_m.Get()) {
4372 std::string error_msg;
4373 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
4374 ThrowLinkageError(klass.Get(),
4375 "Class %s method %s resolves differently in superclass %s: %s",
4376 PrettyDescriptor(klass.Get()).c_str(),
4377 PrettyMethod(h_m.Get()).c_str(),
4378 PrettyDescriptor(klass->GetSuperClass()).c_str(),
4379 error_msg.c_str());
4380 return false;
4381 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004382 }
4383 }
4384 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004385 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004386 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4387 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4388 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004389 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4390 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08004391 if (h_m.Get() != super_h_m.Get()) {
4392 std::string error_msg;
4393 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
4394 ThrowLinkageError(klass.Get(),
4395 "Class %s method %s resolves differently in interface %s: %s",
4396 PrettyDescriptor(klass.Get()).c_str(),
4397 PrettyMethod(h_m.Get()).c_str(),
4398 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str(),
4399 error_msg.c_str());
4400 return false;
4401 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004402 }
4403 }
4404 }
4405 }
4406 return true;
4407}
4408
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004409bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4410 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004411 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004412 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004413 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004414 return true;
4415 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004416 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004417 if (!success) {
4418 if (can_init_fields && can_init_parents) {
4419 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4420 }
4421 } else {
4422 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004423 }
4424 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004425}
4426
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004427void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4428 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4429 if (fields != nullptr) {
4430 for (int index = 0; index < fields->GetLength(); index ++) {
4431 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4432 fields->Get(index)->SetDeclaringClass(new_class);
4433 }
4434 }
4435 }
4436
4437 fields = new_class->GetSFields();
4438 if (fields != nullptr) {
4439 for (int index = 0; index < fields->GetLength(); index ++) {
4440 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4441 fields->Get(index)->SetDeclaringClass(new_class);
4442 }
4443 }
4444 }
4445
4446 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4447 if (methods != nullptr) {
4448 for (int index = 0; index < methods->GetLength(); index ++) {
4449 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4450 methods->Get(index)->SetDeclaringClass(new_class);
4451 }
4452 }
4453 }
4454
4455 methods = new_class->GetVirtualMethods();
4456 if (methods != nullptr) {
4457 for (int index = 0; index < methods->GetLength(); index ++) {
4458 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4459 methods->Get(index)->SetDeclaringClass(new_class);
4460 }
4461 }
4462 }
4463}
4464
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004465bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4466 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004467 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004468 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004469
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004470 if (!LinkSuperClass(klass)) {
4471 return false;
4472 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004473 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4474 self, Runtime::Current()->GetImtUnimplementedMethod());
4475 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004476 return false;
4477 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004478 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004479 return false;
4480 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004481 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004482 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004483 return false;
4484 }
4485 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004486 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004487
4488 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4489 // We don't need to retire this class as it has no embedded tables or it was created the
4490 // correct size during class linker initialization.
4491 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4492
4493 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004494 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004495 }
4496
4497 // This will notify waiters on klass that saw the not yet resolved
4498 // class in the class_table_ during EnsureResolved.
4499 klass->SetStatus(mirror::Class::kStatusResolved, self);
4500 *new_class = klass.Get();
4501 } else {
4502 CHECK(!klass->IsResolved());
4503 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004504 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004505 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004506 CHECK(self->IsExceptionPending()); // Expect an OOME.
4507 klass->SetStatus(mirror::Class::kStatusError, self);
4508 return false;
4509 }
4510
4511 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4512 StackHandleScope<1> hs(self);
4513 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4514 ObjectLock<mirror::Class> lock(self, new_class_h);
4515
4516 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4517
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004518 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4519 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004520 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004521
4522 // This will notify waiters on temp class that saw the not yet resolved class in the
4523 // class_table_ during EnsureResolved.
4524 klass->SetStatus(mirror::Class::kStatusRetired, self);
4525
4526 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4527 // This will notify waiters on new_class that saw the not yet resolved
4528 // class in the class_table_ during EnsureResolved.
4529 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004530 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004531 return true;
4532}
4533
Andreas Gampefd9eb392014-11-06 16:52:58 -08004534static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
4535 size_t* virtual_methods,
4536 size_t* direct_methods,
4537 size_t* static_fields,
4538 size_t* instance_fields) {
4539 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
4540
4541 while (dex_data.HasNextStaticField()) {
4542 dex_data.Next();
4543 (*static_fields)++;
4544 }
4545 while (dex_data.HasNextInstanceField()) {
4546 dex_data.Next();
4547 (*instance_fields)++;
4548 }
4549 while (dex_data.HasNextDirectMethod()) {
4550 (*direct_methods)++;
4551 dex_data.Next();
4552 }
4553 while (dex_data.HasNextVirtualMethod()) {
4554 (*virtual_methods)++;
4555 dex_data.Next();
4556 }
4557 DCHECK(!dex_data.HasNext());
4558}
4559
4560static void DumpClass(std::ostream& os,
4561 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
4562 const char* suffix) {
4563 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
4564 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
4565 os << " Static fields:\n";
4566 while (dex_data.HasNextStaticField()) {
4567 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4568 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4569 dex_data.Next();
4570 }
4571 os << " Instance fields:\n";
4572 while (dex_data.HasNextInstanceField()) {
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 << " Direct methods:\n";
4578 while (dex_data.HasNextDirectMethod()) {
4579 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4580 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4581 dex_data.Next();
4582 }
4583 os << " Virtual methods:\n";
4584 while (dex_data.HasNextVirtualMethod()) {
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}
4590
4591static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4592 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
4593 std::ostringstream os;
4594 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
4595 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
4596 return os.str();
4597}
4598
4599
4600// Very simple structural check on whether the classes match. Only compares the number of
4601// methods and fields.
4602static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4603 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
4604 std::string* error_msg) {
4605 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
4606 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
4607
4608 // Counters for current dex file.
4609 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
4610 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
4611 &dex_instance_fields1);
4612 // Counters for compile-time dex file.
4613 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
4614 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
4615 &dex_instance_fields2);
4616
4617 if (dex_virtual_methods1 != dex_virtual_methods2) {
4618 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4619 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
4620 dex_virtual_methods2, class_dump.c_str());
4621 return false;
4622 }
4623 if (dex_direct_methods1 != dex_direct_methods2) {
4624 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4625 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
4626 dex_direct_methods2, class_dump.c_str());
4627 return false;
4628 }
4629 if (dex_static_fields1 != dex_static_fields2) {
4630 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4631 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
4632 dex_static_fields2, class_dump.c_str());
4633 return false;
4634 }
4635 if (dex_instance_fields1 != dex_instance_fields2) {
4636 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4637 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
4638 dex_instance_fields2, class_dump.c_str());
4639 return false;
4640 }
4641
4642 return true;
4643}
4644
4645// Checks whether a the super-class changed from what we had at compile-time. This would
4646// invalidate quickening.
4647static bool CheckSuperClassChange(Handle<mirror::Class> klass,
4648 const DexFile& dex_file,
4649 const DexFile::ClassDef& class_def,
4650 mirror::Class* super_class)
4651 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4652 // Check for unexpected changes in the superclass.
4653 // Quick check 1) is the super_class class-loader the boot class loader? This always has
4654 // precedence.
4655 if (super_class->GetClassLoader() != nullptr &&
4656 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
4657 // which is implied by different dex cache.
4658 klass->GetDexCache() != super_class->GetDexCache()) {
4659 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
4660 // definition for the super-class, and (b) the files are in separate oat files. The oat files
4661 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
4662 const OatFile* class_oat_file = dex_file.GetOatFile();
4663 if (class_oat_file != nullptr) {
4664 const OatFile* loaded_super_oat_file = super_class->GetDexFile().GetOatFile();
4665 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
4666 // Now check (a).
4667 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
4668 if (super_class_def != nullptr) {
4669 // Uh-oh, we found something. Do our check.
4670 std::string error_msg;
4671 if (!SimpleStructuralCheck(dex_file, *super_class_def,
4672 super_class->GetDexFile(), *super_class->GetClassDef(),
4673 &error_msg)) {
4674 // Print a warning to the log. This exception might be caught, e.g., as common in test
4675 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
4676 // only save the type of the exception.
4677 LOG(WARNING) << "Incompatible structural change detected: " <<
4678 StringPrintf(
4679 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4680 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4681 class_oat_file->GetLocation().c_str(),
4682 loaded_super_oat_file->GetLocation().c_str(),
4683 error_msg.c_str());
4684 ThrowIncompatibleClassChangeError(klass.Get(),
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 return false;
4691 }
4692 }
4693 }
4694 }
4695 }
4696 return true;
4697}
4698
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004699bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004700 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004701 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4702 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004703 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004704 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004705 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004706 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004707 return false;
4708 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004709 // Verify
4710 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004711 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004712 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004713 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004714 return false;
4715 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004716 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004717 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08004718
4719 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
4720 DCHECK(Thread::Current()->IsExceptionPending());
4721 return false;
4722 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004723 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004724 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004725 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004726 for (size_t i = 0; i < interfaces->Size(); i++) {
4727 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004728 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004729 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004730 DCHECK(Thread::Current()->IsExceptionPending());
4731 return false;
4732 }
4733 // Verify
4734 if (!klass->CanAccess(interface)) {
4735 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004736 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004737 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004738 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004739 return false;
4740 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004741 }
4742 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004743 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004744 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004745 return true;
4746}
4747
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004748bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004749 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004750 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004751 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004752 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004753 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004754 return false;
4755 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004756 return true;
4757 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004758 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004759 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4760 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004761 return false;
4762 }
4763 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004764 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004765 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004766 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004767 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004768 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004769 return false;
4770 }
4771 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004772 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004773 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004774 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004775 return false;
4776 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004777
Brian Carlstromf3632832014-05-20 15:36:53 -07004778 // Inherit kAccClassIsFinalizable from the superclass in case this
4779 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004780 if (super->IsFinalizable()) {
4781 klass->SetFinalizable();
4782 }
4783
Elliott Hughes2da50362011-10-10 16:57:08 -07004784 // Inherit reference flags (if any) from the superclass.
4785 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4786 if (reference_flags != 0) {
4787 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4788 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004789 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004790 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004791 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004792 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004793 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004794 return false;
4795 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004796
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004797 if (kIsDebugBuild) {
4798 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004799 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004800 CHECK(super->IsResolved());
4801 super = super->GetSuperClass();
4802 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004803 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004804 return true;
4805}
4806
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004807// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004808bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004809 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4810 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004811 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004812 if (klass->IsInterface()) {
4813 // No vtable.
4814 size_t count = klass->NumVirtualMethods();
4815 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004816 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004817 return false;
4818 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004819 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004820 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004821 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004822 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4823 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004824 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004825 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004826}
4827
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004828// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4829// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4830// caches in the implementation below.
4831class MethodNameAndSignatureComparator FINAL : public ValueObject {
4832 public:
4833 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4834 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4835 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4836 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004837 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4838 }
4839
4840 const char* GetName() {
4841 if (name_ == nullptr) {
4842 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4843 }
4844 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004845 }
4846
4847 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4848 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4849 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4850 const DexFile* other_dex_file = other->GetDexFile();
4851 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4852 if (dex_file_ == other_dex_file) {
4853 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4854 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004855 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004856 uint32_t other_name_len;
4857 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4858 &other_name_len);
4859 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4860 return false;
4861 }
4862 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4863 }
4864
4865 private:
4866 // Dex file for the method to compare against.
4867 const DexFile* const dex_file_;
4868 // MethodId for the method to compare against.
4869 const DexFile::MethodId* const mid_;
4870 // Lazily computed name from the dex file's strings.
4871 const char* name_;
4872 // Lazily computed name length.
4873 uint32_t name_len_;
4874};
4875
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004876class LinkVirtualHashTable {
4877 public:
4878 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4879 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4880 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4881 }
4882 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4883 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4884 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004885 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004886 uint32_t index = hash % hash_size_;
4887 // Linear probe until we have an empty slot.
4888 while (hash_table_[index] != invalid_index_) {
4889 if (++index == hash_size_) {
4890 index = 0;
4891 }
4892 }
4893 hash_table_[index] = virtual_method_index;
4894 }
4895 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4896 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4897 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004898 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004899 size_t index = hash % hash_size_;
4900 while (true) {
4901 const uint32_t value = hash_table_[index];
4902 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4903 // the block and can safely assume not found.
4904 if (value == invalid_index_) {
4905 break;
4906 }
4907 if (value != removed_index_) { // This signifies not already overriden.
4908 mirror::ArtMethod* virtual_method =
4909 klass_->GetVirtualMethodDuringLinking(value);
4910 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4911 hash_table_[index] = removed_index_;
4912 return value;
4913 }
4914 }
4915 if (++index == hash_size_) {
4916 index = 0;
4917 }
4918 }
4919 return GetNotFoundIndex();
4920 }
4921 static uint32_t GetNotFoundIndex() {
4922 return invalid_index_;
4923 }
4924
4925 private:
4926 static const uint32_t invalid_index_;
4927 static const uint32_t removed_index_;
4928
4929 Handle<mirror::Class> klass_;
4930 const size_t hash_size_;
4931 uint32_t* const hash_table_;
4932};
4933
4934const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4935const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4936
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004937bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004938 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004939 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004940 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4941 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004942 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004943 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004944 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004945 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4946 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4947 if (UNLIKELY(vtable.Get() == nullptr)) {
4948 CHECK(self->IsExceptionPending()); // OOME.
4949 return false;
4950 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004951 for (size_t i = 0; i < super_vtable_length; i++) {
4952 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004953 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004954 if (num_virtual_methods == 0) {
4955 klass->SetVTable(vtable.Get());
4956 return true;
4957 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004958 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004959 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4960 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4961 if (num_virtual_methods == 0) {
4962 klass->SetVTable(super_vtable);
4963 return true;
4964 }
4965 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004966 if (UNLIKELY(vtable.Get() == nullptr)) {
4967 CHECK(self->IsExceptionPending()); // OOME.
4968 return false;
4969 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004970 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004971 // How the algorithm works:
4972 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4973 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4974 // method which has not been matched to a vtable method, and j if the virtual method at the
4975 // index overrode the super virtual method at index j.
4976 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4977 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4978 // the need for the initial vtable which we later shrink back down).
4979 // 3. Add non overridden methods to the end of the vtable.
4980 static constexpr size_t kMaxStackHash = 250;
4981 const size_t hash_table_size = num_virtual_methods * 3;
4982 uint32_t* hash_table_ptr;
4983 std::unique_ptr<uint32_t[]> hash_heap_storage;
4984 if (hash_table_size <= kMaxStackHash) {
4985 hash_table_ptr = reinterpret_cast<uint32_t*>(
4986 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4987 } else {
4988 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4989 hash_table_ptr = hash_heap_storage.get();
4990 }
4991 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4992 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004993 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004994 hash_table.Add(i);
4995 }
4996 // Loop through each super vtable method and see if they are overriden by a method we added to
4997 // the hash table.
4998 for (size_t j = 0; j < super_vtable_length; ++j) {
4999 // Search the hash table to see if we are overidden by any method.
5000 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
5001 MethodNameAndSignatureComparator super_method_name_comparator(
5002 super_method->GetInterfaceMethodIfProxy());
5003 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5004 if (hash_index != hash_table.GetNotFoundIndex()) {
5005 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
5006 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
5007 super_method->GetAccessFlags())) {
5008 if (super_method->IsFinal()) {
5009 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5010 PrettyMethod(virtual_method).c_str(),
5011 super_method->GetDeclaringClassDescriptor());
5012 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005013 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005014 vtable->SetWithoutChecks<false>(j, virtual_method);
5015 virtual_method->SetMethodIndex(j);
5016 } else {
5017 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005018 << " would have incorrectly overridden the package-private method in "
5019 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005020 }
5021 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005022 }
5023 // Add the non overridden methods at the end.
5024 size_t actual_count = super_vtable_length;
5025 for (size_t i = 0; i < num_virtual_methods; ++i) {
5026 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
5027 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5028 if (method_idx < super_vtable_length &&
5029 local_method == vtable->GetWithoutChecks(method_idx)) {
5030 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005031 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005032 vtable->SetWithoutChecks<false>(actual_count, local_method);
5033 local_method->SetMethodIndex(actual_count);
5034 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005035 }
5036 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005037 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005038 return false;
5039 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005040 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005041 CHECK_LE(actual_count, max_count);
5042 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005043 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005044 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005045 CHECK(self->IsExceptionPending()); // OOME.
5046 return false;
5047 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005048 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005049 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005050 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005051 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005052 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005053 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5054 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005055 return false;
5056 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005057 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
5058 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005059 CHECK(self->IsExceptionPending()); // OOME.
5060 return false;
5061 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005062 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005063 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005064 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005065 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005066 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005067 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005068 }
5069 return true;
5070}
5071
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005072bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
5073 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
5074 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07005075 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005076 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005077 const bool has_superclass = klass->HasSuperClass();
5078 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
5079 const bool have_interfaces = interfaces.Get() != nullptr;
5080 const size_t num_interfaces =
5081 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
5082 if (num_interfaces == 0) {
5083 if (super_ifcount == 0) {
5084 // Class implements no interfaces.
5085 DCHECK_EQ(klass->GetIfTableCount(), 0);
5086 DCHECK(klass->GetIfTable() == nullptr);
5087 return true;
5088 }
Ian Rogers9bc81912012-10-11 21:43:36 -07005089 // Class implements same interfaces as parent, are any of these not marker interfaces?
5090 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005091 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005092 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005093 if (super_iftable->GetMethodArrayCount(i) > 0) {
5094 has_non_marker_interface = true;
5095 break;
5096 }
5097 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005098 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07005099 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005100 klass->SetIfTable(super_iftable);
5101 return true;
5102 }
5103 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005104 size_t ifcount = super_ifcount + num_interfaces;
5105 for (size_t i = 0; i < num_interfaces; i++) {
5106 mirror::Class* interface = have_interfaces ?
5107 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
5108 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005109 if (UNLIKELY(!interface->IsInterface())) {
5110 std::string temp;
5111 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
5112 PrettyDescriptor(klass.Get()).c_str(),
5113 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
5114 return false;
5115 }
5116 ifcount += interface->GetIfTableCount();
5117 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005118 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005119 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005120 CHECK(self->IsExceptionPending()); // OOME.
5121 return false;
5122 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005123 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005124 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005125 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005126 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07005127 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005128 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005129 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005130 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005131 // Flatten the interface inheritance hierarchy.
5132 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005133 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07005134 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
5135 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005136 // Check if interface is already in iftable
5137 bool duplicate = false;
5138 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005139 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005140 if (existing_interface == interface) {
5141 duplicate = true;
5142 break;
5143 }
5144 }
5145 if (!duplicate) {
5146 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07005147 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005148 // Add this interface's non-duplicate super-interfaces.
5149 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005150 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005151 bool super_duplicate = false;
5152 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005153 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005154 if (existing_interface == super_interface) {
5155 super_duplicate = true;
5156 break;
5157 }
5158 }
5159 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005160 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005161 }
5162 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005163 }
5164 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005165 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08005166 // Shrink iftable in case duplicates were found
5167 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005168 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005169 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005170 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005171 CHECK(self->IsExceptionPending()); // OOME.
5172 return false;
5173 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08005174 ifcount = idx;
5175 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005176 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005177 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005178 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07005179 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07005180 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005181 return true;
5182 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005183 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005184 size_t max_miranda_methods = 0; // The max size of miranda_list.
5185 for (size_t i = 0; i < ifcount; ++i) {
5186 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
5187 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005188 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005189 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005190 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
5191 hs.NewHandle(klass->GetVTableDuringLinking()));
5192 // Copy the IMT from the super class if possible.
5193 bool extend_super_iftable = false;
5194 if (has_superclass) {
5195 mirror::Class* super_class = klass->GetSuperClass();
5196 extend_super_iftable = true;
5197 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5198 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5199 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
5200 }
5201 } else {
5202 // No imt in the super class, need to reconstruct from the iftable.
5203 mirror::IfTable* if_table = super_class->GetIfTable();
5204 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5205 const size_t length = super_class->GetIfTableCount();
5206 for (size_t i = 0; i < length; ++i) {
5207 mirror::Class* interface = iftable->GetInterface(i);
5208 const size_t num_virtuals = interface->NumVirtualMethods();
5209 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5210 DCHECK_EQ(num_virtuals, method_array_count);
5211 if (method_array_count == 0) {
5212 continue;
5213 }
5214 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5215 for (size_t j = 0; j < num_virtuals; ++j) {
5216 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5217 if (method->IsMiranda()) {
5218 continue;
5219 }
5220 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5221 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5222 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5223 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5224 out_imt->SetReference(imt_index, method);
5225 } else if (imt_ref != conflict_method) {
5226 out_imt->SetReference(imt_index, conflict_method);
5227 }
5228 }
5229 }
5230 }
5231 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005232 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005233 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005234 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005235 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005236 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005237 const bool is_super = i < super_ifcount;
5238 const bool super_interface = is_super && extend_super_iftable;
5239 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5240 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5241 if (super_interface) {
5242 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5243 DCHECK(if_table != nullptr);
5244 DCHECK(if_table->GetMethodArray(i) != nullptr);
5245 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005246 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005247 AsObjectArray<mirror::ArtMethod>());
5248 // We are overwriting a super class interface, try to only virtual methods instead of the
5249 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005250 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005251 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005252 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005253 // A new interface, we need the whole vtable incase a new interface method is implemented
5254 // in the whole superclass.
5255 input_array = vtable;
5256 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005257 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005258 CHECK(self->IsExceptionPending()); // OOME.
5259 return false;
5260 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005261 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005262 if (input_array.Get() == nullptr) {
5263 // If the added virtual methods is empty, do nothing.
5264 DCHECK(super_interface);
5265 continue;
5266 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005267 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005268 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005269 MethodNameAndSignatureComparator interface_name_comparator(
5270 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005271 int32_t k;
5272 // For each method listed in the interface's method list, find the
5273 // matching method in our class's method list. We want to favor the
5274 // subclass over the superclass, which just requires walking
5275 // back from the end of the vtable. (This only matters if the
5276 // superclass defines a private method and this class redefines
5277 // it -- otherwise it would use the same vtable slot. In .dex files
5278 // those don't end up in the virtual method table, so it shouldn't
5279 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005280 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5281 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005282 mirror::ArtMethod* vtable_method_for_name_comparison =
5283 vtable_method->GetInterfaceMethodIfProxy();
5284 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005285 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005286 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005287 ThrowIllegalAccessError(
5288 klass.Get(),
5289 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005290 PrettyMethod(vtable_method).c_str(),
5291 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005292 return false;
5293 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005294 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005295 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005296 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5297 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5298 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5299 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5300 out_imt->SetReference(imt_index, vtable_method);
5301 } else if (imt_ref != conflict_method) {
5302 // If we are not a conflict and we have the same signature and name as the imt entry,
5303 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005304 MethodNameAndSignatureComparator imt_ref_name_comparator(
5305 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005306 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005307 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005308 out_imt->SetReference(imt_index, vtable_method);
5309 } else {
5310 out_imt->SetReference(imt_index, conflict_method);
5311 }
Jeff Hao88474b42013-10-23 16:24:40 -07005312 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005313 break;
5314 }
5315 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005316 if (k < 0 && !super_interface) {
5317 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005318 for (size_t l = 0; l < miranda_list_size; ++l) {
5319 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005320 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005321 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005322 break;
5323 }
5324 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005325 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005326 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005327 miranda_method = interface_method->Clone(self)->AsArtMethod();
5328 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005329 CHECK(self->IsExceptionPending()); // OOME.
5330 return false;
5331 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005332 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005333 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005334 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005335 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005336 }
5337 }
5338 }
5339 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005340 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005341 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005342 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005343 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5344 if (old_method_count == 0) {
5345 virtuals = AllocArtMethodArray(self, new_method_count);
5346 } else {
5347 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5348 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005349 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005350 CHECK(self->IsExceptionPending()); // OOME.
5351 return false;
5352 }
5353 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005354
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005355 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005356 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005357 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005358 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005359 CHECK(self->IsExceptionPending()); // OOME.
5360 return false;
5361 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005362 for (size_t i = 0; i < miranda_list_size; ++i) {
5363 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005364 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005365 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5366 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5367 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005368 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005369 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005370 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005371 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005372 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005373
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005374 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005375 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5376 for (int i = 0; i < check_vtable->GetLength(); ++i) {
5377 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005378 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005379 }
5380
Ian Rogers7b078e82014-09-10 14:44:24 -07005381 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005382 return true;
5383}
5384
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005385bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005386 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005387 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005388}
5389
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005390bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005391 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005392 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005393}
5394
Brian Carlstromdbc05252011-09-09 01:59:59 -07005395struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005396 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5397 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005398 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005399 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005400 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005401 // 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 -07005402 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5403 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005404 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005405 if (type1 == Primitive::kPrimNot) {
5406 // Reference always goes first.
5407 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005408 }
Vladimir Markod5777482014-11-12 17:02:02 +00005409 if (type2 == Primitive::kPrimNot) {
5410 // Reference always goes first.
5411 return false;
5412 }
5413 size_t size1 = Primitive::ComponentSize(type1);
5414 size_t size2 = Primitive::ComponentSize(type2);
5415 if (size1 != size2) {
5416 // Larger primitive types go first.
5417 return size1 > size2;
5418 }
5419 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5420 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005421 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005422 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5423 // by name and for equal names by type id index.
5424 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5425 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005426 }
5427};
5428
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005429bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005430 size_t* class_size) {
5431 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005432 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005433 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005434
Brian Carlstromea46f952013-07-30 01:26:50 -07005435 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005436 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005437
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005438 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005439 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005440 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00005441 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005442 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005443 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005444 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005445 CHECK(super_class->IsResolved())
5446 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005447 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005448 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005449 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005450
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005451 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005452
Brian Carlstromdbc05252011-09-09 01:59:59 -07005453 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005454 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005455 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005456 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005457 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005458 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005459 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005460 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005461 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005462 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005463 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5464 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005465
Fred Shih381e4ca2014-08-25 17:24:27 -07005466 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005467 size_t current_field = 0;
5468 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005469 FieldGaps gaps;
5470
Brian Carlstromdbc05252011-09-09 01:59:59 -07005471 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005472 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005473 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005474 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005475 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005476 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005477 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005478 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5479 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005480 MemberOffset old_offset = field_offset;
5481 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5482 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5483 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005484 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005485 grouped_and_sorted_fields.pop_front();
5486 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005487 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005488 field_offset = MemberOffset(field_offset.Uint32Value() +
5489 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005490 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005491 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5492 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005493 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5494 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5495 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5496 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005497 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5498 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005499 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005500
Elliott Hughesadb460d2011-10-05 17:02:34 -07005501 // 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 -07005502 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005503 // We know there are no non-reference fields in the Reference classes, and we know
5504 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005505 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005506 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005507 --num_reference_fields;
5508 }
5509
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005510 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005511 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005512 if (is_static) {
5513 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005514 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005515 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005516 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005517 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08005518 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
Jeff Haoc7d11882015-02-03 15:08:39 -08005519 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
5520 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartier2d721012014-11-10 11:08:06 -08005521 } else {
5522 std::string temp;
5523 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5524 size_t previous_size = klass->GetObjectSize();
5525 if (previous_size != 0) {
5526 // Make sure that we didn't originally have an incorrect size.
5527 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5528 }
5529 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005530 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005531 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005532 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005533
5534 if (kIsDebugBuild) {
5535 // Make sure that the fields array is ordered by name but all reference
5536 // offsets are at the beginning as far as alignment allows.
5537 MemberOffset start_ref_offset = is_static
5538 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5539 : klass->GetFirstReferenceInstanceFieldOffset();
5540 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5541 num_reference_fields *
5542 sizeof(mirror::HeapReference<mirror::Object>));
5543 MemberOffset current_ref_offset = start_ref_offset;
5544 for (size_t i = 0; i < num_fields; i++) {
5545 mirror::ArtField* field = fields->Get(i);
5546 if ((false)) { // enable to debug field layout
5547 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5548 << " class=" << PrettyClass(klass.Get())
5549 << " field=" << PrettyField(field)
5550 << " offset="
5551 << field->GetField32(mirror::ArtField::OffsetOffset());
5552 }
5553 if (i != 0) {
5554 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005555 // NOTE: The field names can be the same. This is not possible in the Java language
5556 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5557 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005558 }
5559 Primitive::Type type = field->GetTypeAsPrimitiveType();
5560 bool is_primitive = type != Primitive::kPrimNot;
5561 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5562 strcmp("referent", field->GetName()) == 0) {
5563 is_primitive = true; // We lied above, so we have to expect a lie here.
5564 }
5565 MemberOffset offset = field->GetOffsetDuringLinking();
5566 if (is_primitive) {
5567 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5568 // Shuffled before references.
5569 size_t type_size = Primitive::ComponentSize(type);
5570 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5571 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5572 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5573 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5574 }
5575 } else {
5576 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5577 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5578 sizeof(mirror::HeapReference<mirror::Object>));
5579 }
5580 }
5581 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5582 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005583 return true;
5584}
5585
Vladimir Marko76649e82014-11-10 18:32:59 +00005586// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005587void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005588 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005589 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005590 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005591 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005592 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005593 // Compute reference offsets unless our superclass overflowed.
5594 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5595 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005596 if (num_reference_fields != 0u) {
5597 // All of the fields that contain object references are guaranteed be grouped in memory
5598 // starting at an appropriately aligned address after super class object data.
5599 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5600 sizeof(mirror::HeapReference<mirror::Object>));
5601 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005602 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005603 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005604 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005605 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005606 reference_offsets |= (0xffffffffu << start_bit) &
5607 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005608 }
5609 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005610 }
5611 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005612 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005613}
5614
Mathieu Chartier590fee92013-09-13 13:46:47 -07005615mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005616 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005617 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005618 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005619 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005620 return resolved;
5621 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005622 uint32_t utf16_length;
5623 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005624 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005625 dex_cache->SetResolvedString(string_idx, string);
5626 return string;
5627}
5628
Mathieu Chartier590fee92013-09-13 13:46:47 -07005629mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005630 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005631 StackHandleScope<2> hs(Thread::Current());
5632 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5633 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005634 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5635}
5636
5637mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005638 Handle<mirror::DexCache> dex_cache,
5639 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005640 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005641 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005642 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005643 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005644 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005645 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005646 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005647 // TODO: we used to throw here if resolved's class loader was not the
5648 // boot class loader. This was to permit different classes with the
5649 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005650 dex_cache->SetResolvedType(type_idx, resolved);
5651 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005652 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005653 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005654 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005655 StackHandleScope<1> hs(self);
5656 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005657 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005658 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005659 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005660 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005661 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005662 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005663 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005664 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005665 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005666 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005667 return resolved;
5668}
5669
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005670mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005671 Handle<mirror::DexCache> dex_cache,
5672 Handle<mirror::ClassLoader> class_loader,
5673 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005674 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005675 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005676 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005677 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005678 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005679 return resolved;
5680 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005681 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005682 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005683 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005684 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005685 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005686 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005687 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005688 // Scan using method_idx, this saves string compares but will only hit for matching dex
5689 // caches/files.
5690 switch (type) {
5691 case kDirect: // Fall-through.
5692 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005693 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005694 break;
5695 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005696 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005697 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005698 break;
5699 case kSuper: // Fall-through.
5700 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005701 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005702 break;
5703 default:
5704 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005705 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005706 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005707 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005708 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005709 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005710 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005711 switch (type) {
5712 case kDirect: // Fall-through.
5713 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005714 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005715 break;
5716 case kInterface:
5717 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005718 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005719 break;
5720 case kSuper: // Fall-through.
5721 case kVirtual:
5722 resolved = klass->FindVirtualMethod(name, signature);
5723 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005724 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005725 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005726 // If we found a method, check for incompatible class changes.
5727 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005728 // Be a good citizen and update the dex cache to speed subsequent calls.
5729 dex_cache->SetResolvedMethod(method_idx, resolved);
5730 return resolved;
5731 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005732 // If we had a method, it's an incompatible-class-change error.
5733 if (resolved != nullptr) {
5734 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5735 } else {
5736 // We failed to find the method which means either an access error, an incompatible class
5737 // change, or no such method. First try to find the method among direct and virtual methods.
5738 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5739 const Signature signature = dex_file.GetMethodSignature(method_id);
5740 switch (type) {
5741 case kDirect:
5742 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005743 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005744 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5745 // have had a resolved method before, which triggers the "true" branch above.
5746 break;
5747 case kInterface:
5748 case kVirtual:
5749 case kSuper:
5750 resolved = klass->FindDirectMethod(name, signature);
5751 break;
5752 }
5753
5754 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005755 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005756 if (resolved != nullptr && referrer.Get() != nullptr) {
5757 mirror::Class* methods_class = resolved->GetDeclaringClass();
5758 mirror::Class* referring_class = referrer->GetDeclaringClass();
5759 if (!referring_class->CanAccess(methods_class)) {
5760 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5761 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005762 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005763 } else if (!referring_class->CanAccessMember(methods_class,
5764 resolved->GetAccessFlags())) {
5765 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005766 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005767 }
5768 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005769 if (!exception_generated) {
5770 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5771 // interface methods and throw if we find the method there. If we find nothing, throw a
5772 // NoSuchMethodError.
5773 switch (type) {
5774 case kDirect:
5775 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005776 if (resolved != nullptr) {
5777 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5778 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005779 resolved = klass->FindInterfaceMethod(name, signature);
5780 if (resolved != nullptr) {
5781 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5782 } else {
5783 ThrowNoSuchMethodError(type, klass, name, signature);
5784 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005785 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005786 break;
5787 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005788 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005789 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5790 } else {
5791 resolved = klass->FindVirtualMethod(name, signature);
5792 if (resolved != nullptr) {
5793 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5794 } else {
5795 ThrowNoSuchMethodError(type, klass, name, signature);
5796 }
5797 }
5798 break;
5799 case kSuper:
5800 if (resolved != nullptr) {
5801 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005802 } else {
5803 ThrowNoSuchMethodError(type, klass, name, signature);
5804 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005805 break;
5806 case kVirtual:
5807 if (resolved != nullptr) {
5808 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5809 } else {
5810 resolved = klass->FindInterfaceMethod(name, signature);
5811 if (resolved != nullptr) {
5812 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5813 } else {
5814 ThrowNoSuchMethodError(type, klass, name, signature);
5815 }
5816 }
5817 break;
5818 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005819 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005820 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005821 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005822 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005823 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005824}
5825
Mathieu Chartier590fee92013-09-13 13:46:47 -07005826mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005827 Handle<mirror::DexCache> dex_cache,
5828 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005829 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005830 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005831 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005832 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005833 return resolved;
5834 }
5835 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005836 Thread* const self = Thread::Current();
5837 StackHandleScope<1> hs(self);
5838 Handle<mirror::Class> klass(
5839 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005840 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005841 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005842 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005843 }
5844
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005845 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005846 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005847 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005848 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005849 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005850
Andreas Gampe58a5af82014-07-31 16:23:49 -07005851 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005852 const char* name = dex_file.GetFieldName(field_id);
5853 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5854 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005855 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005856 } else {
5857 resolved = klass->FindInstanceField(name, type);
5858 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005859 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005860 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005861 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005862 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005863 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005864 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005865 return resolved;
5866}
5867
Brian Carlstromea46f952013-07-30 01:26:50 -07005868mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005869 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005870 Handle<mirror::DexCache> dex_cache,
5871 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005872 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005873 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005874 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005875 return resolved;
5876 }
5877 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005878 Thread* self = Thread::Current();
5879 StackHandleScope<1> hs(self);
5880 Handle<mirror::Class> klass(
5881 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005882 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005883 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005884 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005885 }
5886
Ian Rogersdfb325e2013-10-30 01:00:44 -07005887 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5888 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005889 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005890 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005891 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005892 dex_cache->SetResolvedField(field_idx, resolved);
5893 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005894 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005895 }
5896 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005897}
5898
Brian Carlstromea46f952013-07-30 01:26:50 -07005899const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005900 uint32_t* length) {
5901 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5902 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005903 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005904 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005905 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005906}
5907
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005908void ClassLinker::DumpAllClasses(int flags) {
5909 if (dex_cache_image_class_lookup_required_) {
5910 MoveImageClassesToClassTable();
5911 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005912 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5913 // 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 -08005914 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005915 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005916 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005917 for (GcRoot<mirror::Class>& it : class_table_) {
5918 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005919 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005920 }
5921
5922 for (size_t i = 0; i < all_classes.size(); ++i) {
5923 all_classes[i]->DumpClass(std::cerr, flags);
5924 }
5925}
5926
Elliott Hughes956af0f2014-12-11 14:34:28 -08005927static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005928 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005929 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5930 base -= sizeof(void*); // Move backward so that code_offset != 0.
5931 const uint32_t code_offset = sizeof(void*);
5932 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005933}
5934
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005935bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5936 return (entry_point == GetQuickResolutionStub()) ||
5937 (quick_resolution_trampoline_ == entry_point);
5938}
5939
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005940bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5941 return (entry_point == GetQuickToInterpreterBridge()) ||
5942 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5943}
5944
5945bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5946 return (entry_point == GetQuickGenericJniStub()) ||
5947 (quick_generic_jni_trampoline_ == entry_point);
5948}
5949
5950const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5951 return GetQuickGenericJniStub();
5952}
5953
Elliott Hughes956af0f2014-12-11 14:34:28 -08005954void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5955 const void* method_code) const {
5956 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005957 oat_method.LinkMethod(method);
5958 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005959}
5960
5961void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5962 if (!method->IsNative()) {
5963 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005964 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5965 } else {
5966 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005967 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005968 oat_method.LinkMethod(method);
5969 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005970 }
5971}
5972
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005973void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005974 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005975 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005976 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005977 MoveImageClassesToClassTable();
5978 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005979 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005980 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5981 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005982}
5983
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005984size_t ClassLinker::NumLoadedClasses() {
5985 if (dex_cache_image_class_lookup_required_) {
5986 MoveImageClassesToClassTable();
5987 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005988 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005989 // Only return non zygote classes since these are the ones which apps which care about.
5990 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005991}
5992
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005993pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005994 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005995}
5996
5997pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005998 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005999}
6000
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08006001void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006002 DCHECK(!init_done_);
6003
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006004 DCHECK(klass != nullptr);
6005 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006006
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07006007 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006008 DCHECK(class_roots != nullptr);
6009 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07006010 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006011}
6012
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006013const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
6014 static const char* class_roots_descriptors[] = {
6015 "Ljava/lang/Class;",
6016 "Ljava/lang/Object;",
6017 "[Ljava/lang/Class;",
6018 "[Ljava/lang/Object;",
6019 "Ljava/lang/String;",
6020 "Ljava/lang/DexCache;",
6021 "Ljava/lang/ref/Reference;",
6022 "Ljava/lang/reflect/ArtField;",
6023 "Ljava/lang/reflect/ArtMethod;",
6024 "Ljava/lang/reflect/Proxy;",
6025 "[Ljava/lang/String;",
6026 "[Ljava/lang/reflect/ArtField;",
6027 "[Ljava/lang/reflect/ArtMethod;",
6028 "Ljava/lang/ClassLoader;",
6029 "Ljava/lang/Throwable;",
6030 "Ljava/lang/ClassNotFoundException;",
6031 "Ljava/lang/StackTraceElement;",
6032 "Z",
6033 "B",
6034 "C",
6035 "D",
6036 "F",
6037 "I",
6038 "J",
6039 "S",
6040 "V",
6041 "[Z",
6042 "[B",
6043 "[C",
6044 "[D",
6045 "[F",
6046 "[I",
6047 "[J",
6048 "[S",
6049 "[Ljava/lang/StackTraceElement;",
6050 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08006051 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
6052 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07006053
6054 const char* descriptor = class_roots_descriptors[class_root];
6055 CHECK(descriptor != nullptr);
6056 return descriptor;
6057}
6058
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006059std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
6060 const {
6061 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006062 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006063}
6064
6065bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
6066 const GcRoot<mirror::Class>& b) {
6067 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
6068 return false;
6069 }
6070 std::string temp;
6071 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
6072}
6073
6074std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
6075 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006076 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006077}
6078
6079bool ClassLinker::ClassDescriptorHashEquals::operator()(
6080 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
6081 if (a.Read()->GetClassLoader() != b.second) {
6082 return false;
6083 }
6084 return a.Read()->DescriptorEquals(b.first);
6085}
6086
6087bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
6088 const char* descriptor) {
6089 return a.Read()->DescriptorEquals(descriptor);
6090}
6091
6092std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006093 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08006094}
6095
Sebastien Hertz6963e442014-11-26 22:11:27 +01006096bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
6097 // Non-image methods don't use direct code pointer.
6098 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
6099 return false;
6100 }
6101 if (m->IsPrivate()) {
6102 // The method can only be called inside its own oat file. Therefore it won't be called using
6103 // its direct code if the oat file has been compiled in PIC mode.
6104 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
6105 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
6106 const OatFile::OatDexFile* oat_dex_file = class_linker->FindOpenedOatDexFileForDexFile(dex_file);
6107 if (oat_dex_file == nullptr) {
6108 // No oat file: the method has not been compiled.
6109 return false;
6110 }
6111 const OatFile* oat_file = oat_dex_file->GetOatFile();
6112 return oat_file != nullptr && !oat_file->IsPic();
6113 } else {
6114 // The method can be called outside its own oat file. Therefore it won't be called using its
6115 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
6116 ReaderMutexLock mu(Thread::Current(), dex_lock_);
6117 for (const OatFile* oat_file : oat_files_) {
6118 if (!oat_file->IsPic()) {
6119 return true;
6120 }
6121 }
6122 return false;
6123 }
6124}
6125
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006126} // namespace art